How to change element class by clicking tag binding link with jquery

Well, how can I change the class (active / inactive) of an element with an identifier associated with binding a binding tag with jquery?

HTML:

<a href="#element1">Show element 1</a> <a href="#element2">Show element 2</a> <div id="element1" class="active"><p>Element 1</p></div> <div id="element2" class="non_active"><p>Element 2</p></div> 

CSS

 .active{ visibility:visible; } .non_active{ visibility:hidden; } 

Thanks in advance!

+4
source share
5 answers

Try

 <a class="accordion-header" href="#element1">Show element 1</a> <a class="accordion-header" href="#element2">Show element 2</a> <div id="element1" class="element active"> <p>Element 1</p> </div> <div id="element2" class="element"> <p>Element 2</p> </div> 

then

 var $els = $('.element'); $els.not('.active').hide() $(".accordion-header").on("click", function (e) { var $target = $($(this).attr('href')).show() $els.not($target).hide() e.preventDefault(); }); 

Demo: Fiddle

+4
source

You can simply take href from the clicked element and use it as a selector:

 $("a").on("click", function() { $("div.active").toggleClass("active non-active"); $($(this).attr("href")).toggleClass("active non-active"); }); 
+2
source
 $("a").click(function(){ $(a).removeClass("active");// Nake all the existing links inactive by removing class active $(this).addClass("active"); //then make current link as active }); 
0
source

Is a non_active class non_active ? I would omit this, and then using jQuery I would do the following (advanced for reading):

 $('a').on('click', function(e){ e.preventDefault(); // prevent the default <a> behaviour var $elm = $(this), // store the clicked element activateElement = $elm.attr('href'); // get the value of the href attribute $('.active').removeClass('active'); // remove currently active element $(activateElement).addClass('active'); // set clicked element to active by removing non_active }); 

CSS

 div{ visibility: hidden; } .active{ visibility:visible; } 

Demo

0
source
 $("a").on("click", function() { var id = $(this).attr('href'); $('.active').removeClass('active'); // remove existing active $(id).addClass('active'); // set current link as active //or //$(id).attr('class','active'); // set current link as active }); 
0
source

All Articles