Reputation: 3212
I want to trigger an event with jQuery when an input is focused. Should be simple enough.
According to this article a simple $('#id').is(':focus')
inside an if statement should work. But not for me: http://jsfiddle.net/PaulvdDool/BdG9N/
I've also tried to use .focus
here but that just triggers the event constantly. I could make it work, but I reckon it's not the best way of doing it.
Can somebody show me the light?
Upvotes: 1
Views: 206
Reputation: 74420
Use the onfocus handler: {you could use of course alias '.focus()' just be aware some customized jquery build remove alias events}
$('#field').on('focus',function(){
alert('Hello world!');
});
But don't use alert() inside focus handler, use console.log() instead. Alert() would create a loop on some browser.
Upvotes: 1
Reputation: 4239
Use as below :
$('#field').focus(function(){
//do your stuff here
});
Upvotes: 2
Reputation: 94429
The best solution is to bind an event handler using focus
such as:
$("#field").focus(function(){
//function body.
});
The main issue with this method is that the alert steals the focus from the input, which then receives focus once again when you click the input to type in the box. This cycle then repeats. I assume your code is going to do something other than throw an alert, so once the actual code is in place it will not repeatedly throw the alert.
Upvotes: 1
Reputation: 10140
Use focus
as a function:
$('#field').focus(function(){
alert('Hello world!');
});
Don't forget to add $(this).blur();
if you will work with alert
, because in this case, you have infinity alerts.
Upvotes: 0