4

How do I wait for an element to be displayed/seen by the user? I have the following function, but it only checks to see if the element exists and not whether it is visible to the user.

function waitForElementDisplay (selector, time) {
    if (document.querySelector(selector) != null) {
        return true;
    } else if (timeLimit < timeSince) {
        return false;
    } else {
        timeSince += time;
        setTimeout(function () {
            waitForElementDisplay(selector, time, timeLimit, timeSince);
        }, time);
    }
}
RPichioli
  • 3,245
  • 2
  • 25
  • 29
Chris Hansen
  • 7,813
  • 15
  • 81
  • 165
  • Possible duplicate of [Detect if an element is visible](http://stackoverflow.com/questions/8774089/detect-if-an-element-is-visible) – VLAZ Oct 03 '16 at 22:23
  • There is also another thing on it [here](http://stackoverflow.com/questions/16255423/finding-if-element-is-visible-javascript) and [here](http://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom) – VLAZ Oct 03 '16 at 22:25
  • 3
    define *"visible to user"* .. can be interpreted several ways – charlietfl Oct 03 '16 at 22:26
  • Possible duplicate of [How to tell if a DOM element is visible in the current viewport?](http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport) – Dekel Oct 04 '16 at 11:03

2 Answers2

2

It's a bit confuse, are you trying a simple "sleep"?

You can wait element load using:

document.querySelector(selector).onload = function() {
  // Your code ...
}

Some working snippet, run it:

// Triggering load of some element
document.querySelector("body").onload = function() {
  // Setting the timeout and visible to another element
    setTimeout(function () {
      document.querySelector("#my_element").style.display = "block" /* VISIBLE */
    }, 1000);
}
#my_element{
  width: 100px;
  height: 100px;
  background-color: red;
  display: none; /* INVISIBLE */
}
<div id="my_element"></div>

If you want to wait time as you have set to the function and the selector which should appear after this time.. You can mind about a simple setTimeout() and CSS.

Run the example below, hope it helps:

// Triggering, in my exemple i've used: WINDOW ONLOAD
window.onload = function() {
  waitForElementDisplay("#my_element", 1000);
}

function waitForElementDisplay (selector, time) {
  // Check the DOM Node in console
  console.log(document.querySelector(selector));
  
  // If it's a valid object
  if (typeof document.querySelector(selector) !== "undifined") {
    
    // Setting the timeout
    setTimeout(function () {
      document.querySelector(selector).style.display = "block" /* VISIBLE */
    }, time);
  }
}
#my_element{
  width: 100px;
  height: 100px;
  background-color: red;
  display: none; /* INVISIBLE */
}
<div id="my_element"></div>
RPichioli
  • 3,245
  • 2
  • 25
  • 29
-1

You could use jQuery .ready()

selector.ready(function(){
  // do stuff
})