0

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?

Community
  • 1
  • 1
Paul van den Dool
  • 3,020
  • 3
  • 20
  • 44

4 Answers4

2

Use as below :

$('#field').focus(function(){
    //do your stuff here
});
Butani Vijay
  • 4,181
  • 2
  • 29
  • 61
1

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.

DEMO

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1

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.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • @PaulvdDool and why not at least upvote all other correct answers?! – A. Wolff Jul 25 '13 at 08:50
  • @Kevin Bowersox Almost all other answers state a solution I already tried (like I said in the post). It's the extra commentary on your answer that brought the solution. – Paul van den Dool Jul 25 '13 at 09:10
0

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.

Maxim Zhukov
  • 10,060
  • 5
  • 44
  • 88