tags:

views:

96

answers:

1

I am trying to track mouse movements in the browser, and if a user stops their mouse for 0.5 seconds, to execute some code. I have put a breakpoint in the code below in firebug, and it breaks on the var mousestop = function(evt) line, but then jumps to the return statement. Am I missing something simple? Why isn't it executing the POST statement? I am tracking mouse clicks in a similar way, and it posts to the server just fine. Just not mouse stops.

$.fn.saveStops = function() {
$(this).bind('mousemove.clickmap', function(evt) {
    var mousestop = function(evt) {
          $.post('/heat-save.php', {  
                x:evt.pageX,  
                y:evt.pageY,
                click:"false",
                w:window.innerWidth,
                h:window.innerHeight,
                l:escape(document.location.pathname) 
            }); 
      }, 
      thread;

      return function() {
        clearTimeout(thread);
        thread = setTimeout(mousestop, 500);
      };

});
};
+1  A: 

Could evt be undefined by the time mousestop is executed?

Try it like this:

      return function() {
        clearTimeout(thread);
        thread = setTimeout(function(){mousestop(evt);}, 500);
      };

here is how i would refactor:

// a closure for good measure...
(function($){
    var mousestop = function(evt){
            // I would use GET because POST makes 2 round trips
            $.get("/heat-save.php", {  
                "x":evt.pageX,  
                "y":evt.pageY,
                "click":false,
                "w":window.innerWidth,
                "h":window.innerHeight,
                "l":escape(document.location.pathname)
            }); 
        },
        thread = null;
    $.fn.saveStops = function() {
        return this.bind("mousemove.clickmap", function(evt) {
            clearTimeout(thread);
            thread = setTimeout(function(){mousestop(evt);}, 500);
        });
    };
}(jQuery));

You can event replace the ajax calls with something like this:

(new Image).src = "/heat-save.php?x=" + evt.pageX + "&y=" + evt.pageY + "&click=false&w=" + window.innerWidth + "&h=" + window.innerHeight + "&l=" + escape(document.location.pathname;

POST vs GET

Also, make sure your server sends back a "204 No Content" status code instead of 200 for the speediest responses.

David Murdoch
Thanks for the reply. I changed the return function, but it still is showing the same behavior and not POSTing.<edit> Just saw you edited as well. I will try this.
Hallik
Excellent! This worked better. I had the (function($) wrapping everything for clicks too, but I refactored it as you showed, and all works perfect! Thanks! (Only have 14 reputation, otherwise I would vote you up too :\ )
Hallik
No that's it. I am going to check the rest of the website, but I don't believe so. trying to make a heat map. This clinched it though
Hallik
Your welcome. Welcome to SO (Stack Overflow)!
David Murdoch