How to set class on clicking a link

I’m trying to get a list of links to show the active one as well as get the corresponding div the be active as well and all others to have the active class removed.

I’ve started to do that here: https://jsfiddle.net/k7qgwcjz/8/ but am not really getting anywhere with it and am not sure what I’m doing wrong so would be grateful for some help please

HI,

You don’t seem to be linking to jquery in that fiddle and you have brackets missing around the second ‘if’ section.

If you want to remove the active class then a simple way is to remove it from all list items in that section and then just add it to the current one.

e.g.

$('.links li').click(function() {
    $('.links li').removeClass("active");
    $(this).addClass("active");
});

Thanks, that’s great but is it possible for me to add a class the div with the same id as the hashtag and then remove it from all others too?

I’ve updated it: https://jsfiddle.net/k7qgwcjz/17/

Hi,

Do you mean something like this:

$('.links li').click(function() {
   var activeTab = $(this).find("a").attr("href"); 
    $('.links li').removeClass("active");
    $('.listContent').removeClass("tabon");
    $(this).addClass("active");
    $(activeTab).addClass('tabon');
});

CSS:

.listContent {
  display: none;
}
.listContent.tabon{display:block}

If you want the first div to show by default then add the tabon class to the first one.

e.g.

  <div class="listContent tabon" id="one">
    	<p>text for link 1</p>
	</div>

Thank you that’s exactly what I was after.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.