2

I am showing a popup on text highlight using JavaScript. But I’m not able to position it at the center of the highlight,

Same as medium.com text highlight popup. I want the .toolbar at the center of the highlighted text like these images below.

  const

    getRoot = document.querySelector('.root'),
    getTool = document.querySelector('.toolbar');


  document.addEventListener('mouseup', e => {
    window.getSelection().toString().length ?
      (
        getTool.style.left = e.clientX + 'px',
        getTool.style.top = e.clientY + 'px',
        getTool.classList.add('active')
      ) : null;
  });

  document.addEventListener('mousedown', () => {
    window.getSelection().toString().length < 1 ?
      getTool.classList.remove('active') : null;
  });
  *,
  *::before,
  *::after {
    box-sizing: border-box;
  }

  body {
    margin: 0;
  }

  .root {
    max-width: 500px;
    margin: 1rem auto;
    font-size: 21px;
    line-height: 1.8;
    font-family: Times new roman;
  }

  .toolbar {
    display: none;
    position: absolute;
    height: 45px;
    width: 220px;
    background-color: #212121;
    border-radius: .25rem;
    transition: .2s;
  }

  .toolbar.active {
    display: block;
  }
<div class="toolbar"></div>

<div class="root">
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos dignissimos porro explicabo soluta totam illum. Lorem
    ipsum dolor sit amet consectetur adipisicing elit. Architecto, sunt.</p>
</div>

Medium.com

enter image description here enter image description here

Tahazzot
  • 1,224
  • 6
  • 27

1 Answers1

1

Like in this post you should use selection range and range boundingClientRect

 document.addEventListener('mouseup', e => {
    s = window.getSelection()
    oRange = s.getRangeAt(0); //get the text range
    oRect = oRange.getBoundingClientRect();
    s.toString().length ?
      (
        getTool.style.left = ((oRect.left + oRect.width / 2) -110)  + 'px', // 110 is toolbox.width/2
        getTool.style.top = (oRect.top - 45 - 10) + 'px', //45 is toolbow.height
        getTool.classList.add('active')
      ) : null;
  });
JB_DELR
  • 737
  • 1
  • 4
  • 7