Detect cursor inactivity

1

I need to detect that the user is not moving the cursor (mouse) with jquery so after x seconds show him a modal window. I know that the mousemove function exists but I need the opposite of this. Thanks.

EDITED

Is there a possibility to stop the setTimeout () after displaying the modal?

    
asked by Lina Cortés 28.02.2018 в 22:05
source

4 answers

1

Here is an example of the function you ask for with the interaction of adding or removing it. I hope you serve as an example.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>
<body> 
<button id="add"onclick="AddAlert()"> Agregar alerta </button> 
<button id="del" onclick="RemoveAlert()" style="display:none;"> Parar alerta </button>
</body>
<script>

var mouseStop = null;
var Time = 5000; //tiempo en milisegundos que espera para saefectuarse la funcion


function RemoveAlert() {
  $("#add").show();
  $("#del").hide();
  $(document).off('mousemove');
  clearTimeout(mouseStop); //agrego esto porque borra tambien el setTimeout y no ejecuta  Myfuncion.

}

function AddAlert() {
  $("#add").hide();
  $("#del").show();
  $(document).on('mousemove', function() {
     clearTimeout(mouseStop);
     mouseStop = setTimeout(Myfunction,Time);

  });
}

function Myfunction() {
     alert("Dejo de mover el raton!!"); //aqui efectua la funcion cuando dejas de mover el raton
}


</script>


</html>
    
answered by 28.02.2018 / 23:14
source
5

Create a new function in Jquery to determine if the mouse is active within the document, use a timeout to determine the time, example (execute it, put the cursor in the snipped space and wait 5 seconds):

(function ($) {
    var timeout;
    $(document).on('mousemove', function (event) {
        if (timeout !== undefined) {
            window.clearTimeout(timeout);
        }
        timeout = window.setTimeout(function () {
            //Creas una funcion nueva para jquery 
            $(event.target).trigger('mousemoveend');
        }, 5000); //determinas el tiempo en milisegundo aqui 5 segundos
    });
}(jQuery));

$(document).on('mousemoveend', function () { //agregas la nueva funcion creada, puede ser una clase o un id
    alert("mouse detenido");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
answered by 28.02.2018 в 22:16
5

You can make a timeout with the function you are commenting on, causing it to be reset each time you move the mouse. If I did not move it in x time it would skip the function you wanted:

var ratonParado = null;
var milisegundosLimite = 2000;

$(document).on('mousemove', function() {
   clearTimeout(ratonParado);

   ratonParado = setTimeout(function() {
      // aqui lanzarias la ventana
   }, milisegundosLimite);
});
    
answered by 28.02.2018 в 22:18
0

You can use the same javascript functions as setTimeout or setInterval, storing the last date in which you moved the cursor and then verifying that the time you want to execute another action has passed

var interval, mouseMove;

$(document).mousemove(function(){
    //Establezco la última fecha cuando moví el cursor
    mouseMove = new Date();
    /* Llamo a esta función para que ejecute una acción pasado x tiempo
     después de haber dejado de mover el mouse (en este caso pasado 3 seg) */
    inactividad(function(){
        alert("Inactivo");
    }, 3);
  });

  /* Función creada para ejecutar una acción (callback), al pasar x segundos 
     (seconds) de haber dejado de mover el cursor */
  var inactividad = function(callback, seconds){
    //Elimino el intervalo para que no se ejecuten varias instancias
    clearInterval(interval);
    //Creo el intervalo
    interval = setInterval(function(){
       //Hora actual
       var now = new Date();
       //Diferencia entre la hora actual y la última vez que se movió el cursor
       var diff = (now.getTime()-mouseMove.getTime())/1000;
       //Si la diferencia es mayor o igual al tiempo que pasastes por parámetro
       if(diff >= seconds){
        //Borro el intervalo
        clearInterval(interval);
        //Ejecuto la función que será llamada al pasar el tiempo de inactividad
        callback();          
       }
    }, 200);
  }
    
answered by 28.02.2018 в 23:05