How to Create a jQuery Bookmarklet

I suspect many of my readers have written at least one jQuery Plugin / Script. In this post, I’d like to show you how to get the most out of that script by also releasing it as a jQuery Bookmarklet. Below, you’ll find two examples of utilities that are ripe for bookmarkleting, as well as a prepared jQuery Bookmarklet file that you can easily modify for the purpose.

Note: Even if you haven’t written a jQuery plugin before, you’ll find bookmarkleting someone else’s plugin as easy as using it on a site.

Before I get to the code though – take a look at the payload. You can add the following links as bookmarklets by right-clicking and selecting “Add to bookmarks / favorites” (in Chrome, you press “ctrl+shift+b” to open the bookmark manager, and drag them over). You can try them before you bookmark them by simply clicking the links on this page too.

Example One:


Clicking the above link will add the table sorter jquery plugin to the page, including its stylesheet, and it will apply the script to all tables on the page. Once it’s loaded, you can click on any of the table column headers to sort the rows by column values.

Example Two:

The visualizer bookmarklet will add graphical representations of the data in the table. As with the table sorter, this bookmarklet was adapted from a pre-existing plugin, Filament’s jQuery Visualize.

2009 Employee Sales by Department
food auto household furniture kitchen bath
Mary 190 160 40 120 30 70
Tom 3 40 30 45 35 49
Brad 10 180 10 85 25 79
Kate 40 80 90 25 15 119

Cool stuff, right? Let’s get to how it works then – starting with the prepared jQuery Bookmarklet template. This is what I recommend you use when writing your own bookmarklets:

/*
 * jQuery Bookmarklet - version 1.0
 * Originally written by: Brett Barros
 * With modifications by: Paul Irish
 *
 * If you use this script, please link back to the source
 *
 * Copyright (c) 2010 Latent Motion (http://latentmotion.com/how-to-create-a-jquery-bookmarklet/)
 * Released under the Creative Commons Attribution 3.0 Unported License,
 * as defined here: http://creativecommons.org/licenses/by/3.0/
 *
 */
 
window.bookmarklet = function(opts){fullFunc(opts)};
 
// These are the styles, scripts and callbacks we include in our bookmarklet:
window.bookmarklet({
 
    css : ['http://www.site.com/your.css'],
    js  : ['http://www.site.com/your.js'],    
//	jqpath : 'myCustomjQueryPath.js', <-- option to include your own path to jquery
    ready : function(){
 
		// The meat of your jQuery code goes here
		$("body").html("Hello World");
 
   	    }
})
 
function fullFunc(a){function d(b){if(b.length===0){a.ready();return false}$.getScript(b[0],function(){d(b.slice(1))})}function e(b){$.each(b,function(c,f){$("<link>").attr({href:f,rel:"stylesheet"}).appendTo("head")})}a.jqpath=a.jqpath||"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js";(function(b){var c=document.createElement("script");c.type="text/javascript";c.src=b;c.onload=function(){e(a.css);d(a.js)};document.body.appendChild(c)})(a.jqpath)};

From top to bottom, what the jQuery Bookmarklet Template does is:

  1. Prepare the full bookmarklet function. This is the call to the minified code in the last line of the js file. It is in an uncompressed format at the bottom of this post for those interested, but most will never need to see it..
  2. Create the configurations, including arrays to your CSS and JS files. You can load as many as you see fit, and the JS files will load asynchronously, ensuring that each file can reliably depend on the file before it.
  3. Provides the callback function for your editing. Place whatever jQuery code you like here.

In order to use that script, though, you’ll need to create a link that calls it. Here’s the code for that link:

<a href="javascript:(function(){var head=document.getElementsByTagName('head')[0],script=document.createElement('script');script.type='text/javascript';script.src='http://www.site.com/your-javascript.js?' + Math.floor(Math.random()*99999);head.appendChild(script);})(); void 0">Your Bookmarklet Name</a>

To some that might look like a handful, but don’t worry, the hard work is already done. All you need to do is change the url in that link to point to your javascript file, and add a little regular-ol-jQuery to that javascript file.

Ok, still with me? Great! Now let’s look at one of the actual live examples we used earlier on the page. Here’s how I included table sorter, which requires both a JS and CSS file:

/*
 * jQuery Bookmarklet - version 1.0
 * Originally written by: Brett Barros
 * With modifications by: Paul Irish
 *
 * If you use this script, please link back to the source
 *
 * Copyright (c) 2010 Latent Motion (http://latentmotion.com/how-to-create-a-jquery-bookmarklet/)
 * Released under the Creative Commons Attribution 3.0 Unported License,
 * as defined here: http://creativecommons.org/licenses/by/3.0/
 *
 */
 
window.bookmarklet = function(opts){fullFunc(opts)};
 
// These are the styles, scripts and callbacks we include in our bookmarklet:
window.bookmarklet({
 
    css : ['http://tablesorter.com/themes/blue/style.css'],
    js  : ['http://tablesorter.com/jquery.tablesorter.js'],    
//	jqpath : 'myCustomjQueryPath.js', <-- option to include your own path to jquery
    ready : function(){
 
		// Initiate table sorter
		$("table").tablesorter().addClass("tablesorter"); 	
 
   	    }
 
})
 
function fullFunc(a){function d(b){if(b.length===0){a.ready();return false}$.getScript(b[0],function(){d(b.slice(1))})}function e(b){$.each(b,function(c,f){$("<link>").attr({href:f,rel:"stylesheet"}).appendTo("head")})}a.jqpath=a.jqpath||"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js";(function(b){var c=document.createElement("script");c.type="text/javascript";c.src=b;c.onload=function(){e(a.css);d(a.js)};document.body.appendChild(c)})(a.jqpath)};

For your convenience, you can also download the script as a JS file.

And that’s about it! Sorta, anyway. Here’re some bonus thoughts for the real enthusiasts:

  1. Bookmarklets leverage caching, big time. When developing, I found this to be a major frustration, so I added a large random number at the end of the js call, which effectively forces a reload each time the javascript is called. Upon deployment – you may choose to remove it, but keep it in mind next time you make a change and don’t see the effects.
  2. Another reason I force refreshing of my js file is because I want to be able to update my scripts without forcing my users to re-bookmark them.
  3. If you create your own bookmarklet and want to post about it in wordpress, you’ll quickly learn you need a workaround. The first one I used was hardcoding the links in an external page, and displaying them through an iframe. It worked, but was lame. Now I’m using javascript to store the desired a href as a variable, then I wrap that variable with the tags, and finally I document.write it. If you have a better idea, let me know.
  4. The table examples that I’ve provided on this page are based on pre-existing jQuery plugins. Those plugins assume that tables are correctly formatted, with table headers etc. If a website’s layout was built in the 90s and still uses tables for page structure, the results won’t be pretty.
  5. Sadly, Disqus (the host service for my comments below) uses tables. This of course conflicts with the specific table examples I used above, and can be resolved by refreshing. I’m sure it’s possible to set the bookmarklet to listen for a click of a table, but that’s beyond the scope of the current script/lesson.

And here’s some extra credit reading:

  • Learning jQuery made me realize that loading jQuery dynamically is possible. Almost ironically, Paul Irish helped with some modifications over there too.
  • After writing this article, I was informed Ben Alman had already written a similar script. His actually includes a “generator” that will use your jquery code and embed it for you, which is cool. It doesn’t include a loop to first include javascript / css files, but he probably figured it was easy enough to add yourself.
  • Tommy, at Smashing Magazine, wrote a much more in-depth article about the details and options when writing a jQuery bookmarklet. Although it was posted a few days after I posted mine, he had submitted it months in advance. Smart guy ;)
  • Marklets is a pretty nifty bookmark database that gives you searchable access to triggering any script in the arsenal. The creator and I are discussing a joint bookmarkleting project. Contact me if you’re interested in making bookmarklets kick ass again.

If you have any ideas, questions, or musings, I’d love to hear ‘em! Please add your comment below.

Update: Paul Irish was kind enough to help improve this script and teach me a couple things along the way. The following is the unminified version of what I’ve listed above, and includes his structural changes.

/*
 * jQuery Bookmarklet - version 1.0
 * Originally written by: Brett Barros
 * Heavily modified by: Paul Irish
 *
 * If you use this script, please link back to the source
 *
 * Copyright (c) 2010 Latent Motion (http://latentmotion.com/how-to-create-a-jquery-bookmarklet/)
 * Released under the Creative Commons Attribution 3.0 Unported License,
 * as defined here: http://creativecommons.org/licenses/by/3.0/
 *
 */
 
window.bookmarklet = function(opts){fullFunc(opts)};
 
// These are the styles, scripts and callbacks we include in our bookmarklet:
window.bookmarklet({
 
    css : ['http://tablesorter.com/themes/blue/style.css'],
    js  : ['http://tablesorter.com/jquery.tablesorter.js'],    
//	jqpath : 'myCustomjQueryPath.js', <-- option to include your own jquery
    ready : function(){
 
		// Initiate table sorter
		$("table").tablesorter().addClass("tablesorter"); 	
 
   	    }
 
})
 
function fullFunc(opts){
 
    // User doesn't have to set jquery, we have a default.
    opts.jqpath = opts.jqpath || "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js";
 
    function getJS(jsfiles){
 
	// Check if we've processed all of the JS files (or if there are none)
	if (jsfiles.length === 0) {
		opts.ready();
		return false;
	}
 
        // Load the first js file in the array
        $.getScript(jsfiles[0],  function(){ 
 
            // When it's done loading, remove it from the queue and call the function again    
            getJS(jsfiles.slice(1));
 
        })
 
    }
 
    // Synchronous loop for css files
    function getCSS(csfiles){
        $.each(csfiles, function(i, val){
            $('<link>').attr({
                    href: val,
                    rel: 'stylesheet'
                }).appendTo('head');
        });
    }
 
	function getjQuery(filename) {
 
		// Create jQuery script element
		var fileref = document.createElement('script')
		fileref.type = 'text/javascript';
		fileref.src =  filename;
 
		// Once loaded, trigger other scripts and styles
		fileref.onload = function(){
 
			getCSS(opts.css); // load CSS files
			getJS(opts.js); // load JS files
 
		};
 
		document.body.appendChild(fileref);
	}
 
	getjQuery(opts.jqpath); // kick it off
 
}; // end of bookmarklet();
  • Digg
  • Sphinn
  • del.icio.us
  • RSS

Popular Posts

Alternatively, you may want to return to the Home Page to view the most recent blog posts in order. If you have any questions, I make a point of reading and responding to all comments. Thanks for joining!

  • Test if jQuery already exists, attempts to load it, and then tests if it’s loaded 5 times every second, waiting to call the jqReady function. Use a similar process with the array JS, attempting to load jQuery dependent scripts (such as jQuery plugins). Once done, it will call jqCustom. In jqCustom, if uncommented, it will load myCSS, and then run any jQuery code you’ve added.

  • Dan The Man

    I think this is a good example how NOT to write a bookmarklet.

    Tablesorter is not working any more and I can not fix it as the Javascript code that fails is not contained in the bookmarklet.

    A bookmarklet is supposed to contain the complete code except for external includes like standard libraries like jQuery.

    This bookmarklet however does not contain the complete code but just  a loader to load the Javascript code from latentmotion.com. The code from latentmotion.com contains an outdated URL that I can not fix.

    Would the complete code for adding the Tablesorter be included in the Bookmarklet, I could have changed the URL most easily.

    Sad - but true.

  • To some that might look like a handful, but don’t worry, the hard work
    is already done. All you need to do is change the url in that link to
    point to your javascript file, and add a little regular-ol-jQuery to
    that javascript file.

  • Really nice and informative post.

  • Miguelgalang

    If I keep on clicking the bookmarklet I made. It keeps on adding jquery over and over again to my head. Is this okay? I end up having multiple include jquery files.

    Thanks for all the help.

blog comments powered by Disqus