Detect event click out of element

Asked

Viewed 395 times

1

I’m learning how to make tooltips, I even played some previous questions here in the OS, but I came up with a new question; When I click off the element that has the tooltip, it could close the tooltip, how can I do this?

Current code:

HTML

<div class="banner-tooltips" id="banner-tooltips">
    <span id="primeira-tooltip">1°</span>
    <span id="segunda-tooltip">2°</span>
    <span id="terceira-tooltip">3°</span>
    <span id="quarta-tooltip">4°</span>
</div>

JS

//Tooltips
function tooltips(){
    var caixaTooltips=document.getElementById("banner-tooltips");
    var tooltips=caixaTooltips.querySelectorAll("span");
    for(var i=0;i<tooltips.length;i++){
        tooltips[i].addEventListener("click",function(){
            var anterior=document.getElementsByClassName("banner-tooltip-active");
            if(anterior.length){
                for(var i=0;i<anterior.length;i++){
                    anterior[i].classList.remove("banner-tooltip-active");
                }
            }
            this.classList.add("banner-tooltip-active");
        });
    }
}
tooltips();
//\.Tooltips

1 answer

2


You can use the property target in the click of the document:

window.addEventListener('click', function(e) {
    if (!document.getElementById('banner-tooltips').contains(e.target)) {
        var anterior = document.getElementsByClassName("banner-tooltip-active");
        if (anterior.length) {
            for (var i = 0; i < anterior.length; i++) {
                anterior[i].classList.remove("banner-tooltip-active");
            }
        }
    }
});
  • I edited the reply @Murilogambôa, see this way.

  • 1

    perfect :D thank you so much again man

Browser other questions tagged

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