April 26, 2012

Add class to link

Question by Danis

I need help with links. I have this kind of links

 <a class="campusIcon km-icon" onclick ="window.location.href='indexHome.html'" data-rel="external">Campus</a>

 <a class="searchIcon km-icon"  onclick ="window.location.href='indexListView.html'"  data-rel="external">Search</a>

 <a class="mapIcon km-icon"  onclick ="window.location.href='indexKBlock.html'"  data-rel="external">Map</a>

 <a class="favIcon km-icon" onclick ="window.location.href='indexChart.html'" data-rel="external">Fav</a>

I need add class km-state-active to this links. if I add class oncklick event, then I get my class added but location.href does not work. So what’s a problem, and how to solve it?

Answer by Starx

You shouldn’t use inline script. its a bad practice. Update you markup to look similar to this.

<a class="campusIcon km-icon" href ="indexHome.html" data-rel="external">Campus</a>

And use jQuery to add the class on click

$("a").on('click', function() {
    $(this).addClass("km-state-active");
});
...

Please fill the form - I will response as fast as I can!