user961627
user961627

Reputation: 12747

jQuery(document).on ('focus')?

Whenever the user focuses on clicks on an input, I want to trigger a method. I have the following code:

jQuery(document).on('focus click', function(e){
        console.log("focused on " + $(e.target).attr('id'));
});

But whenever I focus on an element it just gives focused on undefined. What's wrong with this code?

Upvotes: 6

Views: 44729

Answers (2)

Anujith
Anujith

Reputation: 9370

Try:

$(document).on('focus click', 'input',  function(e){
        console.log("focused on " + e.target.id);
});

Also just e.target.id is enough..

Upvotes: 7

Adil
Adil

Reputation: 148110

You missed the input selector in bind event using on().

jQuery(document).on('focus click', 'input',  function(e){
        console.log("focused on " + $(e.target).attr('id'));
});

syntax of on() .on( events [, selector ] [, data ], handler(eventObject) ), reference

Upvotes: 7

Related Questions