Link to different page -> jquery scroll to specific anchor

别来无恙 提交于 2019-12-01 05:45:40
akbar ali

Try this, your script is OK only the last line is missing

 (function ($) {

     var jump = function (e) {
         if (e) {

             e.preventDefault();
             var target = $(this).attr("href");

         } else {

             var target = location.hash;

         }
         $('html,body').animate({

             scrollTop: $(target).offset().top

         }, 1000, function () {

             location.hash = target;

         });
     }

     $('html, body').hide();

     $(document).ready(function () {
         $('a[href^=#]').bind("click", jump);

         if (location.hash) {
             setTimeout(function () {

                 $('html, body').scrollTop(0).show()
                 jump();

             }, 0);
         } else {

             $('html, body').show();

         }
     });
 })(jQuery)

I'm not sure what your code is, but i've been able to get it working. One thing is, the code you posted, it's missing a })(jQuery) at the end. Anyway, check out what i did here, i think it's what you're looking for. I'm not sure what your website's HTML looks like, but i think you can adapt it. All you need to do is set the href attribute of the contact button to index.html#contact. On index.html, you can just use #contact and it will do the same thing.

In index.html, Header:

<div id="header">
    <a href="index.html">Homepage</a>
    <a href="otherpage.html">Other page</a>
    <a href="otherpage2.html">Another Page</a>
    <a href="#contact">Contact</a>
</div>

but in any other page:

<div id="header">
    <a href="index.html">Homepage</a>
    <a href="otherpage.html">Other page</a>
    <a href="otherpage2.html">Another Page</a>
    <a href="index.html#contact">Contact</a>
</div>

removing index.html in the header in index.html prevents the page from being loaded twice, so that jQuery simply scrolls the page down.

Little tip I came across while testing out your code:

Because you're using the href attribute of the anchor tag, it comes over as #contact, which jQuery interprets as an ID.

You will need to add an id="contact" to the anchor in order for it to work, regardless of the page it's on.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!