简体   繁体   中英

How to keep the active state of a link when the new page is loaded

I am developing a website using Bootstrap. I have a section with three buttons, each one of them leading to a different page of my website.

<div class="container-fluid filter-tag py-3">

    <ul class="tag-menu">
        <li><a href="<?php echo esc_attr( add_query_arg( 'tag', 'biella' ) ); ?>" class="btn"> Biella </a></li>
        <li><a href="<?php echo esc_attr( add_query_arg( 'tag', 'vercelli' ) ); ?>" class="btn"> Vercelli </a></li>
        <li><a href="<?php echo esc_attr( add_query_arg( 'tag', 'valsesia' ) ); ?>" class="btn"> Valsesia </a></li>
    </ul>
    

</div>

I've set the css active class so that, when a button (link) is clicked the background-color and color change, in order to let the user know which section of my website is currently on.

.tag-menu li a{
    border:1px solid $primary;
    border-radius:12px;
    padding:5px;
    margin-right:7px;
    color:#000000;
}
.tag-menu li a:active{
    border:1px solid $primary;
    background-color:$primary;
    border-radius:12px;
    padding:5px;
    margin-right:7px;
    color:#ffffff;
    box-shadow:none;
}

I can see, through the inspector, that the active class is set correctly, but when I click on one of the buttons, I see that the active class appears for just one second and then, when the new page is loaded, the button hasn't kept its active class. I'm aware of the fact that Stack is full of questions similar to mine and that I should probably use JQuery/JavaScript, but none of the solutions I've tried so far worked for me.

Could you please help me solving the problem?

Thank you very much!

:active is not a class, but a selector that catch the clicking moment (between the click and the release), so your CSS is added only for that instant. Here a small example:

 a:active{ color:red; }
 <a>link example</a>

In order to achieve what you wanted to do, you should use an event listener to add the class when the link is clicked:

 var links = document.querySelectorAll(".link"); for(link of links){ link.addEventListener("click", function(e){ for(inlink of links){ inlink.classList.remove("active"); } e.target.classList.add("active"); }); }
 .active { color:red; }
 <a class="link">link 1</a><br> <a class="link">link 2</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM