jquery - deciding whether a user is "away"
im doing a little test to check whether the user is "away" (unactive) or not;
function away_status(){
$("#away_stat_update").everyTime(1000, function(i) {
var number = Number($(this).html());
if( number == 20 ) {
// set user as away
alert( "user away" );
}
if( number > 20 ) {
$("*").mousemove(functi开发者_高级运维on(e){
$("#away_stat_update").html(0);
var number = Number(0);
// reset user to being online
alert( "user back online" );
});
}
$("#away_stat_update").html( number + 1 );
});
$("*").mousemove(function(e){
$("#away_stat_update").html(0);
});
}
away_status();
the only problem is that when the number is greater than 20 and the mouse is moved it keeps alerting "user back on line" instead of doing it just once. The number is resetting by the way.
I'm answering this in a slightly different way - as I think it's always nice to solve a problem gracefully and with the briefest possible code.
This example does exactly what you want, fully working. It doesn't write the number into the DOM, it holds it in memory in JavaScript - you can write it into the element if you wish to display the number, but this saves having to retrieve it each time.
The alerts also work as you described.
var number = 0;
var timer;
function handle_mouse_move() {
if (number > 20) {
alert("User back online, was away for approx " + number + " seconds");
}
number = 0;
}
function handle_timer() {
if (number === 20) {
alert("User away");
}
number++;
timer = window.setTimeout(function() { handle_timer(); }, 1000);
}
$(document).ready(function() {
timer = window.setTimeout(function() { handle_timer(); }, 1000);
$("*").mousemove(function(e){
handle_mouse_move();
});
});
You're attaching multiple mousemove
events twice in the same method which won't help matters...so every time the timer elapses you're attaching two new event handlers. Combine and move the mousemove
event code and move them out of the away_status ()
method.
As for the reset, in the first mousemove event handler change:
var number = Number(0);
to
number = Number(0); // or just = 0;
Notice we removed the var...it looks to be a scoping issue.
It looks like you add a mousemove event every time the callback function is executed, i.e. every second.
function away_status(){
$("#away_stat_update").everyTime(1000, function(i) {
var number = Number($(this).html());
if( number == 20 ) {
// set user as away
alert( "user away" );
}
$("#away_stat_update").html( number + 1 );
});
}
away_status();
$("*").mousemove(function(e){
$("#away_stat_update").html(0);
alert( "user back online" );
});
This way you only set the mousemove event once and there is no need to unbind it. Note this resets the number whenever the mouse is moved, it doesn't wait until number > 20.
$("*").mousemove(function(e){
// ...
});
This will assign an event handler to the mousemove event, which will remain there until you remove it.
精彩评论