Frederik Voordeckers
Frederik Voordeckers

Reputation: 1331

Navigate slow to id in URL

On my homepage I have a menu with ID's, when I click it, it slides to the corresponding div and it works smooth.

But when I'm not on my homepage and I click an item I want to be able to go to the homepage and then slide to the section.

Here is the code I'm using now:

$('#mainMenu a').click(function(e){
    e.preventDefault();
    var div = $(this).attr('href');
    if('<?=get_site_url()?>/' == '<?=get_permalink()?>')
    {
        $('html, body').animate({scrollTop:$(div).position().top}, 'slow');
    }
    else
    {
        window.location.href = '<?=get_site_url()?>/'+div;
    }
});

This works excellent, the next part works to but I can't get it to slide to the ID.

if (window.location.hash != "") {
    e.preventDefault();
    $('html, body').animate({scrollTop:$(window.location.hash).position().top}, 'slow');
}

Is there a way I can prevent the browser from directly jumping to the section and instead sliding to it?

Upvotes: 0

Views: 1201

Answers (2)

Frederik Voordeckers
Frederik Voordeckers

Reputation: 1331

This works like a charm:

$('#mainMenu a').click(function(e){
    e.preventDefault();
    var div = $(this).attr('href');
    if('<?=get_site_url()?>/' == '<?=get_permalink()?>')
    {
        $('html, body').animate({scrollTop:$(div).position().top}, 'slow');
    }
    else
    {
        localStorage.setItem("hash", div);
        window.location.href = '<?=get_site_url()?>/';
    }
});

if (localStorage.getItem("hash")!=null) {
    $('html, body').animate({scrollTop:$(localStorage.getItem("hash")).position().top}, 'slow');
    localStorage.removeItem("hash");
}

Instead of putting the hash in my url I stored it in localStorage and in my head of the page I checked if it was set.

Founded this solution just a few minutes after posting the question, thanks to those who helped me :)

Upvotes: 0

Leonardo Santos
Leonardo Santos

Reputation: 11

Try to scroll to top right at the start, then roll down:

if (window.location.hash != "") {
    $('html, body').scrollTop(0).animate({scrollTop:$(window.location.hash).position().top}, 'slow');
}

Also, remove e.preventDefault(), since you're not defining any variable named e nor an event.

Upvotes: 1

Related Questions