jQuery Quick Tip #1 – Adding a class on focus
Posted on by MattI’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
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’); });
}):
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.
Cheers sean for the heads up about the alternative method! I’ll give it a try.
Leave a Reply