Detect event click out of element

1

I'm learning to do tooltips, I've even thrown some previous doubts here in the OS, but I ended up with a new question; When I click outside the element that has the tooltip, it could close the tooltip, how can I do that?

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
    
asked by anonymous 22.03.2017 / 13:48

1 answer

2

You can use the target property in 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");
            }
        }
    }
});
    
22.03.2017 / 13:52