Skip to content
Advertisement

CommonJS I Can’t uncheck the Checkbox

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

const chat_win = document.getElementById('chat-window')
const autoscroll = document.getElementById('autoscroll')

autoscroll.onchange = function() {
    checked = autoscroll.checked;
    console.log(checked);
    if(checked == true) pageScroll()
    else return;
}
function pageScroll() {
    chat_win.scrollBy(0, 5);
    scrolldelay = setInterval(pageScroll, 10);
}

Advertisement

Answer

// every second white to chat
setInterval( function() {
  let d = document.createElement( "div" );
  d.innerText = new Date().toGMTString();
  document.getElementById( "chat_window" ).appendChild( d );
}, 1000 );

var chat_window_scroll_interval;
document.getElementById( "autoscroll_chbx" ).addEventListener( "change", function() {
  // this == checkbox
  if ( this.checked ) {
    // scroll every 1 second by 40px vertically
    chat_window_scroll_interval = setInterval( function() {
       document.getElementById( "chat_window" ).scrollBy( 0, 40 );
    }, 1000 );
  } else {
    clearInterval( chat_window_scroll_interval );
  }
} );
#chat_window {
  height: 200px;
  max-height: 200px;
  width: 200px;
  overflow-y: auto;
}
<div id="chat_window"></div>
<input type="checkbox" id="autoscroll_chbx" />
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement