Beta Version Sticker

jQuery Quick Tip #1 – Adding a class on focus

June 1st, 2009

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;
});
});

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Reddit
  • Slashdot
  • MySpace
  • NewsVine
  • LinkedIn
  • Twitter
  • email
  • FriendFeed
  • Posterous

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

  1. Sean Curtis Says:

    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’); });
    }):

  2. Sean Curtis Says:

    Oops – should be:

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

    You can do it this way currently in 1.3.2 but if you have other classes they may be removed. See http://brandonaaron.net/blog/2009/05/6/jquery-edge-enhanced-toggleclass for more info.

  3. admin Says:

    Cheers sean for the heads up about the alternative method! I’ll give it a try.

Leave a Reply