Clearing Class using Jquery prior using toggleClass

149 Views Asked by At

Initial - UPDATE:

HTML:

<li class="span3 trainer-profiles active">
    <aside class="trainer-info">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur, fugit hic ex delectus fugiat quidem atque esse. Quod, pariatur, voluptatem.</p>
    </aside>

    <img src="/img/placeholder/trainer-pic.png" alt="" class="trainer-pic">
        <h2 class="trainer-name">name</h2>
        <a href="#" class="trainer-icon"></a>
</li>

JS:

$(".trainer-profiles > a.trainer-icon").on("click", function(e){
    e.preventDefault();
    $(this).parent().toggleClass("active");
});
$(".trainers-view-all").on("click", function(e){
    e.preventDefault();
    $(".trainer-profiles").siblings().toggleClass("active");
});

As you can see one section shows the immediate child of the click. The other shows all. However if the class "active" is already present, as the other block of code gets called the script removes the "active" due to the toggleClass api.

What is the quickest way of removing all the prior active classes before using the toggleClass api. As at the moment any class with an active class present gets removed as the others get "active" added.

Any help is welcome :)

Many thanks!

------> Solution

&.show-all{
    @extend .trainer-profiles.active;
}

Created a new class, extending the prior class gives me the same result.

jQuery:

$(".trainers-view-all").on("click", function(e){
    e.preventDefault();
    $(".trainer-profiles").siblings().toggleClass("show-all");
});

By adding the .show-all class on toggle, I mimicked the class behavior and as it sits within a toggleClass. When the class gets removed it is does not negate the initial .active class.

I am pretty sure I could get the jQuery to a smaller state but it is effective at present.

1

There are 1 best solutions below

3
On

here we are not looking to toggle the state... just add the active class to all elements since the option says viewAll

$(".trainer-profiles > a.trainer-icon").on("click", function(e){
    e.preventDefault();
    $(this).parent().toggleClass("active");
});
$(".trainers-view-all").on("click", function(e){
    e.preventDefault();
    $(".trainer-profiles").addClass("active");
});