How to detect when mouse stops moving in React?

Viewed 4898

I'm trying to dynamically toggle the visibility of a button element based on mouse movement (i.e., {visibility: visible} when the mouse is moving, {visibility: hidden} when it stops moving). The button is showing with onMouseMove, but I'm struggling with where to start on the second part. Since React doesn't have an onMouseStop event, what's the best way to achieve this?

export default class Infographic extends Component {
  constructor(props){
    super(props);

    this.state = {
      mouseMoving: false,
    };

    this.setMouseMove = this.setMouseMove.bind(this);
  }

  setMouseMove(e) {
    e.preventDefault();
    this.setState({mouseMoving: true});
  }

  render() {

    const scrollButtonStyle = {
      visibility: this.state.mouseMoving ? 'visible': 'hidden', 
     };

     return (
       <div onMouseMove={e => this.setMouseMove(e)}>
         <button style={scrollButtonStyle}>Back to top</button>
         <h1>Lorem Ipsum</h1>
       </div>  
     );
  }
}

UPDATE

Per the suggestions below, I added the following IIFE block to the setMouseMove method (using arrow functions for scope access) and it works just as expected. Thanks for the help!

setMouseMove(e) {
  e.preventDefault();
  this.setState({mouseMoving: true});

  let timeout;
  (() => {
    clearTimeout(timeout);
    timeout = setTimeout(() => this.setState({mouseMoving:false}), 50);
  })();
}
1 Answers

Have a timeout function that sets how many milliseconds of inactivity counts as "not moving".

let timeout;
let whenMouseMoves = () => {
  clearTimeout(timeout);
  timeout = setTimeout(toggleButton(), 50);
}

And adjust the function as you see fit for your button. Obviously, you'll need to make the toggleButton() function if you use this code.

Related