jQuery Quick Tip #1 – Adding a class on focus

Posted on by Matt

I’ve been learning and messing around more with jQuery recently, so i thought it would be a good chance to share some of the stuff i’m learning.

The Problem

I needed to add a focus class to my form input when i clicked the mouse in the input box.  I then needed to remove that class and add it to the next input in the form.  Well here’s how i did it!

The Solution

$(function() {
$(“input[type=text]”).focus(function() {
$(this).addClass(‘focus_class’);
return false;
});
});

$(function() {
$(“input[type=text]”).blur(function() {
$(this).removeClass(‘focus_class’);
return false;
});
});

3 Responses to jQuery Quick Tip #1 – Adding a class on focus

Sean Curtis says: June 2, 2009 at 1:29 am

You can soon do this even simpler with toggleClass(). From version 1.3.3 (out soon) you can just do:

$(function(){
$(‘input[type=text]’).trigger(‘focus blur’, function(){ $(this).toggleClass(‘focus_class’); });
}):

Reply

Leave a Reply