Question

I've a set of links on a page that toggle divs. When the link is clicked it adds "active" to the required div and toggles it - I also toggle any existing active div - however what I can't get to work is the removal of the "active" class so it will not toggle again.

<a href="valor" class="mas">link</a>
<a href="acaba" class="mas">link</a>
<a href="soluc" class="mas">link</a> 

<div id ="content">   
<div class="valor">TEXT</div>
<div class="acaba">TEXT</div>
<div class="soluc">TEXT</div> 
</div>

$(".mas").click(function () {
    var divToShow = "." + $(this).attr('href');
    $(".active").toggle("fast");
    $("#content div").removeClass(".active");
    $(divToShow).toggle("fast");
    $(divToShow).addClass("active");
    return false;
});
Was it helpful?

Solution

Just need to remove . from the value of removeClass since removeClass takes the className and .active is not a classname (I think you meant to provide a selector).

$("#content div").removeClass(".active");

should be

$("#content div").removeClass("active");

Just another approach:

HTML:- Add a data-target attribute and provide the selector there.

 <a href="#" data-target=".valor" class="mas">link</a>  
 <a href="#" data-target=".acaba" class="mas">link</a>
 <a href="#" data-target=".soluc" class="mas">link</a> 
<div id="content">
    <div class="valor">TEXT1</div>
    <div class="acaba">TEXT2</div>
    <div class="soluc">TEXT3</div>
</div>

JS:

   $(".mas").click(function () {
       var divToShow = $(this).data('target');
       $('#content').children().not( //Hide all the children
              $(divToShow).toggle('fast').addClass('active') //But not the target which you do a toggle
       ).hide("fast").removeClass('active');
       return false;
   });

Demo

OTHER TIPS

removeClass() does not require the selector prerequisite.

It might also be better for memory usage to add .active to your select:

$('#content div.active').removeClass('active');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top