Custom Web Design & Development


jQuery Fade In Page Load with Redirect

Building on a PREVIOUS TUTORIAL of fading in the background & content on page load, now I will show you how to redirect users to a new URL after 5 seconds.  You can change the delay time in milliseconds to whatever is required. 

Live Demo

The CSS added to your stylesheet.

body {
   margin:0;
   padding:0;
   z-index:-2;
   background:#000;
}

#background{
   margin:0;
   padding:0;
   position:absolute;
   z-index: -1;
   display: none;
   top:0;
   left:0;
   width: 100%;
   height: 200%;
   /**scalable background to fill available viewport**/
   background: url(/Images/YOUR_BG_IMAGE.jpg) center center fixed;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
}

.jumbotron {
   width: 80%;
   margin: 5% auto;
   border: 3px solid #990000;
   background: rgba(255,153,153,0.6);
   text-align:center;
   color: #FFF;
}

The HTML inside <body> tag:

<div class="container">
<div id="background" class="row">
<div class="jumbotron">
<h2>Heading 2</h2>
<p>Your content, some more content, and some more content...</p>
<p>In 5 seconds, this page will redirect to a new URL.</p>
</div>
</div>
</div>

The jQuery Library

If it's not already included in your document, add a link to the latest stable release of jQuery's core library. It's important to put this library where it will load before the function script which follows.

<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.min.js">
</script>

JQuery Function

<script>
//invoke background fadein on page load
$(window).ready(function() {
   $('#background').fadeIn(3700, function() {
   //wait 5 seconds and redirect to new URL
   $(this).delay(5000).fadeOut(2000, function() { window.location = 'http://example.com'; });
   });
});
</script>

And there you have it. Hope you enjoyed this brief tutorial.