How to fade in content using HTML, CSS, and JavaScript

Sometimes we want our content to make a cool entrance on a webpage.  Luckily, using CSS and HTML, we can do just that by easily fading something onto the page.  First thing we’ll need to do is create a HTML page like so:

<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″>
<title>Select Tag</title
</head>
<body>
<div id=”fademe”>Fade me in!</div>
</body>
</html>

This is your typical HTML page that has a div with an id of fademe.  We will be fading the div in later with the text “Fade me in!”.  The first thing we’ll need to do is create the CSS inside the head tag that will make the text invisible so we can start from not seeing it to seeing it.  Add the following inside the head tag:

<style>
#fademe{
opacity:0;
transition:2s;
}
</style>

This selects the div using the #fademe selector and makes it invisible with the opacity set to 0.  The transition property says if any of the properties that have already been set are changed, it will animate that change for 2 seconds if it can. Well, we need to change the opacity from 0 to 1 and we’ll need to use JavaScript to do that.  We will use window.load to run the code after the page has loaded.  Right before the closing body tag in the HTML, we will put this:

<script>
window.onload = function(){
document.getElementById(“fademe”).style.opacity = 1;
}
</script>

This says when the window loads it will run a function.  A function is a group of code that runs when we tell it to.  When the function runs it will select the element (or tag) with the ID of fademe (the div) and then change the opacity style to 1.  When all is said and done the completed project will look like this:

<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″>
<title>Select Tag</title>
<style>
#fademe{
opacity:0;
transition:2s;
}
</style>
</head>
<body>
<div id=”fademe”>Fade me in!</div>
<script>
window.onload = function(){
document.getElementById(“fademe”).style.opacity = 1;
}
</script>
</body>
</html>

When this is run, you will see the div, with the text in it, fade onto the page in 2 seconds.  If you want to learn more be sure to check out our web design/development courses.  Have an amazing day!

 

Leave a Reply

Your email address will not be published. Required fields are marked *