HTML change opacity onload using this will not work

Viewed 1432

I have a code like so:

<body style='opacity:0' onload='this.style.opacity=1'>

I would like to change opacity of body once everything is loaded. Is there a reason this wont work. Can I change this opacity? If I reference by the tag body it will work. For example using jquery :

<body style='opacity:0' onload='$("body")[0].style.opacity=1'>

Will work but :

<body style='opacity:0' onload='$(this)[0].style.opacity=1'>

Will not work. Can I use this somehow?

1 Answers

Is there a reason 'this' wont work.

this has no context inside the onload that why it's not working.

If I reference by the tag 'body' it will work

$("body")[0] refer to the body that why it's work, you could use document.body also.

When I onload='alert(this)' why do I get an object?

Since this keyword in global scope refers to window object.


Because you're using jQuery you could avoid the inline events and use ready function instead of onload and change the style using css() :

//When the page is fully loaded
$(function(){
    //Change the opacity to 1
    $("body").css('opacity','1');
});

Hope this helps.

Related