0

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

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?

Frederik Voordeckers
  • 1,321
  • 15
  • 31

2 Answers2

1

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.

  • Thanks for the answer, the e is in my document.ready(function(e){... This works but not really smooth, some flickering, I found another way around, I'll post my solution in a minute ;) Thanks anyway!! – Frederik Voordeckers Apr 12 '13 at 02:08
0

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 :)

Frederik Voordeckers
  • 1,321
  • 15
  • 31