4

I have a scenario,where I need to show a div(like popup) on-select of text in text-area.But, I used mouse-down for it,the position of div is not exactly below the text sometimes.

JavaScript:

    function getSel() {
    // obtain the object reference for the textarea>
    var txtarea = document.getElementById("mytextarea");
    // obtain the index of the first selected character
    var start = txtarea.selectionStart;
    // obtain the index of the last selected character
    var finish = txtarea.selectionEnd;
    //obtain all Text
    var allText = txtarea.value;
    // obtain the selected text
    var sel = allText.substring(start, finish);
    sel = sel.replace(/[\S]/g, "*");
    //append te text;
    var newText = allText.substring(0, start) + sel + allText.substring(finish, allText.length);
    txtarea.value = newText;
    $('#newpost').offset({ top: 0, left: 0 }).hide();
}

$(document).ready(function () {
    var position;
    $('#newpost').hide();
    $('#mytextarea').on('select', function (e) {
        var str = $('#mytextarea').val();
        $('#newpost').offset(position).show();
        var txtarea = document.getElementById("mytextarea");
        var start = txtarea.selectionStart;
        var finish = txtarea.selectionEnd;
        $('#newpost div').text('Replace with stars');
    }).on('select', function (e) {
        position = { top: e.pageY+10, left: e.pageX };
    });
    $('#newpost').hide();
});
function closePopUp() {
    $('#newpost').hide();
}

Here is my plunker link

Here my requirement is to show a div on-select of text.But when I am using on-select instead of mouse-down,the div is showing below text-area.

Thanks in Advance.

anub
  • 527
  • 1
  • 4
  • 21

2 Answers2

2

A few days ago in this answer I suggested an approach of finding the cursor position and displaying a div over the textarea when the user selects some text.

This approach works, however, as @anub has mentioned, div is sometimes displayed not right under the selected text, but a couple of pixels up or down - because it's position is determined based on the first user's click.

After a short search I found this post that describes how to find the position of the selected text in the textarea by creating a temporary div clone of the given textarea.

I've adopted the getCursorXY method from there and used it to position the popup.

Give it a try!

function getSel() {
    // obtain the object reference for the textarea>
    var txtarea = document.getElementById("mytextarea");
    // obtain the index of the first selected character
    var start = txtarea.selectionStart;
    // obtain the index of the last selected character
    var finish = txtarea.selectionEnd;
    //obtain all Text
    var allText = txtarea.value;

    // obtain the selected text
    var sel = Array(finish - start + 1).join("*");
    //append te text;
    var newText = allText.substring(0, start) + sel + allText.substring(finish, allText.length);
    txtarea.value = newText;
    
    $('#newpost').offset({top: 0, left: 0}).hide();
}
function closePopUp() {
    $('#newpost').offset({top: 0, left: 0}).hide();
}

$(document).ready(function () {
    closePopUp();
    var newpost = $('#newpost');
    $('#mytextarea').on('select', function (e) {
        var txtarea = document.getElementById("mytextarea");
        var start = txtarea.selectionStart;
        var finish = txtarea.selectionEnd;
        newpost.offset(getCursorXY(txtarea, start, 20)).show();
        newpost.find('div').text(Array(finish - start + 1).join("*"));
    });
});

const getCursorXY = (input, selectionPoint, offset) => {
  const {
    offsetLeft: inputX,
    offsetTop: inputY,
  } = input
  // create a dummy element that will be a clone of our input
  const div = document.createElement('div')
  // get the computed style of the input and clone it onto the dummy element
  const copyStyle = getComputedStyle(input)
  for (const prop of copyStyle) {
    div.style[prop] = copyStyle[prop]
  }
  // we need a character that will replace whitespace when filling our dummy element 
  // if it's a single line <input/>
  const swap = '.'
  const inputValue = input.tagName === 'INPUT' ? input.value.replace(/ /g, swap) : input.value
  // set the div content to that of the textarea up until selection
  const textContent = inputValue.substr(0, selectionPoint)
  // set the text content of the dummy element div
  div.textContent = textContent
  if (input.tagName === 'TEXTAREA') div.style.height = 'auto'
  // if a single line input then the div needs to be single line and not break out like a text area
  if (input.tagName === 'INPUT') div.style.width = 'auto'
  // create a marker element to obtain caret position
  const span = document.createElement('span')
  // give the span the textContent of remaining content so that the recreated dummy element 
  // is as close as possible
  span.textContent = inputValue.substr(selectionPoint) || '.'
  // append the span marker to the div
  div.appendChild(span)
  // append the dummy element to the body
  document.body.appendChild(div)
  // get the marker position, this is the caret position top and left relative to the input
  const { offsetLeft: spanX, offsetTop: spanY } = span
  // lastly, remove that dummy element
  // NOTE:: can comment this out for debugging purposes if you want to see where that span is rendered
  document.body.removeChild(div)
  // return an object with the x and y of the caret. account for input positioning 
  // so that you don't need to wrap the input
  return {
    left: inputX + spanX,
    top: inputY + spanY + offset,
  }
}
#mytextarea {width: 600px; height: 200px; overflow:hidden; position:fixed}
#newpost {
    position:absolute;
    background-color:#ffffdc;
    border:1px solid #DCDCDC;
    border-radius:10px;
    padding-right:5px; 
    width: auto;
    height: 30px;
}
#newpost span {
    cursor:pointer;
    position: absolute;
    top: 0;
    right: 5px;
    font-size: 22px;
}
#newpost div {
    color:#0000ff;
    padding:10px;
    margin-right:10px;
    width: auto;
    cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <head>
  </head>
 <body>
    <textArea id="mytextarea"></textArea>
    <div id="newpost">
        <span onclick="closePopUp();">&#735;</span>
        <div onclick="getSel()"></div>
    </div>
</body>

</html>
Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42
  • thanks a lot..It works for me..But default actions like(Ctrl+z) is not working after text is replaced..Can you help me in this.. – anub Jan 29 '18 at 09:30
  • @anub If this answer helped then please accept it. And then you can ask a new question about [capturing ctr+z key event in javascript](https://stackoverflow.com/questions/16006583/capturing-ctrlz-key-combination-in-javascript). If you post a link to your new question here, I will be glad to help you. – Kirill Simonov Jan 29 '18 at 09:47
  • @anub seems like it's closed as a duplicate. Indeed you should follow the steps described in that answer: listen for a key event and check the codes: `evtobj.keyCode == 90 && evtobj.ctrlKey`. If it matches, do something like this `var newText = allText.substring(0, start) + text+ allText.substring(finish, allText.length);` but use the previously saved `start`, `finish` and `text` – Kirill Simonov Jan 29 '18 at 10:32
  • Don't forget to call `e.preventDefault();` to prevent default Ctr+Z – Kirill Simonov Jan 29 '18 at 10:33
  • I can't get you..I will post another ask..There you can answer – anub Jan 29 '18 at 10:34
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/164079/discussion-between-anub-and-kirill-simonov). – anub Jan 29 '18 at 10:37
0

I have encountered that problem while close the popup and reselecting another region, I resolved that by

function closePopUp() {
    $('#newpost').offset({ top: 0, left: 0 }).hide();
}

check this out

Aswin Ramesh
  • 1,654
  • 1
  • 13
  • 13
  • but here my issue is to show,onselect popup instead of mousedown – anub Jan 29 '18 at 07:33
  • @anub But I think you would get the offset only by using mouse events, the issue I encountered is that the popup is moving downwards as I keep on closing and reselecting a region, at that time the position of the popup is not resetting, that why I ask you to change the offset while hiding the popup – Aswin Ramesh Jan 29 '18 at 07:54