So I’ve got a js function that’s triggered when an option is chosen from a <select> element. This function triggers some DOM manipulation< and for whatever reason it makes the scrollbar shoot up to the top every time. This is frustrating, because I switched my old form data to ajax to avoid this problem.
I’ve researched this problem and found this:
How to prevent page's scroll position reset after DOM manipulation?
But I’m not calling the function from a link, rather an onchange event within a select form, so I don’t know how to apply the provided solutions.
Here’s the form element calling the function:
<div id="imageTable">
<form action="">
<select onchange="getOption()" name="dir">
<option value="Anotherguyly">Anotherguyly</option>
<option value="Hello">Hello</option>
<option value="page1">page1</option>
<option value="pageish2">pageish2</option>
</select>
</form>
</div>
Here are the js functions in the header:
function getOption() {
var selectDOM = document.getElementById("imageTable").getElementsByTagName("select")[0];
var i = selectDOM.selectedIndex;
var selectedChoices = selectDOM.options;
var selectedText = selectedChoices[i].value
resetImageTable(selectedText);
}
function resetImageTable(option) {
// clears out previous DOM elements, inserts new chosen by the provided option
}
I suspect the answer is in the order of execution.
clears out previous DOM elementsis very likely to influence the effective scroll position.Rather than removing and then adding nodes, consider applying a CSS
visibility:hiddento all current images, and then swapping them out for the newly loaded images. If there are fewer new than old, remove the stragglers at the end of the function call; if there are more new than old, then continue to add them beyond replacement.This approach would result in minimal scroll position change.