简体   繁体   中英

How to make text/div appear when the user stops scrolling

I'm trying to achieve an effect where the javascript detects whether the user has stopped scrolling/hovering over the page, and slowly shows a piece of text over the page, sort of like a paywall. The effect I'm trying to achieve is a simplified version of this website where when the user is inactive for a certain amount of time, eyes start to appear on the page

You can use setTimeout and clearTimeout to perform an action when the mouse stops moving. Here the text would reappear after 3 seconds of inactivity

 var timeout; var element = document.getElementById("element"); document.addEventListener("mousemove", function(e) { element.style.display = "none"; clearTimeout(timeout); timeout = setTimeout(function() { element.style.display = "block"; }, 3000); });
 <div style="display: none" id="element">I see you<div>

First, you want to define what it means for a user to be "inactive". For example, we can consider a user to be inactive if they haven't moved their mouse or scrolled for 30 seconds. When that happens, we want to fire off some other code to signal that the user has gone inactive.

const addUserInactiveListener = (
  onUserInactive, 
  inactiveTimeMs = 30000
) => {
  let timeout = setTimeout(onUserInactive, inactiveTimeMs);

  const onUserAction = () => {
    clearTimeout(timeout);
    timeout = setTimeout(onUserInactive, inactiveTimeMs);
  }

  
  document.addEventListener('mousemove', onUserAction);
  document.addEventListener('scroll', onUserAction);
}

// console log after 5s of inactivity
addUserInactiveListener(() => console.log('inactive'), 5000)

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