Scroll to bottom of div after changing contents using Javascript - javascript

For some reason the methods to scroll to bottom of div are not working for me after refreshing its contents using Ajax.
I think the issue has something to do with how the DOM works--eg when it makes its changes, however, I don't know enough about javascript or the DOM to really understand how that would interfere with scrolling to bottom.
So I think the issue is when and how to call the methods rather than the methods themselves. Can anyone suggest a way to scroll to bottom after the refresh of div?
Methods to scroll to bottom I am trying:
Method 1:
var element = document.getElementById("chatBox");
element.scrollTop = element.scrollHeight;
Method 2:
document.getElementById('chatBox').scrollIntoView({ behavior: 'smooth', block: 'end' });
Method that refreshes div:
function refreshDiv() {
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)
{
alert("got 200");
document.getElementById("chatBox").innerHTML=xmlhttp.responseText;
alert("will now try to update Scroll");
//FOLLOWING HAS NO EFFECT POSSIBLY BECAUSE DOM HAS NOT YET RETURNED RESULTS
document.getElementById('chatBox').scrollIntoView({ behavior: 'smooth', block: 'end' });
}
}
xmlhttp.open("GET","refreshDiv.php,true);
xmlhttp.send();
return;
//THIS ALSO HAS NO EFFECT POSSIBLY AS IT IS AFTER RETURN
document.getElementById('chatBox').scrollIntoView({ behavior: 'smooth', block: 'end' });
}
What is the proper place to call scroll to bottom after refreshing div?

use this script to scroll to bottom of div
var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;

Related

External php page taking too long to parse and load with javascript

I have a code that is supposed to get an external page (In this cage, php) parse and load inside another page, it's like an iframe, but it uses javascript. The code is working, but it's the last thing that is executed on the page, it has to wait everything on the whole page to load, so it can be executed.
What I need to achieve is that I need it to load with the page, or before the page loads.
I believe it's because of the even window.addEventListener.
<div style="min-height:300px;
display: block;">
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
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("myDiv020103").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.jonasweb.net/samples.php",true);
xmlhttp.send();
}
if(window.addEventListener){
window.addEventListener('load',loadXMLDoc,false); //W3C
}
else{
window.attachEvent('onload',loadXMLDoc); //IE
}
</script>
<div width="100%" id="myDiv020103"></div>
</div>
<div style="clear:both"></div>
I tried creating a fidle, but it's not working, http://jsfiddle.net/5wcncs1x/
It only works on a host.
I found out by myself. Just had to change:
if(window.addEventListener){
window.addEventListener('load',loadXMLDoc,false); //W3C
}
else{
window.attachEvent('onload',loadXMLDoc); //IE
}
for
document.addEventListener("DOMContentLoaded", loadXMLDoc, false);document.addEventListener("DOMContentLoaded", loadXMLDoc, false);

Drop down menu with hover and up and down key selections - conflict code

I have created a drop down menu with the help from stackoverflow users and this
LINK HERE from w3schools.
<script>
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
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","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
However, I am having problems implementing this code to include a function that will pick up on the user selecting without the use of a mouse (i.e key up and key down). I have tried to implement the following example from another thread on stackoverflow: LINK HERE and a FIDDLE HERE but to no avail.
var active = document.querySelector(".hover") || document.querySelector(".dropdownItemContainer li");
document.addEventListener("keydown",handler);
document.addEventListener("mouseover",handler);
function handler(e){
console.log(e.which);
active.classList.remove("hover");
if (e.which == 40){
active = active.nextElementSibling || active;
}else if (e.which == 38){
active = active.previousElementSibling || active;
}else{
active = e.target;
}
active.classList.add("hover");
}
What happens is depending on where I place my code in my javascript sheet, it either does not work at all, or when a down key is pressed, it automatically jumps back up to the top selection. If I hold down the down key, it rapidly filters through all selections until it hits the bottom, then flicks back again to the top selection.
By implementing an alert in between each up key and down key, the result works. Therefore something is conflicting.
Does anyone have any clues on how to remove this conflict? Or are able to overcome this?
I am not interested in jquery, and any help or further links that may be of help will be welcomed.

Refresh only one div with AJAX

I want to dynamically reload only one div in my page every five seconds. But in my response I get the content of the whole page... How can I get only the content of the specified div ?
<script>
function ajaxrefresh()
{
var xmlhttp;
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)
{
//Here i want only the content for the div from the response
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
else
{
//alert("state: "+xmlhttp.readyState)
//alert("status: "+xmlhttp.status)
}
}
xmlhttp.open("GET","http://${localHostAddress}:8080/adress",true);
xmlhttp.send();
var t=setTimeout(ajaxrefresh,5000);
}
window.load = ajaxrefresh();
</script>
Someone has already ask something like this on SO. Best voted-up is to create an invisible div in your page, and fill it with the AJAX response to be able to get back element you need with hiddenDiv.getElementById("myDiv").
As you can not use Jquery, I think your best bet is in response to ajax call return only the div contents from server side. this way your response size will be smaller and hence faster too...
if you can not change the response of request use below code
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//Here i want only the content for the div from the response
var mydiv= document.getElementById("myDiv");
var doc=document.createElement("div");
doc.innerHTML=xmlhttp.responseText;
document.body.appendChild(doc); // Note append temp to document
mydiv.innerHTML=doc.getElementById("theDivYouWant")
.innerHTML;
document.body.removeChild(doc);// Note remove temp from document
May be you will get some idea from below script:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_div_refresh = setInterval(function(){
$('#load_data').load('fb_count.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
You could try something like this:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//Here i want only the content for the div from the response
var doc=document.createElement("div");
doc.innerHTML=xmlhttp.responseText;
document.getElementById("myDiv").innerHTML=doc.getElementsByTagName("div")[5]
.innerHTML
Here 5 is just a random number, if the div is always fixed you can use the number that the div is located and if it's not you need to loop through the divs and find the one you're looking for (maybe based on id).

Dynamically adding HTML using .innerHTML (formatting issue in IE7)

I have a select dropdown that when updated takes the new variable and dynamically updates the div directly below it.
HERE is my select input:
<select name='region_name' onchange='showDistrict(this.value)'>
here is my javascript that controls the dynamic stuff:
<script>
function showDistrict(str)
{
if (str=="")
{
document.getElementById("district_div").innerHTML="";
return;
}
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("district_div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getdistrict.php?q="+str,true);
xmlhttp.send();
}
</script>
The page getdistrict.php?q= does another MySQL call and loops out info into the div "district_div" MY PROBLEM IS... that div region does not stretch correctly in IE 7. So my dynamic data overlays everything below it.
When I look at the source with firebug I don't even see the new html from innerHTML so I am not sure this is a css issue or something having to do with .innerHTML
do not set any width or height for this DIV, or set only min-width min-height, and you can also set overflow:hidden for this DIV

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?
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
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
}
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;
}
try adding
return false;
at end of the ajax request
Not sure this was answered completely.
I had the same problem, trying all solutions above did not solve it. What i found was that refreshing the innerHTML actually made the Scrollbar disappear for a very short period of time (because the entire page becomes a lot smaller in height as the content gets refreshed), subsequently when content reappears (and the Scrollbar) the browser has no way of knowing where he was before the call and hence scrolls all the way up.
My own solution was very simple and does not involve catching events etc..., I added a column which I filled with a spacer.gif the height of the div I intend to refresh. That way the entire page layout itself never actually gets distorted, the Scrollbar never disappear even a short period of time.
<table width="30%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td>
<img src="/images/spacer.gif" width="0" height="170"/> <-- adding the extra column to keep the height always the same.
</td>
<td>
<div id="content">
<script>loadnewusermenu()</script> <-- content getting refreshed
</div>
</td>
</tr>
</table>
Hope it makes sense.
DjYoy

Categories

Resources