kentor kentor - 2 months ago 6
HTML Question

Check if any text inside of ul is selected

I am coding a log message box / same function as a chat and I would like to set my AutoScrollDown Boolean to false once someone selects text inside of the chat (if the user wants paste something for example).

I realized my log message/chat box with an ul and lis, which looks like this:

<ul id="1" class="logbox">
<li class="debug"><b>At</b> w3schools.com you will learn how to make a website. We offer free tutorials in all web development technologies.learn how to make a website. We offer free tutorials in all web development technologies.</li>
<li class="error"><b>At</b> w3schools.com you will learn how to make a website. We offer free tutorials in all web development technologies.</li>
<li class="warning"><b>At</b> w3schools.com you will learn how to make a website. We offer free tutorials in all web development technologies.</li>
<li>blabla</li>
</ul>


I have tried the following events to check if content inside of my ul is selected or not, which didn't work:

$("#1").on("focus", function() {
autoScrollEnabled = 0;
});

$("#1").off("focus", function() {
autoScrollEnabled = 1;
});


My question:
How can I set
autoScrollEnabled
to 0 once someone selects/highlights text inside of my ul and how can I check if the user has stopped selecting/highligting any text.

Answer

To detect if user's are highlighting text in the log box, you should first listen for the mousedown event and then see if there are any mousemove events while the mouse is still down. You can set your flag to false either on mouse down or on mouse move, and then reset it in the mouseup event.

document.querySelector('#one').addEventListener('mousedown', function (event) {

  window.onmousemove = function (event) {
    console.log('the user is selecting text');
  }
  
  window.onmouseup = function (event) {
    console.log('the user mousedup');
    console.log(window.getSelection());
    autoScrollEnabled = 1;
    window.onmousemove = null;
    window.onmouseup = null;
  }
  
  console.log('user mouseddown in ' + event.target.nodeName);
  autoScrollEnabled = 0;
}, false);
<ul id="one" class="logbox">
   <li class="debug"><b>At</b> w3schools.com you will learn how to make a website. We offer free tutorials in all web development technologies.learn how to make a website. We offer free tutorials in all web development technologies.</li>
   <li class="error"><b>At</b> w3schools.com you will learn how to make a website. We offer free tutorials in all web development technologies.</li>
   <li class="warning"><b>At</b> w3schools.com you will learn how to make a website. We offer free tutorials in all web development technologies.</li>
   <li>blabla</li>
</ul>

Comments