I have a div container that gets its content modified every 3 seconds by a JavaScript function. The function is initially called by the onload event of the body tag.
function showNow(){
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "tab.php", true);
xmlhttp.send();
setTimeout(showNow, 3000);
}
The content is being refreshed every 3 seconds. The only problem is that the scroll position is being reset and hence my page jumps back to beginning. This is affecting the usability highly.
Can anyone please suggest a solution?
Before the innerHTML is set, you could get the txtHint
element's scrollTop
property. Then, after the text is added, set that variable to scrollTop
again.
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var scroll = document.body.scrollTop;
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
document.body.scrollTop = scroll;
}