Button triggers the method of your container

Asked

Viewed 110 times

1

I created a tab that opens and closes using jQuery and am 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 the close, it probably understands that it is clicking on the open as well; that is, it closes and opens right away. I tried to use a flag, but without success.
The real problem is that I can’t take the close button out from inside the tab.

  • I think the error is in not changing the value of the variable fechado , try to add below the $("#aba").animate({left: "10px"}); one fechado = false

  • Since the span is below the DIV, possibly it is superimposed by it, that is, you think you are clicking on the span but you are clicking on the DIV. Try to change the location or use z-index.

  • @Hermesautran, my fault, I forgot to put in the code, but there is.

  • @Ascension, it didn’t work.

  • 2

    Another thing, you shouldn’t take the animate of $("#aba") instead of $("#fechar"). Like the span is inside the div, if you hide it all will hide too. Try $("#aba").animate({left: "0px"}); instead of $("#fechar").animate({left: "0px"});

  • Again, it’s like closing the tab, I misspelled.

Show 1 more comment

1 answer

4


Like the div #fechar is inside the div #aba, the browser understands that when you click on #fechar, you intend to click both on it and on the element that is "behind" it, in this case, the #aba. What you must do to avoid this is stop the spread of the click event. In the code, it goes 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.
});

Also note that instead of closing the tab, you were "closing" your button which was just a Rigger: $("#fechar").animate({left: "0px"});.

Jsfiddle (open the console to view test messages)

  • It worked perfectly. As for the "close the button", it was my fault, here I wrote #fechar, but there in the code is #aba.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.