Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery focus in / out

Tags:

jquery

I would like is to add class "active" to input on input focus, and when focus off, remove that class.

Thank's

like image 690
somewhereInPHP Avatar asked Jan 24 '11 21:01

somewhereInPHP


People also ask

What is the difference between jQuery Focusout () and Blur () events?

The focusout event fires when an element is about to lose focus. The main difference between this event and blur is that focusout bubbles while blur does not.

How can input focus in jQuery?

Using jQuery With jQuery, you can use the . focus() method to trigger the “focus” JavaScript event on an element. This method is a shortcut for . trigger("focus") method.

What is jQuery Focusin?

jQuery focusin() MethodThe focusin event occurs when an element (or any elements inside it) gets focus. The focusin() method attaches a function to run when a focus event occurs on the element, or any elements inside it. Unlike the focus() method, the focusin() method also triggers if any child elements get focus.

What is the difference between focus and Focusin?

The focusin event fires when an element is about to receive focus. The main difference between this event and focus is that focusin bubbles while focus does not. The opposite of focusin is focusout .


4 Answers

once you've included the jquery lib, it's pretty standard

$('input').focus( function() {
  $(this).addClass('active');
});

$('input').blur( function() {
  $(this).removeClass('active');
});

focus and blur are more appropriate than focusin and focusout for just input focusing. focusin and focusout bubble events to children objects and for the most part, that's (likely) unnecessary here.

pretty standard stuff. take a look at the jquery docs for more. also maybe modify the selector (the 'input' part) if you only want it for particular input fields.

selector examples:

$('input#my_id_is_bob') for $('input.my_class_is_activatable') for

like image 58
Michael Glass Avatar answered Sep 17 '22 22:09

Michael Glass


If target-id is the id of the input on which you want to swap the class in and out, you could use something like this:

$('#target-id').focusin(  
  function(){  
    $(this).addClass('active');  
  }).focusout(  
  function(){  
    $(this).removeClass('active');  
  });
like image 22
ozarius Avatar answered Sep 18 '22 22:09

ozarius


$("#id-of-your-field").focusin(function() {
    $('#id-of-your-field').addClass("active");
});
$("#id-of-your-field").focusout(function() {
    $('#id-of-your-field').removeClass("active");
});

This would solve your problem

like image 21
Frederik Kammer Avatar answered Sep 19 '22 22:09

Frederik Kammer


Try the following.

$("input[type=text]").focus(function(){
  $(this).addClass("active");
}).focusOut(function(){
  $(this).removeClass("active");
});
like image 32
Phil.Wheeler Avatar answered Sep 20 '22 22:09

Phil.Wheeler