jcgoble3
jcgoble3

Reputation: 625

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!

Upvotes: 5

Views: 2444

Answers (2)

jcgoble3
jcgoble3

Reputation: 625

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.)

Upvotes: 7

albert
albert

Reputation: 8153

CSS Tricks has an article that explains how to do that and more. I'm well aware link only answers are less than ideal here, however the question is asking for pointers in the right direction, so I believe its a good fit.

The bookmarklet from the tutorial prefills forms, so essentially you are going to want to gut it, but first peek into how it is finding form controls and prefilling them. Then tweak to fit your desired functionality, and finally rip everything else out that you do not need or use.

Prefilling Forms Custom Bookmarklet

Upvotes: 0

Related Questions