Karish Karish
Karish Karish

Reputation: 269

javaScript Fade-In OnLoad

i am trying to fade in a div once page loaded, for some reason it doesn't work, also is there a better way to do this using JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Fade In</title>
    <meta charset="UTF-8"/>
    <link rel="stylesheet" href="main.css">
    <script src="main.js"></script>
</head>

<body onload="FadeIn('box2');">   
    <div id="box2">Content in Box2...</div>
</body>
</html>

.

function FadeIn(el2){
    var element2 = document.getElementById(el2);
    element2.style.transition = "opacity 1.0s linear 0";
    element2.style.opacity = 1;                
}

.

#box2{
    background:#9dceff;
    width:400px;
    height:200px;
}

Upvotes: 0

Views: 5524

Answers (2)

SineLaboreNihil
SineLaboreNihil

Reputation: 953

If you want to do this in JavaScript, my suggestion would be to use for example the jQuery JavaScript library (other libraries can do this as well, such as Prototype, MooTools or Dojo), because it might be a bit easier and maybe a bit more readable instead of using plain JavaScript.

Simply add the following code to your page:

In the head of your document call the jQuery library from Google like so:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

And add the following few lines of code:

<script>
        $(document).ready(function(){
            $("#box2").fadeIn();
        });
</script>

And in your CSS document (main.css) add the display: none; property to the styling of your box2 div element. Please note that when display is set to none the element won't take up any space on your page. Then when the jQuery code is executed it will simply fade in the box2 div element on your page. The cool thing is that this code will execute when the entire document is loaded ($document).ready()), so you can take the onload attribute from your body tag out. I think that this is the simplest way of doing this in JavaScript.

Upvotes: 1

11684
11684

Reputation: 7507

As far as I can see from the code, you forgot to set the opacity to zero in the first place. If the element is fully opaque from the beginning, there won't be much to fade.

Upvotes: 1

Related Questions