shumonira
shumonira

Reputation: 23

onload event in home page

I have some text in a div in my home page, I want this should appear with light background (in less opacity) and the width of the div should be 50%, and will load after 2seconds after the page load. I tried with javascript but its not working. in my css file "transition: width 2s;"

var slider = document.getElementById("splasher");

function splasher(){
slider.style.width="50%";
}

I put onload in the div which is

onload ="splasher();"

any help for this

Upvotes: 0

Views: 169

Answers (3)

Christos
Christos

Reputation: 53958

You need something like the following. Initially we wait the DOM to be loaded. Then we set a timeout for the splasher.

document.addEventListener("DOMContentLoaded", function(){
    var slider = document.getElementById("splasher");
  
    function splasher(){
        slider.style.width="50%";
        slider.style.opacity = 0.5;
        slider.style.display = 'block';
    }
  
    setTimeout(splasher, 2000);
})
<h4>Slider Demo</h4>
<div id="splasher" style="display:none;">Slider</div>

Upvotes: 1

Scott Marcus
Scott Marcus

Reputation: 65796

You need to make sure you don't run the var slider=... line before the element is loaded.

Upvotes: 0

zurfyx
zurfyx

Reputation: 32767

Your slider might not have been rendered yet. Put in inside onload as well.

<body onload="loaded()">

function loaded() {
 var slider = document.getElementById("splasher");

 function splasher(){
   slider.style.width="50%";
 }
}

Upvotes: 0

Related Questions