Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mousemove event working on document but not 'body'

Tags:

jquery

I am trying to make a div look like a turned-off light and when the mouse moves, the light turns on.

I am done with the part where the mouse movement turns the light on. Look at this fiddle.

jQuery code:

$(document).mousemove(function() {
    $('div').addClass('glow');
});

I have 2 questions about it

  1. If I put 'body' instead of document, it doesn't work, why?

  2. How can I detect the mouse stop?

like image 502
Sourabh Avatar asked May 14 '13 18:05

Sourabh


1 Answers

1) 'body' perfectly works but you must move the mouse over the body, which doesn't go until the bottom of the window (yes, the body is a strange and sometimes incoherent thing).

2) To detect mouse stop, the simplest solution is to use setTimeout and define a delay :

(function (){
    var i =0;
    var timer;
    $('body').mousemove(function() {
        clearTimeout(timer);
        // 'body' doesn't work instead of document
        i += 1;
        $('p').text(function() {
            return 'Moved: ' + i;
        });
        $('div').addClass('glow');
        timer = setTimeout(function(){$('div').removeClass('glow')}, 2000);
    });     
})();

Demonstration

like image 122
Denys Séguret Avatar answered Nov 24 '22 06:11

Denys Séguret