Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent scroll reset in AJAX

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?

like image 380
Gowtham Avatar asked Feb 20 '26 22:02

Gowtham


2 Answers

I'm french so forgive me for my bad English

I had the same thing on my page : when I clicked on the link, the XHR request reseted my scroll on full top. I've found my mistake...a very stupid one... Check your HTML, if your "onClick" is in a <a> tag, check you've not written <a href="#" onClick="myFunction()">... That was my mistake, and just <a onClick="myFunction()"> don't reset the scroll x)

Hope I've helped you

like image 127
Elephantin Avatar answered Feb 22 '26 10:02

Elephantin


You can use window.scrollTo(x, y) to set the position of scroll, for sample:

if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
   document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
   window.scrollTo(0, 0); //stay on the top
}
like image 26
Felipe Oriani Avatar answered Feb 22 '26 12:02

Felipe Oriani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!