Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery blur() not working?

Tags:

jquery

blur

Totally stumped here. Trying something pretty easy, but it's not working:

$("input.input1, textarea.input1").focus(function(){
    $(this).addClass("input2").removeClass("input1");
});
$("input.input2, textarea.input2").blur(function(){
    $(this).addClass("input1").removeClass("input2");
});

Basically the blur isn't firing. I click on the input box and the box changes. I click away from the box and nothing happens. Any help with this would be awesome.

like image 305
3Dom Avatar asked Nov 28 '11 00:11

3Dom


2 Answers

You need to use a delegated handler as the input doesn't have class input2 at the time the handler is applied.

$(document).on('focus','input.input1, textarea.input1', function() {
    $(this).addClass('input2').removeClass('input1');
});
$(document).on('blur','input.input2, textarea.input2', function() {
    $(this).addClass('input1').removeClass('input2');
});

There are probably better ways to do this, however. I'd suggest using a third class to mark the inputs that need the class toggled, then just toggle the classes when the event occurs.

$('.needsToggle').on('focus blur', function() {
     $(this).toggleClass('input1 input2');
});

If they always have class input1 to start, you could use that instead of needsToggle.

like image 63
tvanfosson Avatar answered Nov 15 '22 10:11

tvanfosson


Because you're affecting the same elements, it's somewhat easier to chain:

$("input.input1, textarea.input1").focus(function(){
    $(this).addClass("input2").removeClass("input1");
}).blur(function(){
    $(this).addClass("input1").removeClass("input2");
});

JS Fiddle demo.

As to why your jQuery isn't working as-is, I'm unsure, I'm afraid; though I suspect it's to do with the selectors.

like image 40
David Thomas Avatar answered Nov 15 '22 10:11

David Thomas