Button triggers the method of your container

1

I created a tab that opens and closes using jQuery and I'm having some problems closing it:

HTML

<div id="aba" style="position: absolute">
    <img src="#"/>
    <span id="fechar">X</span>
</div>

jQuery

var fechado = true;
$("#aba").click(function(){
    if (fechado){
        $("#aba").animate({left: "10px"});
        fechado = false;
    }
});
$("#fechar").click(function(){
    if (fechado == false){
        $("#aba").animate({left: "0px"});
        fechado = true;
    }
});

What happens is that when I click on close, it probably understands that it is clicking on open as well; that is, it closes and opens soon after. I tried to use a flag but unsuccessfully. The real problem is that I can not remove the close button from inside the flap.

    
asked by anonymous 04.07.2014 / 05:55

1 answer

4

As the #fechar div is within the% d%, the browser understands that when you click #aba , you intend to click on it as well as the element that is "behind" it, in this case, #fechar %. What you should do to avoid this is stop the click event propagation . In the code, this looks like this:

var fechado = true;
$("#aba").click(function(){
    if (fechado){
        $("#aba").animate({left: "10px"});
        fechado = false;
    }
});

$("#fechar").click(function(e){ // Recebe o evento como parâmetro do listener
    if (fechado == false){
        $("#aba").animate({left: "0px"}); // Você tem que fechar a #aba, não o #fechar
        fechado = true;
    }
    e.stopPropagation(); // Manda o navegador parar de "subir o evento" para os próximos elementos.
});

Note also that instead of closing the tab, you were "closing" your button that was just a trigger: #aba .

JsFiddle (open the console to view test messages)

    
04.07.2014 / 07:04