Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

javascript scroll event

// Binding an event to scroll will cause that event to be fired excessively.
// Tie your event to a throttle instead to preserve smooth scrolling:
window.addEventListener('scroll', throttle(myFunction, 1000)) // Fire myFunction when you scroll/are scrolling, but only every 1000ms.

function myFunction() { // The main function you want fired by scrolling.
	console.log('hello')
}


// Utility functions
function throttle(goal_func, wait_ms) { // fires goal_func but only if wait_ms has elapsed, otherwise does nothing.
  var time = Date.now()
  return function() {
    if ((time + wait_ms - Date.now()) < 0) {
      goal_func()
      time = Date.now()
    }
  }
}
Source by www.sitepoint.com #
 
PREVIOUS NEXT
Tagged: #javascript #scroll #event
ADD COMMENT
Topic
Name
3+5 =