0

I'm creating some form elements dynamically and I need to trigger an event for each element.

Say I have something like this:

$("#select_123").val("easy").change().trigger("createRow");


$("#container").bind("createRow",function() {
   //doStuff
}

How do I chain .trigger to run the "createRow" event?? Even better, how can I use .delegate instead of .bind?

3
  • I'm not following your question. If you hook the event before triggering it (the above hooks it after), you'll receive the event. Commented Jun 16, 2016 at 16:17
  • 3
    Side note: .bind and .delegate are thoroughly outdated. The modern method to use is on. Commented Jun 16, 2016 at 16:18
  • oh wow, re-ordered and it worked. ok cool. Commented Jun 16, 2016 at 16:19

1 Answer 1

1

Your code fires the event before you've hooked up a handler for it. If you reverse the order, it'll work.

It'll also work with event delegation, because jQuery's custom events bubble by default. So you just trigger the event on the child and watch for it on the parent.

Example:

$(".child").on("click", function() {
  // Fire the custom event on the child element
  $(this).trigger("custom-event");
});

// Watch for custom events using delegation
$("#parent").on("custom-event", ".child", function(e) {
  console.log("Got event: " + e.type);
});
<div id="parent">
  <div class="child">Click me</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.