开发者

Howto: Check if on Page, if not Redirect and then Scroll

开发者 https://www.devze.com 2023-04-10 22:43 出处:网络
I am trying to get one last thing working: I have a blog link in the main navigation and when you click it, it scrolls down to the blog. But when I\'开发者_如何学Cm on any other page, this logic obv

I am trying to get one last thing working:

I have a blog link in the main navigation and when you click it, it scrolls down to the blog. But when I'开发者_如何学Cm on any other page, this logic obviously doesn't work. It should first consequently first go to the root page and then scroll. I've got the opposite thing working here, but haven't quite gotten this task done yet.

Any help?

I am using scrollTo successfully like this:

$(".scroll_to_top").click(function() {$.scrollTo($("body").position().top, 300)});

The blog part however is not yet reacting:

if(window.location.hash === 'blog') {
    $.scrollTo($("#blog").position().top, 300);
}

What am I doing wrong?


You could use a basic hash (#) at the end of the URL to automatically scroll the the element with the id specified in the hash (i.e. http://example.com#blog). That would be the simplest solution, with no need for Javascript.

If, however, the element you want to scroll to doesn't have an id that you can use (and you can't modify the HTML so that it does), or you want to animate the scroll rather than just jumping the the element in question, you could still use a hash in the URL and do something like the following:

//URL is http://example.com#blog

if(window.location.hash === 'blog'){
    //scroll
}

Finally, if you really hate the idea of putting a hash in the URL for some reason, you could intercept the click on the <a>, create a cookie, redirect to the desired page, and then have that page check for the existence of the cookie.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号