Elaine’s jQuery Lessons: Part 1

Since I’m new to jQuery I thought this would be a good place to pop down my progress in learning jQuery.

So far I’ve spent a little time reading “jQuery: From Novice to Ninja” which is a fantastic book, its easy to read and simple to follow, highly recommend you guys to check this eBook.

I did a small amount of jQuery for ProCare, the search box had default text that needed styling (italic, light grey), but when a user clicks into the box and starts typing it would revert to normal body copy text.

Here’s a look at the original code piece by piece:

var searchBox = '#ctl00_plcUpperRightNav_CMSSearchDialog1_txtWord'

Simple enough, find this ID and we’ll reference this as searchBox later on.

$(searchBox).val('Enter Keyword');

Give this search box the value of Enter Keyword.

$(searchBox).blur(function() {
  if($(searchBox).val() === '') {
    $(searchBox).val('Enter Keyword');
  }
});

I thought blur had something to do with focus, turns out its when it loses focus, either by tabbing or clicking away. Basically this peice is saying when the search box loses focus do the following: if its empty then add Enter Keyword value.

$(searchBox).focus(function() {       
  if($(searchBox).val() === 'Enter Keyword') {
    $(searchBox).val('');
  }
});

This last piece is pretty much the opposite, when the search box gets focus and the value is Enter Keyword then make the value blank.

I already had my style set up for the Enter Keyword default text, I just needed to append it via jQuery, so here what I did:

$(searchBox).val('Enter Keyword').addClass("prompt");

Search box has the value Enter Keyword and the class ‘prompt’ which gives it the light grey and italic.

$(searchBox).blur(function() {<       
  if($(searchBox).val() === '') {
    $(searchBox).val('Enter Keyword').addClass("prompt");
  }
});

Again, when it loses focus and its still has the default text then append the 'prompt' class to it.

$(searchBox).focus(function() {
  if($(searchBox).val() === 'Enter Keyword') {
    $(searchBox).val('').removeClass("prompt");
  }
});

Remove the 'prompt' class from the search box so its ready for typing into.

Although this looks incredibly simple and doesn't look like much was done on my part, it still took me a while to get my head around the original code and where to add the class and remove it.

I think jQuery is awesome, powerful and quite easy to understand once you get the hang of it. It's just one of those things you need to do on a regular basis so you don't forget how to code.

I'll be adding more of these jQuery learning snippets to the blog, its mainly for my reference, so that I can come back here after a year and laugh see how far I've come.