简体   繁体   中英

How to hide tooltips using JavaScript (not jQuery)

I created my tooltips using this website:

http://www.w3schools.com/howto/howto_css_tooltip.asp

Now I'm wondering how would I close the tooltip after an arbitrary amount of time using a vanilla javascript solution.

My solution so far:

window.setTimeout(closeTooltips(), 700);

function closeTooltips(){
    document.getElementsByClassName('tooltipText').style.display="none";
}

I understand why this is not working but I'm unable to see a solution. I could iterate through the NodeList that getElementsByClassName returns and hide each individual one but I feel that is probably not an ideal solution.

You were close, but with setTimeout , you aren't trying to invoke the function, you are only trying to reference it, so don't include the parenthesis (which are the "invocation operator" in JavaScript):

setTimeout(closeTooltips, 700);

Next, you need to iterate all the elements found by your DOM query and set their styles individually, like this:

function closeTooltips(){
    var elems = document.querySelectorAll('.tooltipText');

    elems.forEach(function(el){
      el.style.display = "none";
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM