Jacob
Jacob

Reputation: 51

add class to li by clicking on a link from nav menu

I'm a newbie so i hope my question will have some logic :)

i wish to add a class "active" to "li" (in this case a portfolio filter item in the page) by clicking on a link from the nav menu. the "li" is not a part of the nav menu, how do i assign a "li" with a class if the "li" is in the deep tree - it's a whole different part of my site.

the "li" is in:
<div class=""section"
<ul id="portfolio-filter" class="list-inline">
        <li <--- the place i wish the "active" be added

i have checked other question but couldn't figure out how to implement the specific need. thanks for the help

Upvotes: 0

Views: 120

Answers (2)

UmairKhan
UmairKhan

Reputation: 108

First you have to specify .active in your CSS.

.active {
//add styles here
}

Then using javascript you have to grab #myLI and set class .active to it using onclick event:

 var  element = document.getElementById("myLI");
 element.onclick = function() {
               element.setAttribute('class','active');
            }

Upvotes: 0

user2274060
user2274060

Reputation: 904

You have to create a listener for the link of the menu. In JQuery, to create a listener, you have the 'on' function.

Example :

$("myElement").on("click",function(){});

After that, add an id attribute for the 'li' tag.

For example:

<li id="myLI">

So, when the user will click on the link of the menu, it will go to the listener. And in the listener, you will do :

$("#myLI").addClass("active") 

Don't forget to create the css class.

Upvotes: 1

Related Questions