Radza Milic
Radza Milic

Reputation: 63

Target input with :focus, even when changing

I have something like this in jQuery

if($("input").is(":focus")){
// do something
}

It has an effect on the focused input like it should. However, when I switch over to a new input that gets the focus instead, the first one is the still having that effect and not the new one. What would be a good way to make it auto update so that the one that is currently focused has the effect? Thanks!

Upvotes: 2

Views: 137

Answers (4)

gfullam
gfullam

Reputation: 12045

"Do something" on focus; "Undo that thing" on blur

Your example only runs one time and targets only one input: the one with focus. It doesn't respond to changes.

Use jQuery's .on() method to bind event listeners that can respond to changes.

A basic example:

$('input').on('focus', function () {
  // do something
  $(this).css('background-color','yellow');
});

$('input').on('blur', function () {
  // do something
  $(this).css('background-color','white');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" />
<input type="text" />

Another example using chaining:

$('input')
  .on('focus', function () {
    $(this).addClass('highlight');
  })
  .on('blur', function () {
    $(this).removeClass('highlight');
  });
input.highlight {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" />
<input type="text" />

Another example using space-separated list of events:

$('input')
  .on('focus blur', function () {
    $(this).toggleClass('highlight');
  });
input.highlight {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" />
<input type="text" />

Upvotes: 1

AlanShearer
AlanShearer

Reputation: 141

You might use a simple CSS3 rule:

input:focus {
  background-color: red;
}

Upvotes: 3

Michael Oakley
Michael Oakley

Reputation: 383

If you're using jQuery, you could attach event handlers to the focus and blur events.

http://api.jquery.com/category/events/form-events/

$(someSelector).on('focus', function(evt) { 
//do stuff
})

and

$(someSelector).on('blur', function(evt) { 
//do stuff
})

Note that you can use focusin and focusout if you need to listen for event bubbling.

Upvotes: 0

Mihai Farcas
Mihai Farcas

Reputation: 119

Does this help?

$('input').on('focusin' function(){
  $(this).toggleClass('someClass')
});
$('input').on('focusout' function(){
  $(this).toggleClass('someClass')
});

Upvotes: 0

Related Questions