Search code examples
javascriptjqueryjquery-focusout

How to trigger focusout event


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/


Solution

  • 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>