Make your web pages fade in and fade out

Before you go ahead and implement this, I recommend a few things.

  • Only use this on websites with a white background
  • Only use this on websites that load fairly fast
  • For best results, put this as the first thing inside of the <body> tag
  • The idea here is to use jQuery’s fadeIn and fadeOut methods on the full body of the website. First let’s take a look at the code, then we’ll go through it.

    <script src="//"></script>
    	jQuery(document).ready(function() {
    			var thetarget = this.getAttribute('target')
    			if (thetarget != "_blank"){			
    				var thehref = this.getAttribute('href')
    					window.location = thehref					
    <div id="wrapper">
    Lorum Ipsum...

    So what exactly are we doing here? First, we’re including the jQuery library hosted by google. If you already have jQuery on the site, then you can skip that first line of code.

    Even though we’re including jQuery in this example, I personally like to keep with native javascript whenever possible. A lot of people overuse jQuery for unnecessary scripts. On the first line inside of the script, we style the body to have a display of none. The reason I do this through the javascript instead of CSS is for the few people who might not have javascript enabled on their computer (phone / tablet ect.) If we used CSS to give the body a display of none, but the person has javascript disabled, then the site will become completely unusable.

    Next is jQuerys classic (document).ready(function(){, which is similar to a window.onload = function{ in native javascript. Inside of the ready function are essentially doing two things.

    • On load we fade in the body instead of letting it load line by line as it would naturally
    • When an <a> tag is clicked, we first check to see if its meant to open in a new tab (typically an external link)
    • If it is, then do nothing, otherwise we prevent the page from immediately disappearing, and instead give it a fadeOut
    • Then using window.location we go to the originally intended link
    • Finally, I use the setTimeout as a fallback just in case it takes a really long time for the function to be called.

    Leave a Reply

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

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>