简体   繁体   中英

How can i update counter once when window is reached to page?

Actually I don't have any source code because I don't know to do it.

Help me please, can you answer to my question? I will repeat "How can I update counter once when window reached to section?", with out libraries.

 /* sample JavaScript tried here */
 /* related CSS */.oops { border: solid red 1px; }
 <div class="oops"> HTML I tried here</div>

This code listens to the scroll event on the window, and increments the counter counter by 1 once the current scroll position of the window scrollPos is greater than or equal to the position of the section sectionTop on the page. The event listener is then removed to prevent the counter from being incremented again.

// initialize the counter to zero
var counter = 0;

// get the section element
var section = document.querySelector("#section");

// get the position of the section on the page
var sectionTop = section.offsetTop;

// listen to the scroll event on the window
window.addEventListener("scroll", function() {
  // get the current scroll position of the window
  var scrollPos = window.scrollY;
  
  // check if the window has reached the section
  if (scrollPos >= sectionTop) {
    // increment the counter by 1
    counter++;
    
    // prevent the counter from being incremented again
    window.removeEventListener("scroll", arguments.callee);
  }
});

I think this will be a good start for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM