Search code examples
javascriptjqueryhtmlfade

Fade between pages using jquery


I'm trying to add a transition effect to my site with Jquery. Everything was working, but suddenly the site started flickering one time before the fade in effect... I add a display:none and it was solved. But if visitors have JavaScript disabled, they won’t be able to view the site. I've already add it as a script but it doesn't work... Any ideas? Here is my fade code:

<!--transition-->
    <script type="text/javascript">
        $(document).ready(function() {

            $("body").css("display", "none");
            $("img").css("display", "none");

            $("body").fadeIn(2000);
            $("img").fadeIn(2000);

            $("a.link").click(function(event){
            event.preventDefault();
            linkLocation = this.href;
            $("body").fadeOut(1000, redirectPage);
            $("img").fadeOut(1000, redirectPage);   
        });

        function redirectPage() {
            window.location = linkLocation;
        }

        });
    </script>

Solution

  • You can perform the fade in transition using CSS only, like so:

    body {
        animation: myfadeInAnimation 2s;
    }
    div {
        width: 300px;
    }
    @keyframe myfadeInAnimation {
        from {opacity: 0;}
        to {opacity: 1;}
    }
    @-webkit-keyframes myfadeInAnimation {
        from {opacity: 0;}
        to {opacity: 1;}
    }
    

    Here is the JSFiddle demo

    As for the fade out effect, if the browser will not be running javascript, you will have no means of detecting the window unload and trigger an effect for it...