What are Bookmarklets?

Bookmarklets are small blocks of JavaScript code that are stored as bookmark URLs and run directly from an internet browser. Although there are a variety of uses for bookmarklets, using them to save time on monotonous tasks is my personal favorite. Anytime you find yourself completing a web form over and over, in a manner according to a set of rules, a bookmarklet can probably help you save time! If you’re someone who wants to learn how to create bookmarklets, follow along as we build several examples and use them in the reactive environment below.

You will not need any previous JavaScript experience for this tutorial, but it would be prudent to review the syntax on a website like w3schools if you are new to the language. It would also be helpful to have a text editor with syntax-highlighting (such as Atom or Sublime Text). Before starting with the examples below, create a new “bookmarklet.js” file and open that file using your text editor.

How do I Write a Bookmarklet?

It can be helpful to think of writing the bookmarklet in three parts. The first part tells the browser that the bookmark will be composed of JavaScript code. The second part defines the anonymous function where we tell the browser what we want to do. The third and final part involves calling the previously defined anonymous function and ending the bookmarklet. To better visualize the three parts of the bookmarklet, review the three distinct segments below.

javascript: ( function() { /* Insert bookmarklet code here */ }) ();

For improved readability in our example bookmarklets, we will be joining the 1st and 2nd components together as shown below.

javascript: ( function() { /* Insert bookmarklet code here */ }) ();

A few things to keep in mind: we will be writing in JavaScript so remember that newlines are not used to end lines of code as they are in Python, single line "//"comments do not work in bookmarklets so we must use multi-line "/* */" comments instead, and be sure to utilize your browser's inspector tool to learn how to identify the elements you want to target!

Example #1: Simple Text Box

Let's start with a relatively simple example where we want to add a static block of text to the text box below. If we right-click on the text box below and select "Inspect", we are able to view the Elements section within the inspector. By moving our cursor over each line of HTML markup in the Elements section, we will see each element highlighted on the actual webpage. Using this method, we can determine that our text box is actually an <input> element, with class of "bookmarklet-field" and id of "text-simple" -- this information is what we will use to target the element. Note: We must first target our intended element in our JavaScript code before we add instructions for what we want to do with the element.

Anytime we want to target an element on the rendered webpage -- aka the DOM, or Document Object Model -- we prepend the our targeting method with “document.”. After we have instructed the bookmarklet to focus on the Document Object Model (our rendered webpage), we can then add additional methods to drill down further. In this example, in order to target our <input class="bookmarklet-field" id="text-simple"> element, we could follow the "document." with either "getElementById('text-simple')" or "getElementsByClassName('bookmarklet-field')[0]". Often, as in this example, there are multiple ways to target the same element so use whatever method you’re more comfortable with! Note: when using the "getElementsByClassName('')" method, if you are trying to target a single element, you will have to specify the [nth] occurrence of that element as this method returns an array.

After that we've targeted our element, we need to include instructions for what we want to do with this element. As this is our first example, let’s keep it simple and try and change the value property of the textbox to "Congratulations!" by appending ".value=Congratulations!" to our line of code. If we combine everything discussed so far, we end up with the following bookmarklet:

javascript: ( function () { document.getElementsByClassName('bookmarklet-field')[0].value="Congratulations!"; }) ();

Now that we have finished creating our first bookmarklet, all that is left to do is save it as a bookmark and try it out! Open your browser's Bookmark Manager, assign the bookmarklet the name "Congrats", copy and paste the code in the above box and save. After saving, click the “Congrats” bookmark, check to see that the bookmarklet worked and the text box above now contains the "Congratulations!" text. If it is not working for you, enter the Inspector again and focus on the Console tab as errors will print here that can help you identify the issue. Tip: the (parentheses) and [square brackets] are very easy to confuse in this font so be sure to double check them.

Example #2: Dropdowns

In this next example, we are going to use a bookmarklet to select specific options for the four dropdowns below. Using the inspector again, we can see that each of the dropdowns below are <select> elements with their respective options listed within as <option> elements.

We are going to use the "getElementsByTagName()" method to select each of our respective dropdowns, and then set the value of each respective dropdown to the option value of our choice. Reminder, much like the previous example, there is more than one way to target each element. When using the "getElementsByTagName()" method, we can refer to each specific dropdown by its position in the array: the Favorite Color dropdown is [0], the Favorite Sport dropdown is [1], etc.

Now that we have figured out how to refer to each dropdown, we must decide what value we should give each one. Unlike the textbox above, there is a finite set of possible options for each respective dropdown, given by the <option> elements listed within each <select> element. Using the inspector, we can identify an arbitrary <option> value for each of the dropdowns and add them to our bookmarklet. Note: when inspecting, the value for each dropdown will be given explicitly within each <option> element as 'value=""'. In our case, the value for each option is the lowercase word associated with each displayed word. Example: the actual value for the Favorite Color option, Red, is "red". If we combine everything discussed so far, we end up with the following bookmarklet:

javascript: ( function () { document.getElementsByTagName('select')[0].value="purple"; document.getElementsByTagName('select')[1].value="hockey"; document.getElementsByTagName('select')[2].value="brownies"; document.getElementsByTagName('select')[3].value="winter"; }) ();

Now, open your browser's Bookmark Manager, assign the bookmarklet the name "Favorites", copy and paste the code in the above box and save. After saving, click the "Favorites" bookmark, check to see that the bookmarklet worked and the dropdown values above are changed to: Purple, Hockey, Brownies and Winter.

Example #3: Buttons

In this example, we will be creating a bookmarklet that will click the blue "Click Me" button below. Before we try to build the bookmarklet, let’s click each button and see what happens. After you click the blue button, an alert message should appear that says "Hey, you clicked the blue button!". After you click the red button, an alert message should appear that says 'Noooooo!!! You clicked the red button :(". If you aren’t seeing these messages, you may need to disable your pop-up blocker.

Using our inspector, we can see that the blue button is a <button> element, with a class of "bookmarklet-button" and an id of "blue-button". Although we could target this button using "document.getElementsByTagName('button')[0]" or "document.getElementsByClassName('bookmarklet-button')[0]", let's try "document.getElementById('blue-button')" instead. Now that we've figured out how to target the blue button, we need to add a "click()" method to our line of code to instruct the browser that we want to click that button.

javascript: ( function () { document.getElementById('blue-button').click(); }) ();

Now, open your browser's Bookmark Manager, assign the bookmarklet the name "Button", copy and paste the code in the above box and save. After saving, click the "Button" bookmark, check to see that the bookmarklet worked and the "Hey, you clicked the blue button!" alert message appears on your screen.

Example #4: Advanced Text Box

In this example, we will be creating a bookmarklet that will target a textbox, as we did in Example #1, however, we will be adding more JavaScript to better illustrate the capabilities of bookmarklets.

We will be targeting the textbox above in the same manner that we did in Example #1, this time using "document.getElementsByClassName('bookmarklet-field')[1]" as this is the second element of this class on the DOM. Remember, we are index 0 so the "[1]" represents the second element in the array. First, however, we will introduce an additional line of code to declare a variable x and give it an initial value of "It is ". To declare a variable in JavaScript you can use the "let" statement, as in 'let x = "It is ";'. After declaring our variable x, we will set the value of the textbox element we are targeting equal to x.

javascript: ( function () { let x = "It is "; document.getElementsByClassName('bookmarklet-field')[1].value=x; }) ();

Now, let's add in some more interesting functionality and enable our bookmarklet to tell us what month of the year we are in. First, let’s create a new date object for today’s date and assign it to the variable t using the line "let t = new Date();". Now that we have our new date object, t, we can apply the getMonth() method to determine the month that today’s date falls in and set that value equal to a new variable m. Next, let's set our "document...value =" line equal to m, before saving and running the bookmarklet.

javascript: ( function () { let x = "It is "; let t = new Date(); let m = t.getMonth(); document.getElementsByClassName('bookmarklet-field')[1].value=m; }) ();

After running the above bookmarklet, you will notice that a number is entered into our targeted text box. This number, given by m, is equal to the current month minus 1. This is because the month value given by m is index 0, so 0 represents January, 1 represents February, and so on. In order to get the name of the current month, we will define an array that contains the names of all 12 months, and then we set our "document...value =" line equal to the m-th value (remember, index 0) in that array.

javascript: ( function () { let x = "It is "; let t = new Date(); let m = t.getMonth(); let monthArray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; document.getElementsByClassName('bookmarklet-field')[1].value=monthArray[m]; }) ();

Lastly, let's concatenate our variable x and monthArray[m] and use that concatenation as our final value for "document.getElementsByClassName('bookmarklet-field')[1]". We will set up an intermediate variable c to store the concatenation value but this isn’t strictly necessary as you could also concentrate directly in the value line of the anonymous function.

javascript: ( function () { let x = "It is "; let t = new Date(); let m = t.getMonth(); let monthArray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; let c = x + monthArray[m]; document.getElementsByClassName('bookmarklet-field')[1].value=c; }) ();

After saving and running the above bookmarklet, we can see that it does input our desired result into the targeted textbox! The way we have written the JavaScript, it should be able to determine the correct month for any day in the future that we run this bookmarklet. Although this is a contrived example, it is cool to see that we can do things like define and work with variables in the URL portion of a browser bookmark.

Combining the Previous Examples

So far, we have written bookmarklets that change the value of textboxes, selected desired options from dropdowns, and clicked buttons. Now, let's combine all the previous examples into one bookmarklet and see what happens.

javascript: ( function () { document.getElementsByClassName('bookmarklet-field')[0].value="Congratulations!"; document.getElementsByTagName('select')[0].value="purple"; document.getElementsByTagName('select')[1].value="hockey"; document.getElementsByTagName('select')[2].value="brownies"; document.getElementsByTagName('select')[3].value="winter"; document.getElementById('blue-button').click(); let x = "It is "; let t = new Date(); let m = t.getMonth(); let monthArray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; let c = x + monthArray[m]; document.getElementsByClassName('bookmarklet-field')[1].value=c; }) ();

After saving and running the above bookmarklet, you will see that it will accomplish each task from each of the previous examples. Note: you will have to click "Ok" in the blue-button alert message that shows up in order for the bookmarklet to work. Hopefully you found this tutorial useful and if you have any questions or suggestions about bookmarklets, please contact me on LinkedIn.