Jquery: How to Get the Event Object in an Event Handler Function Without Passing It as an Argument

jQuery: How to get the event object in an event handler function without passing it as an argument?

Since the event object "evt" is not passed from the parameter, is it still possible to obtain this object?

No, not reliably. IE and some other browsers make it available as window.event (not $(window.event)), but that's non-standard and not supported by all browsers (famously, Firefox does not).

You're better off passing the event object into the function:

<a href="#" onclick="myFunc(event, 1,2,3)">click</a>

That works even on non-IE browsers because they execute the code in a context that has an event variable (and works on IE because event resolves to window.event). I've tried it in IE6+, Firefox, Chrome, Safari, and Opera. Example: http://jsbin.com/iwifu4

But your best bet is to use modern event handling:

HTML:

<a href="#">click</a>

JavaScript using jQuery (since you're using jQuery):

$("selector_for_the_anchor").click(function(event) {
// Call `myFunc`
myFunc(1, 2, 3);

// Use `event` here at the event handler level, for instance
event.stopPropagation();
});

...or if you really want to pass event into myFunc:

$("selector_for_the_anchor").click(function(event) {
myFunc(event, 1, 2, 3);
});

The selector can be anything that identifies the anchor. You have a very rich set to choose from (nearly all of CSS3, plus some). You could add an id or class to the anchor, but again, you have other choices. If you can use where it is in the document rather than adding something artificial, great.

event object is recognized without passing it, in javascript function?

You're accessing the global window.event. Support for this object varies from browser to browser.

See http://www.quirksmode.org/js/events_access.html

The parameter passed by jQuery is normalized to avoid these browser inconsistencies, but as you realized, you weren't accessing that parameter, so you were getting the raw global event object instead.

How to pass event as argument to an inline event handler in JavaScript?

to pass the event object:

<p id="p" onclick="doSomething(event)">

to get the clicked child element (should be used with event parameter:

function doSomething(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}

to pass the element itself (DOMElement):

<p id="p" onclick="doThing(this)">

see live example on jsFiddle.

You can specify the name of the event as above, but alternatively your handler can access the event parameter as described here: "When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters". There's much more additional documentation at the link.

Pass event object in a javascript function

setTimeout() does not pass an event object to its callback. And, even if you do find some way to get access to an event object in setTimeout(), it will be too late at that point to call e.preventDefault() because the default action will have already occurred.

So, your current approach to solving whatever problem you're trying to solve will not work. If you back up a few steps and explain the actual problem you're trying to solve, we could probably help you find a different way to solve it.

FYI, this type of question is known as the XY Problem where you describe a problem with your solution rather than the actual real problem you're trying to solve. An XY question vastly limits how we can help you.

JS: Why is the Event object accessible in event handlers without accepting it in a parameter?

Depending on the browser, there is a global event variable that refers to the currently fired event.

How can I pass arguments to event handlers in jQuery?

The simplest way is to do it like so (assuming you don't want any of the event information passed to the function)...

$("#myid").click(function() {
myfunction(arg1, arg2);
});

jsFiddle.

This create an anonymous function, which is called when the click event is triggered. This will in turn call myfunction() with the arguments you provide.

If you want to keep the ThisBinding (the value of this when the function is invoked, set to the element which triggered the event), then call the function with call().

$("#myid").click(function() {
myfunction.call(this, arg1, arg2);
});

jsFiddle.

You can't pass the reference directly in the way your example states, or its single argument will be the jQuery event object.

If you do want to pass the reference, you must leverage jQuery's proxy() function (which is a cross browser wrapper for Function.prototype.bind()). This lets you pass arguments, which are bound before the event argument.

$("#myid").click($.proxy(myfunction, null, arg1, arg2));   

jsFiddle.

In this example, myfunction() would be executed with its ThisBinding intact (null is not an object, so the normal this value of the element which triggered the event is used), along with the arguments (in order) arg1, arg2 and finally the jQuery event object, which you can ignore if it's not required (don't even name it in the function's arguments).

You could also use use the jQuery event object's data to pass data, but this would require modifying myfunction() to access it via event.data.arg1 (which aren't function arguments like your question mentions), or at least introducing a manual proxy function like the former example or a generated one using the latter example.

How to pass event and other arguments to click handler

Just to throw a more context-specific answer into the mix. I believe this question was asked in reference to this codepen: http://codepen.io/Barak/pen/AXZxKN

From an architecture standpoint, injecting parameters into handlers is a workaround you don't need. Instead, use the event target to access what was clicked/interacted with, and determine the values you need.

For your example, you are looking for the original data properties used to plot the points in your graph. You can either inject those properties onto the display object, inject a reference to the original data object, or create a look-up table to associate the display object with its related data point.

for (...) {
var point = data[i];
var dot = new createjs.Shape();
dot.x = point.x * GRAPH_WIDTH;

// Inject property or reference
dot.point = point;

// Create lookup
lookupTable[i] = dot;
}

Then when you click the object, look up the data.

dot.on("click", function(event) {
var dot = event.target;

// Use reference
var point = dot.point;

// Or use lookup
var index = lookup.indexOf(dot);

//...do stuff with it
}

There are lots of other ways to create this relationship, these are just some suggestions. Creating wrapper functions will work, but IMHO it is not a great approach for the long term or for a larger application. You can totally continue to use your approach, as it appears to be working for you -- but I wanted to offer some food for thought.

Cheers.

JQuery passing value to function accepting event object argument

You'd have to either pass the same object

var evt = {
data : {
opt : 3
}
}

function dev(){
revealOption(evt);
}

Or change the function to check for both an event object and an integer or string or something else etc.

function revealOption(event){
var n = typeof event === 'object' ? event.data.opt : event;

Then you could call it as

revealOption(3)

If you want to pass custom objects as well, you'd have to check for some property of the object that is unique to the event object etc.

jQuery .on() method - passing argument to event handler function

The .on() function expects a function reference to be passed; what you're doing is calling the function and passing its return value. If you need to pass a parameter you'll need to wrap the call in an anonymous function.

$(document).on('dblclick', '#an_tnam tr', function(event) {
ADS('hello');
});

jQuery always passes its normalized event object as the first argument to the function to be executed.



Related Topics



Leave a reply



Submit