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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With