Search code examples
javascriptbookmarklet

How to create a JS bookmarklet to insert fixed text at cursor position?


I want to create a bookmarklet that I can drop on my browser's bookmark toolbar which, when clicked, inserts a fixed, predefined text (in my use case, a shruggie: ¯\_(ツ)_/¯ ) at the current cursor position (assuming that the cursor is in an editable input field or textarea). However, I am a beginner at JavaScript, and can't figure out how to get started doing this. Any help? If I can get a pointer in the right direction, I can probably figure it out from there. Thanks!


Solution

  • Apologies for the delay; life threw a few curveballs at me right about the time I posted the question, and I forgot about this until StackOverflow notified me of the responses tonight.

    The comment by afuous gave me everything I was looking for, and I now have a working bookmarklet. For anyone else who comes across this, here it is:

    javascript:(function(a){a.value=a.value.slice(0,a.selectionStart)+"%C2%AF\\_(%E3%83%84)_/%C2%AF"+a.value.slice(a.selectionEnd);})(document.activeElement);

    Or, as JavaScript that hasn't been converted to bookmarklet form:

    (function (a) {
      a.value =
        a.value.slice(0, a.selectionStart) +
        "¯\\_(ツ)_/¯" +
        a.value.slice(a.selectionEnd);
    })(document.activeElement);
    

    This has the benefit of allowing for me to select a portion of a text and use the bookmarklet to replace the selection with a shruggie, as if I had hit a hypothetical shruggie key on the keyboard.

    Feel free to steal and modify as you see fit. This has been tested only in Firefox 50.0.2, but I think it should work in all modern browsers. (It won't work in Internet Explorer 8 or earlier.)