Home > OS >  Mark clicked menu item as active
Mark clicked menu item as active

Time:06-15

So I was wondering how to make the menu item that has been clicked, shown as 'active'/'highligted', so the user can see which page they are on?

I've made this menu bar.

/* Add a black background color to the top navigation */

.topnav_menu {
    background-color: #333;
    overflow: hidden;
    display: flex;
    align-items: center;
}


/* Style the links inside the navigation bar */

.topnav_menu a {
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
    cursor: pointer;
}


/* Change the color of links on hover */

.topnav_menu a:hover,
.engine_dropdown:hover .engine_dropbtn {
    background-color: #ebebeb;
    color: black;
}
<div >
  <a href="#profile">Profile</a>
  <a href="#index">Test Runs</a>
  <a href="#dashboard">Dashboard</a>
  <a href="#dbOperations">TRT Tools</a>
</div>

After the item has been clicked it should appear highlighted.

EDIT

So I created a solution, but is that the best way?

CodePudding user response:

Created this function to check which page in on, and then if im on that page, I would set the class to active

function active($currect_page){
    $url = basename(getcwd())."/".str_replace(".php", "", basename($_SERVER['PHP_SELF'])); // If filename is just "name" or "name.php"
    // Also checks which directory the file is in, to avoid highlighting multiple menu items with same name
    // $currect_page == $url :: parentFolder/fileName == parentFolder/fileName (without .php here)
    if($currect_page == $url || $currect_page == basename(getcwd())."/".basename($_SERVER['PHP_SELF'])){
        echo 'active'; // class name in css
    }
}
<div >
    <a href="profile" ><div id="imgDiv"></div></a>
    <a href="index" >Test Runs</a>
    <a href="dashboard" >Dashboard</a>
    <a href="dbOperations" >TRT Tools</a>
</div>

active class would look like this

/* Active menu item */

.topnav_menu a.active {
    /* When a-tags inside this class has been clicked */
    background-color: #ffffff;
    color: black;
}

CodePudding user response:

Based on how you have written the HTML, bellow js will solve the problem.

//JS
let a = document.querySelectorAll('a')

for(let i =0; i< a.length; i  ){
    a[i].onclick = function(){
        a.forEach(function(item){
          item.classList.remove("active");
      });
        this.classList.add("active");
    }
}
  • Related