Reputation: 5985
So, I've made simple function to get the mouse location on a page. I want to make it simpler so I can just pass a variable to another function. Right now, I have this:
$(document).on('mousemove', world, function(e){
var loc = function(){
this.x = function(){
return e.pageX - $(world).offset().left;
}
this.y = function(){
return (e.pageY - $(world).offset().top)*(-1);
}
}
console.log(loc.x, loc.y)
});
The console.log just returns undefined. Is there a way to do this globally so I can use a variable such as loc.x
to pass into a function?
Upvotes: 0
Views: 709
Reputation: 782407
Not that I'm advocating it, but here's how you would do it in the way you tried:
$(document).on('mousemove', "#world", function(e){
var self = this
var loc = function(){
this.x = function(){
return e.pageX - $(self).offset().left;
}
this.y = function(){
return (e.pageY - $(self).offset().top)*(-1);
}
}
var thing = new loc();
console.log(thing.x(), thing.y())
});
You have to call loc()
to get the object. And then you have to call thing.x()
and thing.y()
to execute those functions and get the values.
Upvotes: 1
Reputation: 6512
You'll want to create an object to the scope of your application. (Putting it to a global level may cause namespace clashes.)
var loc = {
x: 0,
y: 0
};
Then just keep reassigning the properties of your object in your event, in this case it's when you move the mouse to keep track of where the mouse location is.
$(document).on('mousemove', function (e) {
loc.x = e.pageX;
loc.y = e.pageY;
console.log(loc.x, loc.y);
});
Upvotes: 2