Skip to content Skip to sidebar Skip to footer

Active Link After Click

I cant find a way to add a class to an 'a' element of a nav bar. This is the html nav and the jQuery (applied to test.html url only, to test it): This isnt working, it just doesn

Solution 1:

Why not use then anchors:active state:

a:active {
     /* your .active styles */
}

Solution 2:

You code is not working as you are trying to set class on some link using javascript, and then navigating same time. So thing is the part where you are changing class for link is working actually, however you are not able to see it as after navigation html will be reloaded.

To solve this problem , you need write a common function for updating the class of link, in your common html. However, call that function from the html being loaded at onload event instead of calling at click.

Your common js or html will be having function :-

highlightlink(linkid){
   $("a[href=' + linkid +']").addClass("active");
}

Each html will call this functin onload with respective htmlname. For example test.html will hat this code :-

$(document).ready( function (){
  highlightlink('test.html')
});
});

While index.html will have :-

 $(document).ready( function (){
  highlightlink('index.html')
});
});

Once your html is loaded, the that particular html will loaded

Solution 3:

Do you really need to add a class to the html element? If it's about styling I think it might be possible to solve your styling using a simple :active pseudo selector. See example below:

li:active {
  background-color: #f99;
}

lia:active {
  color: #fff;
}
<nav><ul><li><ahref="index.html">Inicio</a></li><li><ahref="test.html">Test</a></li><li><ahref="#">Item</a></li><li><ahref="test2.html"> test2</a></li></ul></nav>

Solution 4:

So what you can do is you can add a page link in the URL querystring like:

www.example.com/test.html?pageinfo=test.html

Now after the successful page loads you can retrieve page info from the query string and then you can add an active class to the anchor tag.

This way you will get querystring like this pageinfo=test.html and after successful parsing of querystring you will convert the information to {pageinfo:test.html}.

Using that you can add style/class to the anchor tag.

Solution 5:

Thanks to @Panther this is easier than i tought:

$(document).ready( function(){
var location = window.location.pathname;
location = location.replace("/", "");
$("a[href='"+location+"']").addClass("active");
});

Post a Comment for "Active Link After Click"