javascript – Add a event to HTML element when it becomes on the user screen-ThrowExceptions

Exception or error:

I want to add a event to HTML element when it becomes on the user screen using only Javascript or React components but not jQuery.

I’m using react components and I want to run setInterval() function to
make a simple counter using state, but the problem is the code runs
when page is rendered, I want to start code only when the element
becomes on the screen.

How to solve:

Use an intersection observer and set the interval within the callback:

let isIntersected = false;

const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    let count = 0;
    if (entry.intersectionRatio > 0 && !isIntersected) {
      isIntersected = true;
      setInterval(() => {
        document.querySelector("#counter").innerText = count;
      }, 1000);


A not very optimized example:



I don’t think you can accomplish this by adding an event to the element itself. I think you’ll have to add listeners to the window for any events that can possibly change which elements are in view (load, scroll, resize).

I borrowed isScrolledIntoView() from this answer

// Get your element however you'd like
let myElmement = document.getElementById('myElement');
// Loop through possible events that will bring element into view
['resize','scroll','load'].forEach( eventName => {
  window.addEventListener(eventName, event => {
    if (isScrolledIntoView(myElmement)) {
    } else {

// Borrowed from
function isScrolledIntoView(el) {
  let rect = el.getBoundingClientRect();
  let elemTop =;
  let elemBottom = rect.bottom;

  // Only completely visible elements return true:
  let isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
  // Partially visible elements return true:
  //isVisible = elemTop < window.innerHeight && elemBottom >= 0;
  return isVisible;


function isUserCanSeeIt(elemClassName,elemNumber){
    var elem = document.getElementsByClassName(elemClassName)[elemNumber];
    var elemPos = elem.getBoundingClientRect();
    if( > 0){
        return true;
    else return false;
function event(elemClassName,elemNumber){

Leave a Reply

Your email address will not be published. Required fields are marked *