javascript - adding specific class to element on click jquery -
i'm having trouble simple nav bar uses jquery add , remove specific class when page active. want class append alink class depending on id click. if click on #aboutlink
want .linkactive
added, if click on #saslink
want .link2active
added. tutorials i've looked @ have single class being added, since both classes different need specific 1 added depending on id click.
html:
<div id="mainnav"> <ul id="nav"> <a id="mainlogo" href="/"><li></li></a> <a id="aboutlink" class="alink" href="/"><li></li></a> <a id="saslink" class="alink" href="/savings-and-support"><li></li></a> <a id="external" href="/"><li></li></a> </ul> </div><!--/#mainnav-->
i know jquery doesn't make sense, it's come with. logically it, i'm lost on syntax.
jquery:
$(function () { $(".alink").click(function () { if ($(this) == $("#aboutlink") $(this).addclass('activelink'); else $(this).addclass('active2link'); }); });
thanks input or direction.
var idtoclass = { 'aboutlink' : 'linkactive', 'saslink' : 'link2active' } $('#nav a').click(function(){ e.preventdefault(); $(this).addclass(idtoclass[this.id]); });
you could, instead, use toggleclass()
allow classes removed second click:
var idtoclass = { 'aboutlink' : 'linkactive', 'saslink' : 'link2active' } $('#nav a').click(function(e){ e.preventdefault(); $(this).toggleclass(idtoclass[this.id]); });
edited in response question, op, in comments, below:
how remove class both links don't appear active @ same time?
there's few ways, because you're adding different class-names denote 'active' state, they're little inefficient. first approach use brute-force method, looking a
elements have class
attribute , setting attribute empty string, , then adding linkactive
/link2active
class-name clicked-on a
element:
$('#nav a').click(function(e){ e.preventdefault(); var self = $(this); self.closest('ul').find('a[class]').attr('class', ''); self.toggleclass(idtoclass[this.id]); });
the alternative remove specific classes elements have id
listed in idtoclass
object. is, however, expensive in needs iterate on object, retrieving id
, finding element with id
, then removing class
-name:
$('#nav a').click(function(e){ e.preventdefault(); (var id in idtoclass) { if (idtoclass.hasownproperty(id)){ $('#' + id).removeclass(idtoclass[id]); } } $(this).addclass(idtoclass[this.id]); });
if, of course, use common class-name becomes easier:
$('#nav a').click(function (e) { e.preventdefault(); var self = $(this); self.closest('ul') .find('.commonactiveclassname') .removeclass('commonactiveclassname'); self.addclass('commonactiveclassname'); });
references:
Comments
Post a Comment