Actual page reference: www.friendsinclass.co.nf
I'm building a simple chat, and I have one problem. The chat scrollbar auto-scrolls down when loading the page, as you can see in the updatescroll() function at the bottom. Currently, updatescroll is also called every second in setInterval within $(document).ready, in order to scroll down when a new message is written. As you can see, there is also a call to autoscroll() in submitChat(), which means autoscroll gets called everytime I SUBMIT a message. The problem is that if a user that OTHER THAN ME submits a message, autoscroll will not get called, hence me setting autoscroll every 1 second to solve this.
PROBLEM: if a user wants to scroll up to see old messages, autoscroll will bring the scroll down again every 1 second, making his search useless. HOW TO SOLVE THIS PROBLEM IN AS EASY WAY? I've tried many ways but it won't work, also I am not very good with Jquery so PLEASE be as simple as possible.
Many thank you! JS below
function submitChat() {
form1.uname.readOnly = true;
form1.uname.style.border = 'none';
var uname = form1.uname.value;
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4&&xmlhttp.status==200) {
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
setTimeout(function(){ updateScroll(); }, 100);
}
}
xmlhttp.open('GET','insert.php?uname='+uname+'&msg='+msg,true);
xmlhttp.send();
setTimeout(function(){ updateScroll(); }, 100);
}
$(document).ready(
function(e) {
$.ajaxSetup({cache:false});
setInterval(function({$('#chatlogs').load('logs.php');updateScroll();}, 1000);
setTimeout(function(){ updateScroll(); }, 1200);
});
</script>
<script language="javascript">
function toggleState(item){
if(item.className == "on") {
item.className="off";
}
else {
item.className="on";
}
}
</script>
<script>
function updateScroll() {
var element = document.getElementById("chatlogs");
var elementHeight = element.scrollHeight;
element.scrollTop = elementHeight;
}
window.onload = updateScroll;
</script>
PS One solution could be using a toggleswitch I created, a simple button which turns red and blue. For instance, when clicked it could call updateScroll() every second, and turn it off again when clicked again. But I don't know how to connect its changing class to the functions.
CSS of toggle switch:
.on { background:blue; }
.off { background:red; }
HTML Toggle:
<input type="button" id="btn" value="button"
class="off" onclick="toggleState(this)" />