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?
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/
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().
var 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With