JQuery blur () not working?

Totally tarnished here. Trying something is pretty simple, but it doesn't work:

$("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 does not work. I click on the input field and the field changes. I go out of the box and nothing happens. Any help with this would be awesome.

+4
source share
5 answers

You need to use a delegated handler, since the input does not have an input2 class when using the handler.

 $(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'); }); 

However, there are probably better ways to do this. I would suggest using a third class to indicate inputs that need a class that switches, and then just switch classes when an event occurs.

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

If they always have an input1 class to run, you can use it instead of needsToggle .

+11
source

Since you are working on the same elements, this is somewhat simpler:

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

JS Fiddle demo .

As for why your jQuery is not working as it is, I'm not sure, I'm afraid; although I suspect that this applies to selectors.

+3
source

Try this code:

 $("input.input1, textarea.input1").bind('focus blur', function(){ $(this).toggleClass("input2").toggleClass("input1"); }); 

If this does not work, you may need focusout instead of blur :

 $("input.input1, textarea.input1").bind('focus focusout', function(){ $(this).toggleClass("input2").toggleClass("input1"); }); 
+1
source

You need to use .delegate() if you are on jQuery <1.7.

And .on() if you are at 1.7 or higher.

Do not use .live() as it is waaaaay slower.

0
source

Also, if your elements loaded with ajax use $ (document) .on (event, selector, function), because it's standard, for example. $ (selector) .click (function () ... does not work

0
source

Source: https://habr.com/ru/post/953507/


All Articles