I’ve tried to autoscroll my div but I wanted to add a checkbox to users can select this event (scroll or not)
I used If statement but doesn’t work, if it is one time checked, always return my function to autoscroll my chat window.
here is my code
JavaScript
x
13
13
1
const chat_win = document.getElementById('chat-window')
2
const autoscroll = document.getElementById('autoscroll')
3
4
autoscroll.onchange = function() {
5
checked = autoscroll.checked;
6
console.log(checked);
7
if(checked == true) pageScroll()
8
else return;
9
}
10
function pageScroll() {
11
chat_win.scrollBy(0, 5);
12
scrolldelay = setInterval(pageScroll, 10);
13
}
Advertisement
Answer
JavaScript
1
19
19
1
// every second white to chat
2
setInterval( function() {
3
let d = document.createElement( "div" );
4
d.innerText = new Date().toGMTString();
5
document.getElementById( "chat_window" ).appendChild( d );
6
}, 1000 );
7
8
var chat_window_scroll_interval;
9
document.getElementById( "autoscroll_chbx" ).addEventListener( "change", function() {
10
// this == checkbox
11
if ( this.checked ) {
12
// scroll every 1 second by 40px vertically
13
chat_window_scroll_interval = setInterval( function() {
14
document.getElementById( "chat_window" ).scrollBy( 0, 40 );
15
}, 1000 );
16
} else {
17
clearInterval( chat_window_scroll_interval );
18
}
19
} );
JavaScript
1
6
1
#chat_window {
2
height: 200px;
3
max-height: 200px;
4
width: 200px;
5
overflow-y: auto;
6
}
JavaScript
1
2
1
<div id="chat_window"></div>
2
<input type="checkbox" id="autoscroll_chbx" />