2009
Testing jQuery Commands With Firebug Or With a Bookmarklet
JavaScript , Web development , jQuery No Comments »Before I went on vacation last week, I read a blog post by Ben Nadel where he demonstrated code for stepping through the search path of a jQuery selector in order to debug the selector. As Ben pointed out, if you make a mistake in your selector, it will fail silently, making it hard to figure out exactly where you went wrong.
In the comments to the blog post, Shayne Sweeny pointed out that you can run jQuery commands directly from the blue command prompt in the Console view of the Firefox Firebug plugin, like so:

I like this technique because it lets me write any jQuery code I want (selectors don't usually give me problems, it's the DOM traversing that sometimes trips me up), and I can use it on any of my pages that use the jQuery library without adding extra code to the page.
But what if you're trying to troubleshoot a jQuery command in a browser other than Firefox (for some reason)? Well, I did a bit of tinkering and came up with a bookmarklet that does something similar. If you're not familiar with bookmarklets, they are bookmarks you can add to your browser's bookmark collection that run JavaScript code instead of opening up a different web page.
The bookmarklet I created adds a <div> at the top of the page with a text input and three buttons. Any jQuery command entered into the text box will be executed on the page and then recorded below the text box for reference. Here's a screenshot of it in action in Opera:

It works in Opera, Safari, and Chrome: I couldn't get it to work in IE 7 (surprise, surprise).
To use it, all you have to do is go into whatever browser you want to use it with and create a bookmark that has the following code in place of a normal bookmark URL:
javascript:var%20d=%20document.createElement("div");d.style.width="100%;";d.style.border="1px%20solid%20#ccc";d.style.margin="5px%200px;";d.style.padding="7px";d.id="jqtD";var%20t=%20document.createElement("input");t.type="text";t.id="jqtT";t.size="80";var%20b=%20document.createElement("input");b.type=%20"button";b.id="jqtB";b.value="Execute";var%20c=%20document.createElement("input");c.type="button";c.id="jqtC";c.value="Clear";var%20s=%20document.createElement("input");s.type="button";s.id="jqtS";s.value="Close";var%20bd=document.getElementsByTagName('body')[0];%20b.appendChild(d);var%20frst=%20bd.firstChild;bd.insertBefore(d,frst);d.appendChild(t);d.appendChild(b);d.appendChild(c);d.appendChild(s);jqtEvts();function%20jqtEvts()%20{$("#jqtB").click(function()%20{var%20tst=%20$(this).prev().val();eval(tst);$("#jqtD").append("<br%20/>"+tst);});$("#jqtC").click(function()%20{$(this).siblings("input[type='text']").val("");});
$("#jqtS").click(function()%20{$("#jqtD").remove();});}
...Just make sure to remove any spaces or line breaks that may have been introduced during the copy and paste process.
Recent Comments