How to show div after selecting text, even if the initial click is outside the div=text

34 Views Asked by At

I have a div=text, which contains the text to be selected, and another div=asd that is displayed when selecting the text inside the div=text.

If you have no text selection AND you click outside the div=text the div=asd is hidden.

The code works perfectly, the question is if the user makes an initial selection that exceeds the limits of the div=text the div=asd is not displayed.

it's as if the initial selection that exceeds the limit of the div=text is taking the click function out, this function can only be executed if it has no selection.

The error is at the time of finalizing the selection. If the click happens outside the div=text, the div=asd is not displayed.

const text = document.querySelector("#text");
const asd = document.querySelector("#asd");
let isShowing = false;

text.addEventListener("click", function() {
  let selection = window.getSelection();
  if (selection.toString().length > 0) {
    isShowing = true;
    const rect = selection.getRangeAt(0).getBoundingClientRect();
    asd.style.left = rect.left + "px";
    asd.style.top = rect.bottom + "px";
    asd.style.display = "block";
  } else {
    asd.style.display = "none";
    isShowing = false;
  }
});

document.addEventListener("click", function(event) {
  if (!isShowing && !text.contains(event.target)) {
    asd.style.display = "none";
    isShowing = false;
  }
});
#asd {
    position: absolute;
    display: none;
    background-color: #f2f2f2;
    padding: 10px;
}   
<p>Select the text below to display the div='asd':</p>
<p id="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed at risus euismod,
  condimentum massa vel, interdum nisl. Sed euismod, massa vel condimentum interdum nisl. </p>

<div id="asd">
  div content
</div>

I tried using a variable is Showing=false/true, but it didn't solve the problem.

enter image description here

0

There are 0 best solutions below