mercredi 7 juillet 2021

Javascript check if a class name has been added to DIV and perform task

I have the following functions:

<div class="chat-box"></div>

setInterval(() => {
  let xhr = new XMLHttpRequest();
  xhr.open("POST", "processes/get-chat.php", true);
  xhr.onload = ()=> {
    if(xhr.readyState === XMLHttpRequest.DONE) {
      if(xhr.status === 200) {
        let data = xhr.response;
        chatBox.innerHTML = data;
        // if(!chatBox.classList.contains("active")) {}
      }
    }
  }
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.send("incoming_id=" + incoming_id);
}, 500);

if(chatBox.classList.contains("active")) {
  $('html,body').animate({scrollTop: document.body.scrollHeight},"fast");
}

I want to check if the chatbox div has the class name active and move to the bottom of the div automatically. The active class is being added from the setInterval function. However, I cannot the if condition inside the setInterval function because it will then be executed ever n amount of time and then I won't be able to scroll up and read the contents. It will take me to the bottom every n seconds. Therefore, I want the scroll to bottom to be executed only once. For this, I have placed it outside of setInterval function. But, this does not seem to be working. What can be the issue here? How can I make this work? Any help would be appreciated. Thanks :)

Aucun commentaire:

Enregistrer un commentaire