Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
88
rated 0 times [  95] [ 7]  / answers: 1 / hits: 28916  / 7 Years ago, mon, october 23, 2017, 12:00:00

I have a focusout event



$('.alpha').on(focusout, function () {...});


and I want want to trigger it from somewhere else in the code.



I tried $('#input12').focus().blur();
and also tried $('#input12').trigger(focusout)



edit: I am using a dynamically generated elements.



but no luck there...



the element #input12 has the class name alpha so I expect The focusout event to be triggered.



Is there any way of getting it done?



here is a jsfiddle example of when I am trying to do https://jsfiddle.net/jnmnk68d/


More From » jquery

 Answers
16

You need to delegate your events to a non-dynamic parent element.



In this example, we listen for focusout events on the form but only fire our function if the event's target matches the selector (in this case .alpha). This way the event can be fired on any elements that match now or in the future.



$(form).on(focusout, .alpha, function() {
console.log(focusout happened!);
});


Here's a full demo which allows you to see how using delegated events we are able to trigger the event on dynamically inserted content.





$(function() {
$(form).on(focusout, .alpha, function(e) {
console.warn(focusout triggered on + e.target.outerHTML);
});

//example trigger
//click the link to trigger the event
$(a).on(click, function(e) {
e.preventDefault();
$(#input12).trigger(focusout);
});

//demo injecting content
//click the create button then focus out on the new element to see the delegated event still being fired.
var i = 12;
$(form).on(submit, function(e) {
e.preventDefault();
var id = input + (++i);
$(this).find(fieldset).append(<input id=' + id + ' class='alpha' placeholder=' + id + ' />);
});

});

<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>
<form>
<fieldset>
<input id=input12 class=alpha placeholder=input12 />
<input type=submit value=create new />
</fieldset>
</form>
<a href=#>trigger on input12</a>




[#56147] Friday, October 20, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maleahp

Total Points: 223
Total Questions: 102
Total Answers: 116

Location: Sao Tome and Principe
Member since Wed, Dec 29, 2021
2 Years ago
;