0

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.

1
  • Iterating through the elements will definitely be necessary. Commented Feb 1, 2017 at 14:37

1 Answer 1

3

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";
    });
}
Sign up to request clarification or add additional context in comments.

4 Comments

This is correct, but the function will still need to iterate through the elements if it's going to work.
@Pointy Yes, I was working on that as you commented.
OK, but note that not all browsers equip NodeList instances with a .forEach() method.
Scott, I deleted my answer. When you posted yours, you hadn't included anything about iteration (you'll note that your edit time and my posting time were nearly identical). I've removed mine as the forEach on a NodeList was also functionally incorrect. Please accept the upvote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.