Link to different page -> jquery scroll to specific anchor

Tom picture Tom · Aug 5, 2012 · Viewed 16.5k times · Source

At the bottom of my home page I have included a contact form and specified the anchor for this section as div id="contact".

When the contact button is clicked on any page it should navigate to the homepage and on page load, scroll automatically to the contact form.

I've been unsuccessful in getting this to work after reviewing a similar question I found here: jQuery scroll to ID from different page When I try, it just jumps to the form. I want it to scroll smoothly.

<li><span>Get in touch</span><a href="index.html#contact">Contact</a></li>

The problem jquery function to scroll to the contact anchor on the home page from other pages:

(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()
    }
});

I'm trying to achieve something similar to this example: http://vostrel.cz/so/9652944/page.html difference being that instead of the "anchor id" in this case appearing on both pages, the anchor id (contact) for me only appears on one page (home).

Answer

akbar ali picture akbar ali · Feb 11, 2015

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)