Wait for the item to be displayed to the user.

How to wait until an item is displayed / viewed by the user? I have the following function, but it only checks 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);
    }
}
+4
source share
2 answers

It’s a little embarrassing, are you just trying to "fall asleep"?

You can wait for the item to load using:

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

Some working snippets, 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>
Run codeHide result

If you want to wait timehow you installed the function and selectorwhich should appear after that time.. You can take into account simple setTimeout()and CSS.

Follow the example below, hope this 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 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>
Run codeHide result
+1

jQuery.ready()

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

Source: https://habr.com/ru/post/1656640/


All Articles