views:

52

answers:

3

My page adds # to the html programatically and have this in the tag

function InsertTag(){
//Add <a name="spot"></a> to the middle of this document
}

window.addEventListener('load', InsertTag, false);

my question is how can I make the document then jump to #spot?

+1  A: 

Here's a suggestion: use id's instead. If you have:

<div id="something">

Then page.html#something will take you straight to that div. It doesn't have to be a div, it can be used on any element. If you can manipulate the DOM to add that anchor, I am pretty sure you'll be able to do this.


Now... To get there, you can use:

// this approach should work with anchors too
window.location.hash = 'something';

// or scroll silently to position
var node = document.getElementById('something');
window.scroll(0, node.offsetTop);

See it in action here: http://ablazex.com/demos/jump.html

There are subtle differences between the methods. Eg: The first one will cause the location on the address bar to be updated, the second one won't.

If you want it to look nicer you can use a jQuery plugin, like ScrollTo.

NullUserException
A: 

Try

window.location = currentUrl+'#spot';

where currentUrl is a variable having the address of the current url

naiquevin
tried it before. it keeps refreshing the page since i added #spot programatically.
Rana
oh yes. didnt think of it. window.scroll is the best option then imo
naiquevin
A: 

You can try this.

var el = document.getElementById('spot');
var eloffsetTop = el.offsetTop;
window.scroll(0,eloffsetTop);
Shardiwal