Scroll to anchor on page refresh

Hi all,

Adapting this code may not be the best method, see what you think.

I have a page where certain actions cause the page to reload and then jumps to an anchor (e.g. #title gets appended to the url) which is disorientating, I think it will soften the blow if the page scrolls to the anchor.

This is code I use to scroll to anchors with links on a page

$(document).ready(function(){
	
	  $('a[href*=#]').click(function() {
		if (location.pathname.replace(/^\\//,'') == this.pathname.replace(/^\\//,'')
		&& location.hostname == this.hostname) {
		  var $target = $(this.hash);
		  $target = $target.length && $target
		  || $('[name=' + this.hash.slice(1) +']');
		  if ($target.length) {
			var targetOffset = $target.offset().top;
			$('html,body')
			.animate({scrollTop: targetOffset}, 1000);
		   return false;
		  }
		}
		});	
	});

I see that this is a click function. Can this just be amended so that it checks the url and scrolls accordingly?

In an ideal world (not sure if this is possible) the page would reload in the same position it was in before the reload. Then remove the need for the scroll.

Any input will be welcomed : )

Mike

You could just rip the guts out of that method and have it outside the click handler.

Though I don’t see why this would be occurring. When linking to an anchor the page should automagically scroll to it without intervention.

Do you perhaps have a test page up somewhere that shows the problem?

Hi, sorry for the late reply.

I tried taking the code outside the click handler, but it didn’t seem to work (I’m not too great with .js so I may have mistyped). When the page reloads, it does jump to the correct anchor but it doesn’t scroll.

I can’t display a test page on here but I can PM you the link if this still is enough information.

Many thanks

Hi, I managed to find a solution to this with a plugin called Softscroll : )