开发者

How to prevent page's scroll position reset after DOM manipulation?

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开发者_如何学Go 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.


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.


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>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜