Skip to content
the poor coder

js poll dom

Poor Man
Published
Reading time
2 min read

JS poll DOM is a way to poll the Document Object Model (DOM) with JavaScript. By polling the DOM, you can check for changes and react accordingly. For example, if you wanted to hide a div element if the user scrolls down the page, you can poll the DOM to detect when the user scrolls and then hide the element. To poll the DOM using JavaScript, you can set up a loop and use the setInterval() function to continually check for changes.

Text

// Create a loop to check for DOM changes every 200 milliseconds
let pollInterval = setInterval(() => {
  // Poll the DOM to see if the user scrolled 
  if (window.scrollY > 0) {
    // Hide the div if the user scrolled
    document.querySelector('#myDiv').style.display = 'none';
  }
}, 200);

The code above sets up a loop that checks for scroll events every 200 milliseconds. If a scroll event is detected, it will hide the div element with the ID of ‘myDiv’. You can also use the MutationObserver() interface to poll the DOM more efficiently. The MutationObserver() interface allows you to observe changes to the DOM and respond accordingly.

Text

// Create a MutationObserver to watch for changes to the DOM
let observer = new MutationObserver(() => {
  // Check for scroll events
  if (window.scrollY > 0) {
    // Hide the div if the user scrolled
    document.querySelector('#myDiv').style.display = 'none';
  }
});
// Start observing the DOM
observer.observe(document, {
  attributes: true,
  childList: true,
  subtree: true
});

The code above creates a MutationObserver and starts observing changes to the DOM. When a scroll event is detected, it will hide the div element with the ID of ‘myDiv’. In conclusion, the JS poll DOM technique is a great way to check for changes to the DOM and react accordingly. You can use the setInterval() function or the MutationObserver() interface to poll the DOM for changes and take action if needed.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC