jQuery scroll to ID from different page

JqueryScrollSmooth Scrolling

Jquery Problem Overview


I was trying to use jQuery's page scroll inside some pages and could successfully make a smooth page scroll. The only problem I have now is when attempting to do that from different page. What I mean by that is if I click on a link in a page, it should load the new page and then scroll to the specific div element.

Here is the code I used to scrolling inside the page:

var jump=function(e)
{
       //prevent the "normal" behaviour which would be a "hard" jump
       e.preventDefault();
   //Get the target
   var target = $(this).attr("href");
   //perform animated scrolling
   $('html,body').animate(
   {
           //get top-position of target-element and set it as scroll target
           scrollTop: $(target).offset().top
   //scrolldelay: 2 seconds
   },2000,function()
   {
           //attach the hash (#jumptarget) to the pageurl
           location.hash = target;
   });

}

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

I hope the idea is clear.

Thanks

Very important Note: This code I posted above works great inside the same page, but what I'm after is to click a link from one page and go to another one and then scroll to the target. I hope it is clear now. Thanks

Jquery Solutions


Solution 1 - Jquery

You basically need to do this:

  • include the target hash into the link pointing to the other page (href="other_page.html#section")
  • in your ready handler clear the hard jump scroll normally dictated by the hash and as soon as possible scroll the page back to the top and call jump() - you'll need to do this asynchronously
  • in jump() if no event is given, make location.hash the target
  • also this technique might not catch the jump in time, so you'll better hide the html,body right away and show it back once you scrolled it back to zero

This is your code with the above added:

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

Verified working in Chrome/Safari, Firefox and Opera. I don't know about IE though.

Solution 2 - Jquery

On the link put a hash:

<a href="otherpage.html#elementID">Jump</a>

And on other page, you can do:

$('html,body').animate({
  scrollTop: $(window.location.hash).offset().top
});

On other page, you should have element with id set to elementID to scroll to. Of course you can change the name of it.

Solution 3 - Jquery

Combining answers by Petr and Sarfraz, I arrive at the following.

On page1.html:

<a href="page2.html#elementID">Jump</a>

On page2.html:

<script type="text/javascript">
	$(document).ready(function() {
		$('html, body').hide();

		if (window.location.hash) {
			setTimeout(function() {
				$('html, body').scrollTop(0).show();
				$('html, body').animate({
					scrollTop: $(window.location.hash).offset().top
					}, 1000)
			}, 0);
		}
		else {
			$('html, body').show();
		}
	});
</script>

Solution 4 - Jquery

I would like to recommend using the scrollTo plugin

http://demos.flesler.com/jquery/scrollTo/

You can the set scrollto by jquery css selector.

$('html,body').scrollTo( $(target), 800 );

I have had great luck with the accuracy of this plugin and its methods, where other methods of achieving the same effect like using .offset() or .position() have failed to be cross browser for me in the past. Not saying you can't use such methods, I'm sure there is a way to do it cross browser, I've just found scrollTo to be more reliable.

Solution 5 - Jquery

I made a reusable plugin that can do this... I left the binding to events outside the plugin itself because I feel it is too intrusive for such a little helper....

jQuery(function ($) {

	/**
	 * This small plugin will scrollTo a target, smoothly
	 *
	 * First argument = time to scroll to the target
	 * Second argument = set the hash in the current url yes or no
	 */
	$.fn.smoothScroll = function(t, setHash) {
		// Set time to t variable to if undefined 500 for 500ms transition
		t = t || 500;
		setHash = (typeof setHash == 'undefined') ? true : setHash;
	
		// Return this as a proper jQuery plugin should
		return this.each(function() {
			$('html, body').animate({
				scrollTop: $(this).offset().top
			}, t);
	
			// Lets set the hash to the current ID since if an event was prevented this doesn't get done
			if (this.id && setHash) {
				window.location.hash = this.id;
			}
		});
	};

});

Now next, we can onload just do this, check for a hash and if its there try to use it directly as a selector for jQuery. Now I couldn't easily test this at the time but I made similar stuff for production sites not long ago, if this doesn't immediatly work let me know and I'll look into the solution I got there.

(script should be within an onload section)

if (window.location.hash) {
	window.scrollTo(0,0);
	$(window.location.hash).smoothScroll();
}

Next we bind the plugin to onclick of anchors which only contain a hash in their href attribute.

(script should be within an onload section)

$('a[href^="#"]').click(function(e) {
	e.preventDefault();

	$($(this).attr('href')).smoothScroll();
});

Since jQuery doesn't do anything if the match itself fails we have a nice fallback for when a target on a page can't be found yay \o/

Update

Alternative onclick handler to scroll to the top when theres only a hash:

$('a[href^="#"]').click(function(e) {
	e.preventDefault();
	var href = $(this).attr('href');
	
	// In this case we have only a hash, so maybe we want to scroll to the top of the page?
	if(href.length === 1) { href = 'body' }
	  
	$(href).smoothScroll();
});

Here is also a simple jsfiddle that demonstrates the scrolling within page, onload is a little hard to set up...

http://jsfiddle.net/sg3s/bZnWN/

Update 2

So you might get in trouble with the window already scrolling to the element onload. This fixes that: window.scrollTo(0,0); it just scrolls the page to the left top. Added it to the code snippet above.

Solution 6 - Jquery

function scroll_down(){
	$.noConflict();
	jQuery(document).ready(function($) {
		$('html, body').animate({
			scrollTop : $("#bottom").offset().top
		}, 1);
	});
	return false;
}

here "bottom" is the div tag id where you want to scroll to. For changing the animation effects, you can change the time from '1' to a different value

Solution 7 - Jquery

I've written something that detects if the page contains the anchor that was clicked on, and if not, goes to the normal page, otherwise it scrolls to the specific section:

$('a[href*=\\#]').on('click',function(e) {

    var target = this.hash;
    var $target = $(target);
    console.log(targetname);
    var targetname = target.slice(1, target.length);

    if(document.getElementById(targetname) != null) {
         e.preventDefault();
    }
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top-120 //or the height of your fixed navigation 

    }, 900, 'swing', function () {
        window.location.hash = target;
  });
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDigital siteView Question on Stackoverflow
Solution 1 - JqueryPetr VostrelView Answer on Stackoverflow
Solution 2 - JquerySarfrazView Answer on Stackoverflow
Solution 3 - JqueryzanetuView Answer on Stackoverflow
Solution 4 - JqueryFresheyeballView Answer on Stackoverflow
Solution 5 - Jquerysg3sView Answer on Stackoverflow
Solution 6 - Jqueryuser1284907View Answer on Stackoverflow
Solution 7 - JqueryJohn-HenryView Answer on Stackoverflow