Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery on focus event delegation

Tags:

jquery

For some strange reason this simple function doesn't seem to work:

$("body").on("focus", this, function(){
    alert('d');
})

this is input or textarea element.

If i were to do this:

$(this).on("focus", function(){
    alert('d');
})

It would work on those elements that exists at the moment, but i event would not fire up on newly created elements, what am i doing wrong?

like image 308
Linas Avatar asked Dec 28 '12 00:12

Linas


2 Answers

The second parameter is, as described by the API, "a selector string to filter the descendants of the selected elements that trigger the event."

I assume this, in your case, is a DOM element. Try changing that to a selector to match inputs or textareas. This will cause your function to be called whenever a focus event bubbles up to body from an element matching your selector. This should work for you:

$("body").on("focus", "input, textarea", function() {
    alert('d');
});

Further information on on() here: http://api.jquery.com/on/

like image 154
grant Avatar answered Sep 18 '22 13:09

grant


As @grantman16 has mentioned that the second parameter must be a selector,

But If it's a newly created element why don't you use focus().

​va​r input = $("<input>");
input.focus(function() {
  alert('d');
});
$("body").append(input);​
​

Example -1

You don't need to use .on, but if you are insistent to use it, you should set a selector as second parameter,

var input = $("<input>").addClass("lastInput");
$("body").on("focus", "input.lastInput", function() {
  alert('d');
});
$("body").append(input);
​

Example -2

like image 23
Okan Kocyigit Avatar answered Sep 19 '22 13:09

Okan Kocyigit