Entries Tagged as 'JavaScript'

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.

The Risk of Performing JavaScript Operations Around User-Generated HTML

JavaScript , Web development , jQuery No Comments »

Last year I wrote a ColdFusion application that included a page where an editor could take a list of short news abstracts and manipulate them (reorder them, place them in categories, add divider lines, create anchor links to highlighted stories, etc.) using a number of jQuery-powered JavaScript functions. It gives them a lot of control over the final layout, and they're pretty happy about it.

However, there have been occasions when this layout tool doesn't work at all. Why? Unclosed HTML tags in the abstract data.

The page they use to enter the news abstracts is comprised of several plain HTML text fields, a set of category checkboxes and two WYSIWYG textarea boxes (powered by JavaScript) for the abstract itself. I gave them the WYSIWYG boxes because I knew they would want to be able to do some basic HTML formatting on the abstract text (boldface, italics, etc.), and the WYSIWYG editors do produce solid, clean HTML.

What they do that gets them in trouble is they enter HTML tags (usually for italics) into the title form field, which is a normal HTML text field. Every once in awhile, they forget the closing tag or maybe just an angle bracket...the abstract itself saves correctly but when they get to the layout tool, that unclosed HTML tag messes up the entire DOM structure the layout tool is programmed to manipulate, rendering it non-functional.

They've now learned that when the header text of the various layout tools appears in italics, that usually means they've got an unclosed italics tag that needs fixing. It's easy enough to fix once they figure out which news item is responsible.

So a word of warning: if your JavaScript functions are designed to act upon HTML code that you yourself don't have complete control over (or the ability to make sure the HTML is clean and proper), consider the possibility that your JavaScript may end up breaking due to the content.

My First Mozilla Jetpack Add-On For Firefox: browseTimer

JavaScript , Miscellaneous , jQuery No Comments »

As I previously mentioned on my blog last week, Mozilla has launched a new means of creating add-ons for Firefox called Jetpack, which allows would-be plugin developers to build add-ons with HTML, CSS, and Javascript functions that include all of the jQuery functions.

As it happens, the first two functions listed in the Jetpack API were the clearInterval() and clearTimeout() functions, and that gave me a idea. My most recent AIR application, focusTimer, is a desktop widget inspired by time management techniques like Pomodoro, where you basically shut out/off all distractions and work on a task for a set amount of time. Once that time is up, the idea is to take a short break before starting another distraction-free period.

So my Jetpack add-on, browseTimer, is a timer built into the status bar of Firefox that lets you set how much time you want to spend browsing the web before getting back to work. Once the timer expires, the add-on uses the Jetpack API functions for the Firefox tabs to blank out the content of all of your open Firefox tabs and turn the body of the now-blank pages red (in other words, you KNOW when the timer has run out!).

It's certainly not the most useful add-on in the world, but it didn't take long and it helped me learn the basics of Jetpack.

If you're interested in checking it out, visit the following page...

http://www.swartzfager.org/blog/mozillaJetpack/browseTimer/installBrowseTimer.html

...for the link to the Jetpack add-on need to run all Jetpack-based add-ons, links to the Macintosh and Windows versions (there were slight differences in how the input elements were displayed in the status bar that warranted two separate versions), and instructions on how to uninstall it if you don't like it/need it.

Mozilla Announces Jetpack, an API For Writing FireFox Adds-On with jQuery, HTML, and CSS

JavaScript , CSS , Miscellaneous , jQuery , RIAs 3 Comments »

I found out about this last night from a tweet sent out by the jQuery Twitter account (which is probably a good indication that they like the idea).

The subject line pretty much says it all: Jetpack is designed to let current web developers use their existing skills with HTML, CSS, JavaScript, and jQuery to build Firefox add-ons/plugins without the need to mess with Firefox's XUL mark-up language. While JavaScript has always been part of the add-on development process, the inclusion of jQuery should make performing certain actions a whole lot easier.

You can learn more about Jetpack via the following URLs:

...the tutorials in the final link give you a good idea of the kinds of things Jetpack will allow you to do: the last example is a Jetpack add-on that will count and display the number of unread e-mails in your Gmail Inbox.

I want to give Jetpack a whirl, but I honestly can't think of any functionality I want to add to Firefox that I can't get from an existing plugin. Anyone have any suggestions for something to try with Jetpack?

It's interesting how web technologies keep being repurposed as a development option in other technologies (Adobe AIR, the upcoming Palm Pre's WebOS, and now Jetpack). Even though I'm not particularly interested in delving into all these different areas, I must say that I like the trend. :)

Preventing Non-Existent Dates with JavaScript

JavaScript No Comments »

When I say "non-existent dates", I mean dates like "April 31" or "June 31," an end-of-the-month date a user might enter if they don't take a moment to review the old "Thirty days hath September" mnemonic rhyme. All decent date pickers/selectors prevents users from entering letters or other inappropriate characters, but few of them bother to check if the date value itself is valid.

You could write a date validation script that took the month and day value submitted by the user and checked it against a list of the maximum number of days for each month, but then your code would also have to determine if the year selected by the user was a leap year in case the user entered "February 29" as their date of choice.

There's a more straightforward way to check the validity of the submitted date: create a JavaScript Date object using the year, month, and day submitted by the user, then extract the year, month, and day values from the newly created Date object and compare those integer values against the ones submitted by the user:

//Since JavaScripts counts months starting from 0 (January is 0), 
//subtract 1 from the month integer submitted by the user

var formattedMonth= userSubmittedMonth-1;
var testDate= new Date(userSubmittedYear,formattedMonth,userSubmittedDay,0,0,0,0);

if (testDate.getFullYear() != userSubmittedYear || testDate.getMonth()
!= formattedMonth || testDate.getDate() != userSubmittedDay)
{
alert("The date that you entered doesn't exist (like Feb. 31)");
}

This works because JavaScript's date creation function will accept the integer values for a non-existent date like April 31, 2009 (4, 31, and 2009), but it will quietly translate it into it's real-life equivalent, in this case May 1, 2009. So the integer values pulled from the date object via the getFullYear(), getMonth(), and getDate() functions will not match the integers originally passed into the date creation function, and you know there's a problem.