简体   繁体   中英

How can I trigger a function if an element is in the viewport for X amount of time?

Using Waypoints and the Inview shortcut , how might I be able to only trigger the handler function if an element is in view for X amount of time, say 5 seconds, rather than trigger immediately on the enter event?

new Waypoint.Inview({
  element:document.getElementById('target'),
  enter: function(direction) {
    // Only do this if in view for 5 seconds
  }
});

Note: This question comes from somebody else, asked through the issue tracker. I've copied it here because it's a good question.

This question has two answers, one specific and one general. I'll start with the general.

Any time you want to see if some condition is true for X amount of time you will need to look for:

  1. An event that marks the condition becoming true.
  2. An event that marks the condition becoming false.

When the condition becomes true, you start a timer using setTimeout that will trigger the action you desire after the given time has elapsed. When the condition becomes false, you clear the timer using clearTimeout . If the clearing event happens to fire after the timer has elapsed and the original event has fired, clearing has no effect.

One of the more common uses of this pattern is with mouse events. We sometimes want to trigger something when a user has been hovering over an element for X amount of time. In this next example the "becoming true" event will be mouseenter . The "becoming false" event will be mouseleave . Here we'll log to the console when the user has hovered over an element for five seconds.

var timer;

$('#something')
  .on('mouseenter', function() {
    timer = window.setTimeout(function() {
      console.log('Hovered for 5 seconds');
    }, 5000);
  })
  .on('mouseleave', function() {
    window.clearTimeout(timer);
  });

The specific answer: You can use this pattern for any of these class of problems in JavaScript, and the Inview events are no different. In this case we'll use enter and exit as the true and false events respectively.

var timer;

Waypoint.Inview({
  element: $('#something')[0],
  enter: function() {
    timer = window.setTimeout(function() {
      console.log('In view for 5 seconds');
    }
  },
  exit: function() {
    window.clearTimeout(timer);
  }
});

For this kind of problem, generally, one starts a timer on enter and stop the timer on exit .

example:

var timerId;
new Waypoint.Inview({
  element: document.getElementById('target'),
  enter: function(direction) {
    timerId = setTimeout(function() {
      // Only do this if in view for 5 seconds
    }, 5000);
  },
  exit: function(direction) {
    clearTimeout(timerId);
  }
});

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