Danny
Danny

Reputation: 9634

javascript - can't change an image's position

I'm trying to change a position of a image that I have in HTML by using javascript. I can actually get it working if I have the following code:

function main()
{
    var catOne = document.getElementById("cat1");
    catOne.style.left = cat1.getX().toString() + "px";
    catOne.style.top = cat1.getY().toString() + "px";
}

but when I change the code to this:

var catOne = new Cat("cat1", 300, 100);

function main()
{

    catOne.setUp();
}

it doesn't work. and I dont know why, but it only gives me an error of "TypeError: Cannot read property 'style' of null"

This is my Cat class in javascript:

function Cat(id, x, y)
{
    this.cat = document.getElementById(id);
    this.x = x;
    this.y = y;
}

Cat.prototype.setUp = function ()
{
    this.cat.style.left = this.x.toString() + "px";
    this.cat.style.top = this.y.toString() + "px";
};

Cat.prototype.getX = function ()
{
    return this.x;
};

Cat.prototype.getY = function ()
{
    return this.y;
};

Upvotes: 0

Views: 509

Answers (2)

Onur Yıldırım
Onur Yıldırım

Reputation: 33674

TypeError: Cannot read property 'style' of null means your catOne does not exist in the DOM tree.

You should instantiate the Cat class when the DOM is ready (or on window load). I don't know why you need that main() function but when does it execute? It should also execute when the DOM is ready.

var catOne;
function main() {
    catOne.setUp();
}

window.onload = function() {
    catOne = new Cat("cat1", 300, 100);
    main();
}

I also suggest that you set the position of your cat to absolute if you are positioning it like that in your setUp() function. (I think you are already doing this with your CSS):

Cat.prototype.setUp = function ()
{
    this.cat.style.position = 'absolute';
    this.cat.style.left = this.x.toString() + "px";
    this.cat.style.top = this.y.toString() + "px";
};

Here is the fiddle.
Other than that your code should work.

Upvotes: 1

eGz3
eGz3

Reputation: 15

with:

var catOne = new Cat("cat1", 300, 100);
catOne.setUp();

works just fine.

I don't quite get it how You managed to get error You mentioned

link: http://jsfiddle.net/Z74mM/

Upvotes: 0

Related Questions