Close element when clicking any other part of page

Asked

Viewed 302 times

0

When the event is triggered, the element opens, but after that it does not close. How can I do so when clicking outside the "infoValor" the tooltype closes?

function formTips(){
    var infoValor=document.getElementById("info-input-valor");
    var tooltipValor=document.getElementById("tooltip-input-valor");
    infoValor.onclick=function(){
        if(tooltipValor.style.display!="block"){
            tooltipValor.style.display="block";
        }else{
            tooltipValor.style.display="none";
        }
    }
}formTips();

1 answer

1


This could be done easily with Tooltip jQuery, but how are you doing in Javascript pure, you will have to capture the event document click.
Then check if you clicked on any element outside your tooltip, and then hide the element. You can do so:

document.onclick = function(e){
    if(e.target.id != 'info-input-valor'){
        var tooltipValor=document.getElementById("tooltip-input-valor");
        tooltipValor.style.display="none";
    }
};

If you want you can also change the code you have already made and in the same function, see if the element id is your tooltip and display.

Browser other questions tagged

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