Gaurav
Gaurav

Reputation: 8487

Passing eventobejct in jquery

I want to pass eventObject with trigger function, means when i manually trigger any event say:

 $(".test").bind({ click : Testing });

 $('.test').trigger("click");

 function Testing(e)
 {
 }

When the function testing is called by mouseclick , the parameter e contains the eventobject, so i want this same thing when we trigger it manually.Can we pass eventobject when we trigger any event manually, Is this possible?

Upvotes: 1

Views: 36

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074266

As gdoron points out (+1), jQuery will supply the event object for you. But you can create it explicitly if you like, to fill it in with information that jQuery can't fill in for you. You can create an Event object and pass it into trigger.

Here's an example of both using the default event object and creating your own: Live copy | source

jQuery(function($) {

  $(".test").click(function(e) {
    display("Received click on target");
    display("typeof e = " + typeof e);
    if (e) {
      display("e.type = " + e.type);
      if (e.type === "click") {
        display("Coords: (" + e.pageX + "," + e.pageY + ")");
      }
    }
  });

  //Create a new jQuery.Event object without the "new" operator.
  var e = $.Event("click");

  // Fill in more info
  e.pageX = 42;
  e.pageY = 27;

  // Trigger an artificial click event
  display("Issuing a click via <code>$('.test').trigger('click')</code>");
  $('.test').trigger("click");

  // Trigger an artificial click event
  display("Issuing a click creating our own event object with more info on it.");
  $('.test').trigger(e);

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }
});

Upvotes: 3

gdoron
gdoron

Reputation: 150253

You don't need to do anything, the Event object is there already when you trigger an event as well....

The event object is always passed as the first parameter to an event handler
...
...

trigger docs

Live DEMO

Upvotes: 3

Related Questions