0

I want to make a script to insert emojis into textarea when click. But it never works.

Can anybody point me out where am I doing wrong?

Thank you.

<form>
    <button value=""></button>
    <button value=""></button>
    <button value=""></button>
    <br>
    <textarea id="text1" cols="40" rows="3" placeholder="This is some dummy text."></textarea>

</form>

<script type="text/javascript ">
    let currentInput = document.getElementById('text1');

    function insertAtCursor() {
        let cursorPos = currentInput.selectionStart;
        let v = currentInput.value;
        let textBefore = v.substring(0, cursorPos);
        let textAfter = v.substring(cursorPos, v.length);
        currentInput.value = textBefore + this.value + textAfter;

        cursorPos += this.value.length;
        currentInput.focus();
        currentInput.setSelectionRange(cursorPos, cursorPos);
    };


    if (document.querySelector('button')) {
        document.querySelectorAll('button').forEach((elem, i) => {
            elem.addEventListener("click", function(event) {

                insertAtCursor();

            });
        });
    }
</script>
Jimmy Xee
  • 27
  • 5
  • `this` is effectively meaningless in a regular function invoked without base reference. See [How does the "this" keyword work?](/q/3127429/4642212). Why not simply pass an argument of `elem` to `insertAtCursor` or use `elem.addEventListener("click", insertAtCursor);` instead? – Sebastian Simon Nov 04 '21 at 03:08
  • Use [event delegation](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple event listeners — it’s more maintainable, and applies to dynamically added elements. E.g., use an [event argument](//developer.mozilla.org/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback)’s [`target`](//developer.mozilla.org/docs/Web/API/Event/target). See [the tag info](/tags/event-delegation/info) and [What is DOM Event delegation?](/q/1687296/4642212). – Sebastian Simon Nov 04 '21 at 03:08
  • Thank you Sebastian, especially for your idea of event delegation. I had reformed my codes. Here it is: https://jsfiddle.net/jimmyxee/v73hs924/15/. Can you give me some advice? – Jimmy Xee Nov 05 '21 at 00:59
  • Looks fine. ‍♂️ Though, in general, I would test `e.target.closest("button")` instead of `e.target.nodeName === "BUTTON"`. If you ever decide to do `` instead, your version won’t work if you click on the `X`. – Sebastian Simon Nov 05 '21 at 06:56

0 Answers0