Cosmin Cosmin - 3 months ago 10
jQuery Question

Use jQuery .trigger() to fire two .bind() events

If I have a single event used like:

$("#total").keyup(function(){
// Code here
});


I can trigger it like:

$("#total").trigger('keyup');


But if I have something like:

$("#total").bind("keyup change", function(e) {
// Some logic here
});


is it possible to use
.trigger()
to fire the binded events?

Answer

According to the documentation:

.trigger( eventType [, extraParameters ] ): eventType is a string containing a JavaScript event type.

If you are using modern versions of jQuery, it's better to use on instead of bind:

As of jQuery 3.0, .bind() has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.

So, you need:

$(function () {
  $("#total").bind("keyup change", function(e) {
    console.log('event: ' + e.type);
  });
  $("#total").trigger('keyup').trigger('change');
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<button id="total">Click Me</button>

Comments