Basic question. When I create an eventlistener as below and give the function the parameter e, what is e? If I understand it right its just the name of the event object?
document.getElementById('theId').addEventListener('submit', function(e) {
e.preventDefault();
})
Then what about this example? Does the event create an object in this case without a name?
document.getElementById("myBtn").addEventListener('submit', function(){
alert("Hello World!");
});
When the event 'submit' is fired, the given function gets called with an event object as the first argument.
You can name it as you like
document.getElementById("myBtn").addEventListener('submit', function(someEvent){
someEvent.preventDefault();
});
If you dont give the parameter a name, you still can access it over the arguments object.
document.getElementById("myBtn").addEventListener('submit', function(){
arguments[0].preventDefault();
});
It behaves like an array, but does not support functions like arguments.pop
More information on the arguments object here
Parameter e would be the event that happend, and yes e is just a name. You can give it any name you whant.
Events have their own properties, and one of them is "type" so you can know what event happened. In this example its type is "click" since that is what we are listening for.
Take look at this example
document.addEventListener("click", function(myEvent){
console.log(myEvent);
});
<p>Click anywhere.</p>
Related
I am new to JavaScript/jQuery and I've been learning how to make functions. A lot of functions have cropped up with (e) in brackets. Let me show you what I mean:
$(this).click(function(e) {
// does something
});
It always appears that the function doesn't even use the value of (e), so why is it there so often?
e is the short var reference for event object which will be passed to event handlers.
The event object essentially has lot of interesting methods and properties that can be used in the event handlers.
In the example you have posted is a click handler which is a MouseEvent
$(<element selector>).click(function(e) {
// does something
alert(e.type); //will return you click
}
DEMO - Mouse Events DEMO uses e.which and e.type
Some useful references:
http://api.jquery.com/category/events/
http://www.quirksmode.org/js/events_properties.html
http://www.javascriptkit.com/jsref/event.shtml
http://www.quirksmode.org/dom/events/index.html
http://www.w3.org/TR/DOM-Level-3-Events/#event-types-list
DISCLAIMER: This is a very late response to this particular post but as I've been reading through various responses to this question, it struck me that most of the answers use terminology that can only be understood by experienced coders. This answer is an attempt to address the original question with a novice audience in mind.
Intro
The little '(e)' thing is actually part of broader scope of something in Javascript called an event handling function. Every event handling function receives an event object. For the purpose of this discussion, think of an object as a "thing" that holds a bunch of properties (variables) and methods (functions), much like objects in other languages. The handle, the 'e' inside the little (e) thing, is like a variable that allows you to interact with the object (and I use the term variable VERY loosely).
Consider the following jQuery examples:
$("#someLink").on("click", function(e){ // My preferred method
e.preventDefault();
});
$("#someLink").click(function(e){ // Some use this method too
e.preventDefault();
});
Explanation
"#someLink" is your element selector (which HTML tag will trigger this).
"click" is an event (when the selected element is clicked).
"function(e)" is the event handling function (on event, object is created).
"e" is the object handler (object is made accessible).
"preventDefault()" is a method (function) provided by the object.
What's happening?
When a user clicks on the element with the id "#someLink" (probably an anchor tag), call an anonymous function, "function(e)", and assign the resulting object to a handler, "e". Now take that handler and call one of its methods, "e.preventDefault()", which should prevent the browser from performing the default action for that element.
Note: The handle can pretty much be named anything you want (i.e. 'function(billybob)'). The 'e' stands for 'event', which seems to be pretty standard for this type of function.
Although 'e.preventDefault()' is probably the most common use of the event handler, the object itself contains many properties and methods that can be accessed via the event handler.
Some really good information on this topic can be found at jQuery's learning site, http://learn.jquery.com. Pay special attention to the Using jQuery Core and Events sections.
e doesn't have any special meaning. It's just a convention to use e as function parameter name when the parameter is event.
It can be
$(this).click(function(loremipsumdolorsitamet) {
// does something
}
as well.
In that example, e is just a parameter for that function, but it's the event object that gets passed in through it.
The e argument is short for the event object. For example, you might want to create code for anchors that cancels the default action. To do this you would write something like:
$('a').click(function(e) {
e.preventDefault();
}
This means when an <a> tag is clicked, prevent the default action of the click event.
While you may see it often, it's not something you have to use within the function even though you have specified it as an argument.
In jQuery e short for event, the current event object. It's usually passed as a parameter for the event function to be fired.
Demo: jQuery Events
In the demo I used e
$("img").on("click dblclick mouseover mouseout",function(e){
$("h1").html("Event: " + e.type);
});
I may as well have used event
$("img").on("click dblclick mouseover mouseout",function(event){
$("h1").html("Event: " + event.type);
});
Same thing!
Programmers are lazy we use a lot of shorthand, partly it decreases our work, partly is helps with readability. Understanding that will help you understand the mentality of writing code.
Today I just wrote a post about "Why do we use the letters like “e” in e.preventDefault()?" and I think my answer will make some sense...
At first,let us see the syntax of addEventListener
Normally it will be:
target.addEventListener(type, listener[, useCapture]);
And the definition of the parameters of addEventlistener are:
type :A string representing the event type to listen out for.
listener :The object which receives a notification (an object that implements the Event interface) when an event of the specified type
occurs. This must be an object implementing the EventListener
interface, or a JavaScript function.
(From MDN)
But I think there is one thing should be remarked:
When you use Javascript function as the listener, the object that implements the Event interface(object event) will be automatically assigned to the "first parameter" of the function.So,if you use function(e) ,the object will be assigned to "e" because "e" is the only parameter of the function(definitly the first one !),then you can use e.preventDefault to prevent something....
let us try the example as below:
<p>Please click on the checkbox control.</p>
<form>
<label for="id-checkbox">Checkbox</label>
<input type="checkbox" id="id-checkbox"/>
</div>
</form>
<script>
document.querySelector("#id-checkbox").addEventListener("click", function(e,v){
//var e=3;
var v=5;
var t=e+v;
console.log(t);
e.preventDefault();
}, false);
</script>
the result will be : [object MouseEvent]5 and you will prevent the click event.
but if you remove the comment sign like :
<script>
document.querySelector("#id-checkbox").addEventListener("click", function(e,v){
var e=3;
var v=5;
var t=e+v;
console.log(t);
e.preventDefault();
}, false);
</script>
you will get : 8 and an error:"Uncaught TypeError: e.preventDefault is not a function
at HTMLInputElement. (VM409:69)".
Certainly,the click event will not be prevented this time.Because the "e" was defined again in the function.
However,if you change the code to:
<script>
document.querySelector("#id-checkbox").addEventListener("click", function(e,v){
var e=3;
var v=5;
var t=e+v;
console.log(t);
event.preventDefault();
}, false);
</script>
every thing will work propertly again...you will get 8 and the click event be prevented...
Therefore, "e" is just a parameter of your function and you need an "e" in you function() to receive the "event object" then perform e.preventDefault(). This is also the reason why you can change the "e" to any words that is not reserved by js.
It's a reference to the current event object
this will be my first stackoverflow help but I am confident that my answer will help anyone reading this.
Basically, e is just an object containing information about the EVENT which has just occured.
if it is 'click', then the object will contain about the click,
if it is 'submit', then the object will contain about the submit,
and they are typically found in addEventListener.
clickMe.addEventListener('click', e => {
console.log(e)
}
meaning, whenever I 'click' the button, it will console.log the INFOMRATION about the event that happened which is I did is to 'click' it, this will print information about the click event.
e is very useful because you can access and use the event to your very own project such as printing the location of x value... like
clickMe.addEventListener('click', e => {
console.log(e.clientX)
}
then it will print the location where you 'click' that event.. mine it returns 32
if you prefer video, please watch this
https://www.youtube.com/watch?v=_BVkOvpyRI0
video is not mine
upvoting me will truly help me since I am a student and looking for opportunity to help here. Love lots!
$(this).click(function(e) {
// does something
});
In reference to the above code
$(this) is the element which as some variable.
click is the event that needs to be performed.
the parameter e is automatically passed from js to your function which holds the value of $(this) value and can be used further in your code to do some operation.
Hey I have a build a canvas using easelJS.
In my canvas, I have points which a click handler is define for them using the following syntax:
p.on("click", handleMouseClickEvent);
Now I want to pass arguments to the handler handleMouseClickEvent , I know that I get the event object for free without passing it, but when I try to pass one argument, lets say I write:
p.on("click", handleMouseClickEvent(arg1));
Then the event object is undefined and not accessible at all.
How can I pass the event object and many more arguments using the above syntax.
p.on("click", handleMouseClickEvent(arg1,arg2,...,argN));
When using jQuery, Ravi's answer is perhaps the best way.
I'll try to provide another perspective to solve your question.
By using
p.on("click", handleMouseClickEvent(arg1));
you're not passing the function as event handler, you're executing it and passing its return value as event handler.
That perhaps already pointed you to the answer, right?
Try to define your event handler like this:
function handleMouseClickEvent(arg1)) {
return function reallyHandleMouseClickEvent(event) {
// all variables available here: arg1, event
}
}
Of course, you can add as many argN parameters as you want.
Since you're not calling the handler function yourself (the browser is doing it for you), you don't get to specify further arguments to the handler. All you'll get is the event object.
However, because of how JavaScript's variable scoping works, you don't have to. Functions have access to variables outside themselves, so you can simply access variables without passing them in explicitly:
var foo = "bar";
var handleMouseClickEvent = function(e) {
console.log(e.type); // 'click'
console.log(foo); // 'bar'
};
p.on("click", handleMouseClickEvent);
You need to define your event handler, try this:
function handleMouseClickEvent(arg1)) {
return function doSomething(event) {
//logic here
}
}
you can try this:
p.on("click", null, {arg1: "abc", arg2: "xyz"},handleMouseClickEvent);
//And in your function, you can get the event data like this
function handleMouseClickEvent()
{
alert(event.data.arg1);
alert(event.data.arg2);
}
According to official documenatation, on takes arguments like this:
.on( events [, selector ] [, data ], handler )
events Type: String
One or more space-separated event types and optional namespaces, such as
"click" or "keydown.myPlugin".
selector Type: String
A selector string to filter the descendants of the selected elements that > > > trigger the event. If the selector is null or omitted, the event is always
triggered when it reaches the selected element.
data Type: Anything
Data to be passed to the handler in event.data when an event is triggered.
handler Type: Function( Event eventObject [, Anything
extraParameter ] [, ... ] )
A function to execute when the event is
triggered. The value false is also allowed as a shorthand for a
function that simply does return false.
For more information, see JQuery Documentation of on() event 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.
This should handle it. You can add more arguments.
(function(arg1, arg2) {
p.on("click", function(event) { handleMouseClickEvent(event, arg1, arg2) })
})(arg1, arg2);
The arguments can be bound to a handler function with Function.prototype.bind
p.on("click", handleEventWithArg.bind(this,arg1));
function handleEventWithArg(arg1, event) {
console.log(arg1);
console.log(event);
});
The .bind method returns a new functon that the browser can invoke with the event object.
I bulid a function to event and I want to know how can I pass parameters to that function?
I use addEventListener method to add events
What I need is to pass the element variable to the function mean this object
For example if I use attribute method to add event I do like this:
<div onclick="function(this)">
And then the function will get the div element
Now my question is how can I pass the this object to the function when I use addEventListener
Is there anyway to get this thing?
Blah.addEventListener(function(event){
var element = event.target;
});
Posted from phone. Please forgive
http://www.w3schools.com/jsref/met_document_addeventlistener.asp
Define your listener with a parameter, this will be an event object.
In this object you will find the triggered element.
In an event handler, such as onclick, 'this' will automatically point to the element, where the event is triggered. You can use it inside your anonymous function.
Note: It's not a string but a HtmlElement.
Hope I have understood your question correctly.
I have event and function pairs like this ..
events : {
'click #category' : 'categoryList',
}
My function needs argument result set to be passed in .
categoryList: function(rs){
this.modelmaker(rs);
var array = JSON.parse('['+ arraymodels +']');
makeList(array,'ProdCat',function(html){$("#listofstuffs").append(html);});
alert(collection.length);
},
if i try to give categorylist(rs) as function value in event function pair it says function is not defined .!
there should be some questions already explaining about this kind of trivial doubts but i don't even know the apt keywords to search for. every example i see in event binding ; i find no argument passed. some one Please help me out.
The value in your events hash can be a function definition. Thus you could do:
events: {
'click #category': function() { this.categorylist('somearg'); }
}
This will work if you want the same argument passed in every time. If you need arguments related to the element clicked, I can suggest adding a data attribute in the html, and retrieving it from event.target in the function.
I have something like the following..
$(document).ready(function() {
$('#doReport').click(doReport);
});
function doReport(type) {
if (type === undefined) {
type = 'blah';
}
alert (type);
}
If I run doReport() from the console or standalone in the javascript with nothing in it, it will return 'blah' (as expected), and obviously if I call doReport('wibble'); it returns 'wibble' as you would expect.
But if I run it by clicking the element with ID doReport (utilising the bind I set up in .ready) it returns [object Object]
I don't understand why that would be the case.
The jQuery library passes your event handlers an "event" object. It will always be there. It's a "wrapped" or "fixed" version of the native browser object, making it somewhat easier to deal with.
Here is the documentation for such objects.
Also of note is the fact that jQuery will invoke your handler functions such that this refers to the DOM element for which the handler is being invoked.
Also also, as #Ericson578 points out in a good comment, jQuery allows additional parameters to be set up, which means that your handler may be passed additional parameters. That might be useful if you've got a single event handler function to be bound to different elements, but you'd like to qualify its behavior with some different flags or whatever based on the particulars of an element.
Event handlers receive an event object as a parameter.
This is because event handlers are triggered with an object (specifically, the event object) passed as the first argument.
This is the reason you see such syntax as
$('#doReport').click(function(e) {
If you want to call your function without any parameters, you'll need to create a wrapping function to do so:
$(document).ready(function() {
$('#doReport').click(function() {
doReport();
});
});
When jQuery calls the function passed as parameter to click, it passed event object as the argument hence you are getting the alert as [object Object].
Check this:
http://api.jquery.com/click/
From JQuery - .click()
.click( handler(eventObject) )
handler(eventObject)A function to execute each time the event is triggered.
Your doReport() function is getting an event object.
wrap it with another function if you need to pass an argument to your function.
$(document).ready(function() {
$('#doReport').click(function(event){
doReport('blah');
});
});