views:

404

answers:

2

I've got two JS functions, one that is adding options to a select box

function addOption(selectId, text, value) {
    var selectbox = document.getElementById(selectId);
    var optNew = document.createElement('option');
    optNew.text = text;
    optNew.value = value;
    try {
        selectbox.add(optNew, null); //page position resets after this
    }
    catch(ex) {
        selectbox.add(optNew);
    }    
}

and another that is doing a document.getElementById(formId).appendChild(newHiddenInput) in a similarly simple function.

They both work, elements are added as expected. However, upon calling either of them, the page resets its scroll position to the top of the page in both IE6 and FF. There is no postback, this is purely clientside manipulation. I've set breakpoints in Firebug, and it occurs immediately after the element.appendChild or select.add gets executed. I know I can use JS to manually set a scroll position, but I didn't think it was necessary when the page isn't being re-rendered.

I'm no expert with JS or the DOM, so I may very well be missing something, but I've looked here and ran through their examples with the Try it Here options and I can't replicate the problem, indicating the codebase I'm working with is the culprit.

Any ideas why the scroll position is being reset? jQuery is available to me as well, if it provides a better alternative.

+1  A: 

If the functions are being called from a link you might have an internal anchor in your link:

http://www.website.com/page.html#

This is causing said behavior. The default behavior is that if an anchor does not exist, the page scroll position jumps to the top (scrollTop = 0).

If this happens on every function call regardless of the source, then this can be crossed off the list.

Yuval A
Thank you! The functions were being called from <a href="#" onclick="addOption"> style "buttons". I've switched them to span tags and that fixed the problem.
Matt Garrison
That's not (necessarily) the solution, but may be in your case. For future reference, when using an anchor tag, you typically want a valid href in it, but may not want to actually have it go anywhere as you are pre-empting the behavior with javascript. That's when you need to use the "return: false;"
DA
+1  A: 

What is activating the event?

If it's an anchor then on the click event you need to "return false;" after the call to your jQuery/Ajax/jScript code.

If it's a button you may need to do the same.

I had this issue yesterday and this was the resolution.

So <a href="#" onclick="DoStuff(); return false;">My link</a>

griegs