Search code examples
javascriptjqueryhttp-redirectscrollpreventdefault

jQuery Click anchor tag prevent page from scrolling to top


I'm doing page transitions with jQuery by fading out content and fading it back in when the page loads but my problem is when I click my link and call my click function and redirecting the page it loads at the the top of the page. Is there a way I can prevent this behavior? Here is my click function for my page transition, thanks in advance for any help!

LINK

<a href="../categories/categories.php"></a>

jQuery

$(".content").fadeIn(750);

$("a").click(function(event){
    event.preventDefault();
    linkLocation = this.href;
    $(".content").fadeOut(500, redirectPage);  
});

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

Solution

  • Good solution : Use history api with hashbangs fallback

    Bad solution: as an easy hack you can capture the current scroll position with

        $(".content").fadeIn(750);
        var offset = window.location.href.match(/offset=(\d+)/)
        if(offset){
           $(document).scrollTop(offset[1])
        }
        $("a").click(function(event){
            event.preventDefault();
            linkLocation = this.href + "?offset="+$(document).scrollTop();//pay 
    //special attentions to this line will work only for a link without get parameters. 
            $(".content").fadeOut(500, redirectPage);  
        });
    
        function redirectPage() {
            window.location = linkLocation;
        }