I don’t understand why this is happening.
I need to get the objects startPoint which is set on mousedown and the current e.pageY from the mousemove to do some calculations.
var adjustHeight = {
change: function(e) {
console.log(this.startPoint)
console.log(e.pageY);
},
};
$('#dragger').mousedown(function(e) {
e.preventDefault();
adjustHeight.startPoint = e.pageY;
$(window).on('mousemove', adjustHeight.change());
$(window).on('mouseup', function() {
$(window).off('mousemove', adjustHeight.change())
});
})
However the console prints out the objects startPoint which is what I expect but e.pageY is undefined,
but when I use this line instead:
...
$(window).on('mousemove', adjustHeight.change);
$(window).on('mouseup', function() {
$(window).off('mousemove', adjustHeight.change)
});
...
I get the e.pageY as expected but now the startPoint is undefined. When I checked what this was pointing at it was the DOMWindow.
My question is why is this happening and how would I go about getting both objects properties and the functions e at the same time?
is executing
adjustHeight.changeimmediately and passing the return value to.on(). Since you are not passing any argument toadjustHeight.change,ewill beundefined(ande.pageYwon’t be available).correctly passes the function to
.on, hence later the event object is passed to the handler and you can accesse.pageY. But the context (this) is notadjustHeightanymore, it’s the DOM element you bound the handler to. Which iswindowin this case andwindowdoes not have astartPointproperty.The MDN documentation has an excellent article about
this(in general), as does quirksmode.org (with respect to event handlers).Solution:
Pass a new function as handler, which calls
adjustHeight.changeand passes theeventobject:or bind
adjustHeight.changetoadjustHeightusing$.proxy[docs]:Since you also want to unbind the handler later, you should either assign it to a variable or use a namespaced event [docs].
Example: