How to use PHP to create a website menu with dynamic highlighting?

I need to change the color of the selected menu when this page is active, and it should remain until another menu is pressed. I used jquery as

$('.navigation ul li a').click(function(){

 $(this).css({"background-color":"#ffffff"});
 $('.navigation ul li a').css({"background":"transparent"});

});

But it only works for the click only function. I need it to be active until I switch to another menu .plz help !!!

+3
source share
4 answers

PHP only

Suppose your website has the following menu:

  • home
  • Guns
  • Rifles

At the top of the HTML home page, paste:

<?php $this_page = "Home"; ?>

At the top of the HTML Pistols page, type:

<?php $this_page = "Pistols"; ?>

At the top of the HTML Rifles page, type:

<?php $this_page = "Rifles"; ?>

css , . #cur_item, .

HTML- :

<ul class="navigation">
    <li <?php if ($this_page == "Home"):?> id="cur_item" <?php endif; ?> >
        Home
    </li>
    <li <?php if ($this_page == "Pistols"):?> id="cur_item" <?php endif; ?> >
        Pistols
    </li>
    <li <?php if ($this_page == "Rifles"):?> id="cur_item" <?php endif; ?> >
        Rifles
    </li>
</ul>
+1

jQuery, CSS.

  • i.e. body id = "contact"
  • ,
  • CSS :

body#home .navigation ul li a.home, 
body#services .navigation ul li a.services,
body#contact .navigation ul li a.contact {
    background-color: #ffffff
}

0

To do this, use the css tag a:activeto

0
source
$('.navigation ul li a').click(function () {

    $('.navigation ul li a').each(function () { // loop through all links
       if ($(this).hasClass('active')) $(this).removeClass('active'); // remove className 'active' from any link
    });

    $(this).addClass('active'); // className active to current link
});

CSS

.navigation ul li a {
    background: transparent;
}

.navigation ul li a.active {
    background-color: #ffffff;
}
0
source

Source: https://habr.com/ru/post/1787683/


All Articles