John Davidson

javascript - Active menu background is not showing after reload

0 comments
Message:


I have created 2 menus called "Habit Setting" and "Team Setting"


But after clicking on second menu the page is reloading and the menu background is not going to second menu. There is always showing menu background of the first menu. Would like to have a better solution for that.


Here is my code -


<?php
defined('ABSPATH') or exit;

// TODO: Refactor tabs
?>

<div id="myDIV">
<nav class="bp-navs bp-subnavs no-ajax user-subnav" id="subnav" role="navigation" aria-label="Sub Menu">
<ul class="subnav">

<li class="bp-personal-sub-tab current selected">
<a href="<?php echo site_url('settings/habit-settings/'); ?>" class="btn active"> Habit Setting </a>
</li>

<li class="bp-personal-sub-tab current">
<a href="<?php echo site_url('settings/team-settings/'); ?>" class="btn"> Team Setting </a>
</li>


</ul>
</nav>
</div><!-- .item-list-tabs#subnav -->


<!-- Add active class to the current list -->

<style>

.btn {
outline: none !important;
cursor: pointer !important;
}

.active, .btn:hover {
background-color: red !important;
color: red;
}

</style>

<script>
var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
</script>

I was trying to show active menu color through JS but my code doesn't work.



My Answer:
One possible solution is to store the active menu item in the browser's local storage and then retrieve it on page load to set the active class accordingly. Here's an updated version of your code:

html
defined('ABSPATH') or exit;

// TODO: Refactor tabs
?>











This code will store the active menu item in the local storage when it is clicked and retrieve it on page load to set the active class accordingly. This way, even after a page reload, the active menu background will be maintained.

Rate this post

4 of 5 based on 4859 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us