user3477366
user3477366

Reputation: 111

Error: this.style is undefined?

Sorry for my noobish question just started learning javascript.

So I want to make function that hides slika[0].

function hide() {
  this.style.display ='none';
};        

slika[0] = setTimeout(hide, 4000);

And the error is:

TypeError: this.style is undefined  
this.style.display ='none';

Upvotes: 5

Views: 4902

Answers (1)

thefourtheye
thefourtheye

Reputation: 239523

When you call hide, this would be the window object and window object doesn't have style attribute. That is why you get

this.style is undefined

If you wanted to hide slika[0], then you should bind the hide function with slika[0], like this

setTimeout(hide.bind(slika[0]), 4000);

Now, you have bound the slika[0] to hide function. So, when hide is invoked, this will refer slika[0], and it will set the display style to none.

If you want a generic function, you can simply accept the object as a parameter, like this

function hideObject(object) {
    object.style.display ='none';
}

Upvotes: 1

Related Questions