Search code examples
javascriptjqueryhtmlcssremoveclass

.removeClass() jQuery adds the removed class instantly


I'm having a issue here: http://jsfiddle.net/wkCV6/

When i click the contacto button it is ok and it opens properly. But when I click on volver, it removes the classes and immediately adds it again. I noticed this, when I put some alerts between the execution. You can see it in my jsfiddle.

Here is the JS I'm using.

$(function () {
    $("div.arrastre").on("click", function () {
        $(this).find("div.bloque").addClass("rotated");
        var esto = $(this);
        setTimeout(function () {
            esto.find("div.bloque div.back").addClass("agrandar");
            esto.addClass("agrandar")
        }, 100);
    });
});

$(function () {
    $("div#volver").on("click", function () {
        var esto = $(this);
        setTimeout(function () {
            esto.closest("div.bloque").removeClass("rotated");
            if (esto.closest("div.back").hasClass("agrandar")) {
                esto.closest("div.back").removeClass("agrandar");
                alert("se supone que quité la clase agrandar en back ");
            };

            if (esto.closest("div.arrastre").hasClass("agrandar")) {
                esto.closest("div.arrastre").removeClass("agrandar");
                alert("se supone que quité la clase agrandar en arrastre");
            };
        }, 100);
    });
});

Solution

  • When you click div#volver, the click event is dispatched and bubbles up to the document, triggering on every ancester.

    You trigger the call back that you first set on div.arrastre because it's a parent of #volver.

    setTimeout is called, causing the class to be added 100ms after the click on #volver.

    To prevent a click event from bubbling, you can just return false; in the set callback or stopPropagation :

    $("div#volver").on("click",function(event){
        // your code
        event.stopPropagation();
        return false;
    }
    

    Working fiddle