How To Bind Mousemove Scroll And Resize All Into One Function
Currently, I 'do stuff' when the mouse moves. However, I also want to do the exact same thing if the user resizes the browser or scrolls down the browser. jQuery(document).bind
Solution 1:
You do still have the event data in the scroll and resize methods. Try wrapping your code into a single function with 3 handlers. The on() method requires jQuery 1.7+
function reusable(eData){
// Heres what you want to do every time
}
$(document).on({
mousemove: function(e) { reusable(e); },
scroll : function(e) { reusable(e); }
);
$(window).on({
resize : function(e) { reusable(e); }
});
edited
The events should be in their correct objects window
and document
or you will get unexpected values.
Solution 2:
from your comment:
the problem is that e.pageX is undefined when the resize or scroll event is activated and that is breaking my application
So why are you using the current object properties when you know they are undefined
? Why not use a global variable and hold in them the last value?
var clientX = 0, clientY = 0,
screenX = 0, screenY = 0,
pageX = 0, pageY = 0;
// bind the events in the correct objectsjQuery(window).bind('resize',function(e) { getBindingValues(e); });
jQuery(document).bind('mousemove scroll',function(e) { getBindingValues(e); });
// your one-functionfunctiongetBindingValues(e) {
clientX = e.clientX ? e.clientX : clientX;
clientY = e.clientY ? e.clientY : clientY;
screenX = e.screenX ? e.screenX : screenX;
screenY = e.screenY ? e.screenY : screenY;
pageX = e.pageX ? e.pageX : pageX;
pageY = e.pageY ? e.pageY : pageY;
$("#hello").html(
"*** Safe values ***<br/>" +
"mouse: X." + clientX + " Y." + clientY + "<br/>" +
"page: X." + pageX + " Y." + pageY + "<br/>" +
"screen: X." + screenX + " Y." + screenY + "<br/><br/>" +
"*** More values ***<br/>" +
"window: W." + $(window).width() + " H." + $(window).height() + "<br/>" +
"type: <b>" + e.type + "</b>"
);
}
you can compare below the e
(event) object on mousemove
and scroll
on scroll
on mousemove
Post a Comment for "How To Bind Mousemove Scroll And Resize All Into One Function"