Updated jQuery Bookmarklet

read 39 comments

For the most recent version of the bookmarklet, see the Better, Stronger, Safer jQuerify Bookmarklet entry.

About 1 1/2 years ago I put together a little "jQuerify" Bookmarklet (and blogged about it here). It's a nice little tool that allows you to play around with jQuery on a page that doesn't already have jQuery loaded and see the results immediately. Based on feedback from others, I've updated the bookmarklet a bit. Now, it first checks to see if jQuery is already loaded on the page and doesn't bother loading it if it's there. Also, instead of showing an alert message, it temporarily places an absolutely positioned div at the top of the page with a message saying either "This page is now jQuerified" or "This page was already jQuerified." After 2 1/2 seconds, the message fades out and is removed from the DOM. Here is what the script looks like before it is converted to bookmarklet format (replacing spaces with %20, etc.):

JavaScript:
  1. (function() {
  2. var s=document.createElement('script');
  3. s.setAttribute('src','http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js');
  4. if(typeof jQuery!='undefined') {
  5.   var msg='This page already using jQuery v' + jQuery.fn.jquery;
  6. } else {
  7.   document.getElementsByTagName('head')[0].appendChild(s);
  8.   var msg='This page is now jQuerified'
  9. }
  10. var el=document.createElement('div');
  11.   el.style.position='fixed';
  12.   el.style.height='30';
  13.   el.style.width='200';
  14.   el.style.margin='0 auto 0 auto';
  15.   el.id='jq-kswedberg';
  16.   el.style.top='0';
  17.   el.style.left='40%';
  18.   el.style.padding='5px 10px 5px 10px';
  19.   el.style.backgroundColor='#f99';
  20.   el.innerHTML=msg;
  21. var b=document.getElementsByTagName('body')[0];
  22. b.appendChild(el);
  23. window.setTimeout(function() {
  24.   jQuery('#jq-kswedberg').fadeOut('slow',function() {
  25.     jQuery(this).remove()
  26.   });
  27. }, 2500);
  28. })();

It might look like a lot of code for something so simple, but most of it is just setting the styles for the inserted div element. Speaking of which, if you're using this in Internet Explorer 6, you might want to change el.style.position='fixed' to el.style.position='absolute'. Also, notice that the script's src is now pointing to the new Google CDN. Nice!

Here is the bookmarklet, ready to go:

» jQuerify «

Just drag it up to your bookmarks (or favorites) toolbar. Then, when you're on a page that doesn't have jQuery, all you have to do is click on the bookmarklet and you'll be ready to play around with jQuery on that page through the browser's console.

What? Your browser doesn't have a console? If you're using Firefox, you can download the Firebug add-on and use its console (you should really have this add-on anyway; it's amazingly helpful for html/css/js development). For Safari, open the Advanced tab in the Preferences and check the checkbox for "Show Develop menu in menu bar." Then you can open the console by selecting Develop > Show Error Console. Finally, the DebugBar plugin has a console that can be used in Internet Explorer.

Update

Thanks to Jonno's suggestion in comment #4 below, I've slightly modified the bookmarklet again to show which version of jQuery has been included on the page. If you ever want to know the jQuery version without using the bookmarklet, just type this in the console: jQuery.fn.jquery.

Update 2

Mark Fowler suggested that I "properly scope" the bookmarklet so variables wouldn't pollute the global namespace. Makes sense to me, so now the bookmarklet is updated with a self-executing function wrapping it. No need anymore for the void(s) at the end, since the variable is only defined within th

comment feed

39 comments

  1. Mind the trap: Dragging the bookmarklet from this post's feed read in (e.g.) Google Reader won't work as all JS is stripped out there.

  2. Very nice job, Karl! I'm brand new to your blog and book. I've had your book for a couple of weeks now and I'm loving it. I'm a noob when it comes to javascript so I'm feeling very smart upon reading the first three chapters of your book. Your book is very well laid out! I've got a question for you. I tried using the jquery bookmarks on firefox although I found something very annoying(I'm sure I'm not doing it right). Once I click on jquery on my bookmark, I get a message saying "This page is jquerified!". I try running some code onto the console, click on run and it runs perfect. However, if I want the page to refresh so I can run the code again, I have to reload the page(F5) so I can reuse it again. Is there anyway to refresh the page without having to reload the site? Also, Do you have instructions on how to use google cdn? Thanks alot!

  3. Thanks — this is very handy. Just one (minor) stylistic comment. This code:

    
      if(typeof jQuery!='undefined') {
        var msg='This page was already jQuerified'
      } else {
        document.getElementsByTagName('head')[0].appendChild(s);
        var msg='This page is now jQuerified'
      }
    

    Should probably declare msg outside of the if statement. I hate the scoping of variables in JavaScript, it's really confusing. It looks like block scope, but it isn't, you get function scope instead.

    
      var msg;
      if(typeof jQuery!='undefined') {
        msg='This page was already jQuerified'
      } else {
        document.getElementsByTagName('head')[0].appendChild(s);
        msg='This page is now jQuerified'
      }
    
  4. It looks like block scope, but it isn't, you get function scope instead.

    Doing what you suggest does not alter the variable's scope, either. Arguably, it makes the code less readable, not more.

    When two ways of doing something have the same results, my money's on the more readable (for various values of "readable", YMMV, etc, etc).

    Is there anyway to refresh the page without having to reload the site?

    As you are fundamentally altering the script environment of the page, no, there isn't.
    (You could assign window.location = window.location in the console, I suppose, but that would be reloading/refreshing {very confusing terminology, colloquially indistinguishable} the page just like Control/Command + R)

  5. Jonno

    A nice addition would be to put the jquery version number in 'This page is now jQuerified' message. I assume google will update the jquery version.

  6. Marius-Remus Mate

    Here's a nice cross-browser console >> http://www.billyreisinger.com/jash/

  7. Jonno, including the version number is a great idea. Thanks for the suggestion. I am updating the bookmarklet now.

    Marius-Remus, I like jash quite a bit, too. Thanks for mentioning!

  8. Juliano, it looks like Daniel Stockman answered one of your questions, but as for the Google CDN question, this article on Ajaxian.com announces the CDN, describes basic usage, and provides a link to the project page. Hope that gets you started, at least.

  9. Mark Fowler

    Dom, Daniel...

    The scope of the variables is indeed messy. spitting el, s and all that all over your namespace. Any reason the bookmarklet couldn't be scoped properly and wrapped in a (function (){...existing code...})() to prevent it from potentially screwing up a whole range of pages?

  10. @ Daniel - You're right! Very indistinguishable! I knew I was getting a bit confused with the terminology.
    @Karl - Thanks for the link!

  11. @Mark Fowler, great point. No reason at all not to scope it properly. Will update the entry and the script in a bit. Thanks!

  12. @Karl:
    I think you are right, thank you too.

  13. Elijah Manor

    Good job!

  14. I have a question that may or may not be related. If someone posts a wordpress comment but denies posting it, beside the avatar, is there any code to show us that the person did indeed access his OWN wordpress blog to post on ours? Again, he keeps denying it, saying that someone hacked his email or hacked his wordpress. its important that we prove beyond a doubt that this person wrote these comments. Please email me your response if possible.

  15. Nice update to the bookmarklet, Karl. I am actually going to incorporate some of this functionality in my jQuery Detector userscript (when clicking the icon). (Hmm...I need to blog about my improvements to that...)

    On the subject of consoles, Opera introduced its own built-in Firebug-type web development tool called Dragonfly with version 9.5. (Current version of Opera is 9.51, as of this writing). It's accessed via Tools => Advanced => Developer Tools. The console is called "Command Line."

    The product page still classifies Dragonfly as "Alpha," but it is functional and feature-rich. There are some warts--such as the page reloading when you open up Dragonfly, losing the original text of this comment in the process--but it is an excellent precursor to the product--and the command line totally works. ;)

  16. Thanks a lot, Pyrolupus! That Opera console sounds promising.

    Let us know when you have the updated jQuery Detector userscript ready. I'd love to see it!

  17. mckincy

    Great job!Thanks.

  18. Marjorie

    Let's say jquery is already loaded. (as in a drupal site.) How do I create a bookmarklet using jquery code? For instance, I'd love to create a little bookmarklet that does this:
    $('fieldset').removeClass('collapsed')

  19. Marjorie,

    Please see my answer where you cross-posted the question. And please try to avoid cross-posting. It just wastes your time and mine.

  20. Your blog is interesting!

    Keep up the good work!

  21. wsmith

    Is there any way to use the google api (as i understand it it is already configured for caching and checking to see if it is already loaded). I tried to do this, setting the src of the new script element to "http://www.google.com," then loading jquery with "google.load('jquery','1.2');" it seemed to work, but it blanked out the page display and not being a real javascripter, i don't know what went wrong. I tried to load jqueryUI the same way with the same results. Just wondering if you had any ideas or experience with this.

    meanwhile, thanks! this is very useful.

  22. wsmith

    The second sentence should read "setting the src of the new script element to "http://www.google.com/jsapi" "

    sorry.

  23. If you use this bookmarklet on a page that uses the prototype.js framework (or any other framework that uses the dollar sign, "$", as a function), it might destroy the functionality on the page.
    To prevent this, add the following code after line 26 of the bookmarklet.

    jQuery.noConflict();

    This way the functionality on the page is preserved and you can use jQuery through the jQuery() function or continue using the dollar sign inside a wrapper function:

    
    (function($) {
      $(function() {
        // more code using $ as alias to jQuery
      });
    })(jQuery);
    
  24. How can i load an iframe inside the div generated by the bookmarklet? thx

  25. just reposting this comment and maybe somebody will see this from here.
    ---

    Hi everyone,
    I've been using same technique too and I renamed it to "JQ", It's shorter so it takes less space on the bookmarks tabs and its self-hosted on my own localhost so its faster to load, but when Im outside I use "Google hosted jQuery".

    Question:
    Does anybody know how to automatically open Firebug using js bookmarklets?
    I mean similar to pressing F12 to show Firebug console window.
    I want the bookmarklet to attach jquery js to the current page and then open firebug already for me. could save me on typing one additional keystroke (F12).
    ...I know its lazyness but it could save a keystroke so I was just wondering if its possible.

    Anyway, learningjquery.com and jQuery rocks. thanks for this post :)
    Happy coding to all

  26. Paul V.

    (I know this post is a year old ...) In the spirit of coding jQuery I have modified your code slightly with true jQuery sytax... why not righ!

    
    (function() {
    var s=document.createElement('script');
    s.setAttribute('src','http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js');
    if(typeof jQuery!='undefined') {
      var msg='This page already using jQuery v' + jQuery.fn.jquery;
    } else {
      document.getElementsByTagName('head')[0].appendChild(s);
      var msg='This page is now jQuerified'
    }
    window.setTimeout(function(){
    // give
    var el=jQuery('');
    var elCss = {
    	'position' : 'fixed',
    	'height' : '30px',
    	'width' : '200px',
    	'margin' : '0 auto 0 auto',
    	'top' : '0',
    	'left' : '40%',
    	'padding' : '5px 10px 5px 10px',
    	'background-color' : '#f99'
    };
    el.css(elCss);
    el.html(msg);
    el.attr('id','jq-kswedberg');
    var b=jQuery('body');
    b.prepend(el);
    }, 0);
    window.setTimeout(function() {
      jQuery('#jq-kswedberg').fadeOut('slow',function() {
    		jQuery(this).remove();
      });
    }, 2500);
    })();
    
  27. Nelson

    Great post and a very useful utility. Thanks. I'm looking to get up to speed on jQuery and use it in my current project. I checked out J. Resig's screencast about hacking Digg with Firebug and jQuery. I used your bookmarklet instead of his code as it seems to be a better fit. However, I'm encountering two issues that are impeding my progress.

    1) I'm not able to invoke jQuery on the Firebug command line with only one $. It requires two ($$) for some reason. Here is an example from the Digg site:
    >>> $("div.sidebar")
    null
    >>> $$("div.sidebar")
    [div.sidebar]

    2) I get an error when attempting to chain a command to the jQuery selector.
    >>> $$("div.sidebar").remove();
    TypeError: $$("div.sidebar").remove is not a function

    Is anyone else seeing these issues? Any pointers?

    Cheers.

    • Clark Updike

      Just to confirm what Nelson sees, I see the same behavior in some cases where $$ is required for it to work--but in other cases only $ is needed. I also see the .remove() issue.

  28. Doug

    Q: What's with the

    window.setTimeout( ... jQuery ...)
    ?

    Why is this needed? Is this some sort of a replacement for $(document).ready()?

    • Hi Doug,
      No, it has nothing to do with document ready. It's just delaying the function from executing for 2 1/2 seconds. Before the script gets to the setTimeout, it displays a notice. If you look at what is occurring inside that setTimeout, you'll see that it is fading out that notice and then removing it from the DOM. It's nice to have a little delay there so that the notice can be read first before it disappears.

  29. JJ

    For my purposes, I have decided to build in the console to the bookmarklet. I added

    
         var w = prompt('statement');
         var start = new Date();
         eval(w);
         alert("it took "+(new Date() -start));
    
    

    which allows me to enter a statement and have it timed. I have been troubleshooting some javascript and trying to optimize the performance of the script. In order to do so it helps to know how long a particular statement takes to run. It could be a function call, a jquery statement or any other javascript. Thanks for the script.

  30. Piotr Findeisen

    Hey, firebug console works for IE too -- just try their bookmarklet http://getfirebug.com/lite.html .

  31. Well .. It doesn't show up the "Now jQuerified" box at all.
    But everything else is still doing fine...
    Nice, really nice work man. Thanks a lot!

    • If the "Now jQuerified" box doesn't show up, it's probably because of a z-index issue. If you really to see it, you can add something like el.style.zIndex='10000;' to it right after el.style.height='30';

  32. I encountered a error 'cannot modify properties of a wrappednative' on some websites using other libraries.

    You might want to add a jQuery.noConflict() call to the end of the bookmarklet to prevent conflicts. You can read more about my experience at the above link.

    • Hi Eric,
      Thanks for the comment. You're not the first to have run across this problem, but the bookmarklet hasn't really been on my radar for a while. Anyway, I updated the post with a "jQuerify noConflict" bookmarklet. The only drawback of it is that you can't use $() for jQuery functions in the console (unless you wrap it in a self-executing anonymous function the way plugins do). I also created a separate alias for jQuery, so you can at least do $jq().

  33. Hey Karl,
    Could you add an UPDATE link to the latest jquerify bookmarklet from here?
    Traversing to the right one from google is becoming more difficult. heh. :)

9 Pings

  1. Learning jQuery » Updated jQuery Bookmarklet...

    Learning jQuery » Updated jQuery Bookmarklet...

  2. jQuery Detector Overkill...

    With the ideas, help, and suggestions of some very smart folks, I’ve been able to put together a userscript that displays whether jQuery is used on the current page—along with version—and can also load jQuery into the current page by ...

  3. [...] Please see my entry about the updated and improved bookmarklet. [...]

  4. [...] recently wrote about an updated jQuery bookmarklet that has things like a spiffy div that pops up and tells you what it’s doing. When I saw that [...]

  5. [...] jQuery Fans: jQuerify (integriert schnell jQuery in die aktuelle Seite um schnell mal Zeug [...]

  6. [...] With Firefox, Firebug, and the jQuerify bookmartlet, I was able to test this for him and provide assurance it can [...]

  7. [...] Firebug (and now Safari or IE8) console. I blogged about it, got lots of great feedback, and then blogged about an improved version. Now that a lot more great feedback has come through the comments of the updated bookmarklet post, [...]

Sorry, but comments for this entry are now closed.