Thursday, 5 September 2013

using objects to get position (x, y) - Javascript

using objects to get position (x, y) - Javascript

this code works:
var myElement = document.getElementById("red");
setInterval(function() {
console.log("Left:" + myElement.offsetLeft + "px | Top:" +
myElement.offsetTop + "px");
}, 1000);
This prints out the position(x, y) every second
But If I try and change it to using objects:
function Enemy(id){
this.id = getElementById(id);
this.getCoordinates = function(){
setInterval(function() {
console.log("Left:" + this.id.offsetLeft + "px | Top:" +
this.id.offsetTop + "px");
}, 1000);
}
}
$(document).ready(function(){
var enemy = new Enemy("red");
enemy.getCoordinates();
});
It prints out nothing - and I can't see where my mistake is.

No comments:

Post a Comment