Search code examples
jquerytoggletoggleclasssiblings

JQuery toggleclass on click and disable when clicking on the other div or outside the div


I've been trying to find a JQuery script that does the following: Toggle enable/disable class once I click on the apply-class-here here div. It should also disable the class once you click outside of the div or click on one of the other apply class div's.

I already found a script that does exactly that, but I cannot seem to get it to work once the div is contained within a couple of other elements. (tile-wrapper > tile > apply-class-here)

<div class="tile-wrapper">
    <div class="tile">
        <div class="apply-class-here">Block</div>
    </div>
</div>
<div class="tile-wrapper">
    <div class="tile">
        <div class="apply-class-here">Block</div>
    </div>
</div>
<div class="tile-wrapper">
    <div class="tile">
        <div class="apply-class-here">Block</div>
    </div>
</div>
<div class="tile-wrapper">
    <div class="tile">
        <div class="apply-class-here">Block</div>
    </div>
</div>

This is the script I found, it only seems to work on elements which are not contained within any other elements like div's etc.

jQuery(document).ready(function($){ 
    $(function () {
            $('.apply-class-here').click(function(evt) {
            evt.stopPropagation();
            $(this).siblings().removeClass('overlay-active');
            $(this).toggleClass('overlay-active');
        });

        $(document).click(function() {
            $('.apply-class-here').removeClass('overlay-active');
        });
    });
});

I would really appreciate it if someone could help me solve this problem. I just cannot seem to get it to work the way I want it to work.


Solution

  • The problem is $(this).siblings().removeClass('overlay-active'); because apply-class-here are not siblings

    jQuery(function ($) {
        $('.apply-class-here').click(function (evt) {
            evt.stopPropagation();
            $('.overlay-active').not(this).removeClass('overlay-active');
            $(this).toggleClass('overlay-active');
        });
    
        $(document).click(function () {
            $('.apply-class-here').removeClass('overlay-active');
        });
    });
    

    Demo: Fiddle