Search code examples
javascriptjqueryfadeinfadeoutjquery-effects

fadeIn and fadeOut effect between pages


I'm trying to make some transition effects for my page.

The goal is to fade in the page when you first enter, and then when you click a link, the page will fadeout and fadein the destination page. But It won't get the destination url so when i click a link, the url changes to www.example.com/#undefined

Any suggestions?

jQuery.holdReady(true);
jQuery("body").css("opacity", 0);
jQuery.holdReady(false);
jQuery(function ($) {
    $("body").fadeTo(1500, 1);
    $(document).on("click", "a", function (event) {
        event.preventDefault();
        $("body").fadeTo(1500, 0, function () {
            // get the href attribute
            var newUrl = $(this).attr("href");

            // veryfy if the new url exists or is a hash
            if (!newUrl || newUrl[0] === "#") {
                // set that hash
                location.hash = newUrl;
                return;
            }

            // now, fadeout the html (whole page)
            $("body").fadeTo(1500, 1, function () {
                // when the animation is complete, set the new location
                location = newUrl;
            });
            // prevent the default browser behavior.
            return false;
        });
    });
});

Solution

  • Within the inner function, this doesn't point at the <a> element that was clicked. Move the resolution of newUrl outside of that function:

    jQuery.holdReady(true);
    jQuery("body").css("opacity", 0);
    jQuery.holdReady(false);
    jQuery(function ($) {
        $("body").fadeTo(1500, 1);
        $(document).on("click", "a", function (event) {
    
            // get the href attribute
            // "this" is still the <a> element here
            var newUrl = $(this).attr("href");
    
            event.preventDefault();
            $("body").fadeTo(1500, 0, function () {
    
                //here, where you were trying to get the url, "this"
                //points to the animated element, ie body
    
    
                // veryfy if the new url exists or is a hash
                if (!newUrl || newUrl[0] === "#") {
                    // set that hash
                    location.hash = newUrl;
                    return;
                }
    
                //just update the location without fading in at this point
                location = newUrl;
    
                // prevent the default browser behavior.
                return false;
            });
        });
    });