Redirect page if user does not interact (click, touchstart, Mousemove)

Asked

Viewed 98 times

1

I need to redirect to a "rest screen", if the user does not interact via click/touch, drag and mouse movement.

Whatever you can do

<script type="text/javascript">

    var meuTempo;

    meuTempo = setTimeout(openUrl, 5000); // redirecionamento

    function resetTimer(){
    clearTimeout(meuTempo); // dá um clear no tempo para dar reload
    }

    function openUrl(){
        window.location = "https://www.google.com/"; // reload
    }

    jQuery(document).bind("click mousemove touchstart", resetTimer); // reset de timer por interação

</script>

The problem

It is necessary that whenever the user does not interact, the counter is set again.

That is, if the user interacts he stays on the page, if not, he is redirected after X seconds to another screen.

1 answer

1


Use a function to count seconds, and use the bind below to test User interactions:

$(document).on("click keydown keyup mousemove")

var segundos = 0;
var timer = setInterval(testarInteracao, 1000); //1000 ms = 1 segundo

function testarInteracao(){
    segundos+= 1;
    
    if(segundos == 10){ //Limite máximo em Segundos
        window.location.href = "www.google.com";
    } 
    
    console.log(segundos)
}

$(document).on("click keydown keyup mousemove", function(){
    segundos = 0;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

If you need other events, put them in the same bind as $(document) separated by space

Browser other questions tagged

You are not signed in. Login or sign up in order to post.