Event 'e' in Javascript Function's Parameter [duplicate] - javascript

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.

Related

Is using event.target necessary when capturing input data?

I'm currently following a tutorial about Javascript events. Basically, what the instructor is walking us through is how to listen to user input data from the HTML input tag using the keyup Javascript event and then logging the value on the console.
Here's the code snippet:
document.getElementById("searchInput").addEventListener("keyup", function(event) {
let searchQuery = event.target.value.toLowerCase();
console.log(searchQuery);
});
It's straightforward, however, I'm curious about the significance of adding the event parameter and accessing the target property of such event. I went ahead and removed the event parameter, as well as the target property, and made it so as to log the value, too, and, as far as I am aware, it behaved identically.
document.getElementById("searchInput").addEventListener("keyup", function () {
let searchQuery = document.getElementById("searchInput").value.toLowerCase();
console.log(searchQuery);
});
Is there a unique reason why the instructor chose to do the former or is it simply for brevity reasons?
It’s useful if you want to write a more general function that would work with whatever element you pass into it. Currently you are specifying the id of the element you’d like to access within the function. But at some point you may want to write a function that you can reuse with multiple elements at once, this is where event.target comes in.

function parameter in addEventListener

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>

Is there actually a good reason for jQuery to manipulate 'this' keyword in event handlers?

Given the following, common scenario:
console.log(this); // window or any parent object
$('.selector').on('click', function(event) {
console.log(this); // clicked DOM element
});
var myFunc = function() {
console.log(this); // window or parent object
}
Since version 1.3 jQuery adds the event.currentTarget when binding event handlers for which counts event.currentTarget === this, so is there actually a good reason to manipulate this and switch context? Doesn't this behaviour generally go against the unspoken rule of "don't change keyword values" (like undefined = 'not defined')?
This "feature" of jQuery makes a lot of OOP less efficient and awkward imho, when we need to either cache the original this in a variable like self or use helpers like jQuery.proxy to reassign context to event handlers.
My question: is this just a relic of early jQuery implementations kept alive or is there an actual benefit which I cannot see (except maybe the slightly more convenient way than accessing event.currentTarget to get the element...)?
Let's say you've got an object with some methods on it:
var object = {
click: function() {
alert(this.property);
},
property: "Hello World"
}
You can call object.click() and, as you'd expect, you'll get "Hello World" in the alert.
You'd like to be able to use that "click" function as an event handler:
$("button").on("click", object.click);
However you discover that that doesn't work, because jQuery invokes the "click" function with this set to the DOM node for the clicked button. This is irritating. It's also inevitable because of the semantics of JavaScript function calls.
When you call the "click" function by way of a property reference, the language arranges for this to refer to that object. That's why object.click() works. However, when you fetch the reference to the function and pass it across a function boundary (as in the call to .on()), that relationship is lost. All that the jQuery method gets is a plain unadorned function that has absolutely no inherent relationship to the original object involved in its definition.
Thus, jQuery really has only two choices. The first is that it could make explicit the fact that the function is unconnected by arranging for this to be undefined. That wouldn't be very useful however. The other choice is to pick something interesting for this, and that's what the library does. Note that the native DOM level 0 event dispatch mechanism does the same thing.
The reason is that jQuery wants to mimic how regular event handlers (ones created without jQuery or any other library) works. In regular event handlers the value of this refers to the DOM node that triggers the event if there is one.
One could in fact consider that this is an example of jQuery not manipulating built-in behavior.

How jquery define click function for get parameter inside anonymous function?

I dont understand javascript syntax well,my question:
How jquery define click function for get parameter inside anonymous function?
The Case:
$("a").click(function(event) {
alert(event.type);
});
in C the function should be defined:
void click(fn,event){
}
in javascript its looks to me that she defined as- (but where defined event?):
click (fn){
}
please explain to me the jquery syntax of click function code source here.
Thanks,
Yosef
If you just want to find out where the event object is passed to your handler, that would be line 2568 of the jQuery-1.5.2 redistributable source code (or line 438 of the actual, un-contatenated source file):
var ret = handleObj.handler.apply( this, args );
In the above line of code, handler is your anonymous function and args is an array whose first element is the event object. jQuery uses the apply method of the JavaScript Function object to invoke the handler and pass in the arguments
The jQuery source code is quite complex when it comes to full sequence of adding and handling events so, unless you want a line-by-line explanation of hundreds of lines of code, I suggest you rephrase your question to a smaller scope (e.g. You could create a toy demonstration of the scenario you want to understand).
Perhaps this will help?
dosomething(function(message) {
alert(message);
});
function dosomething(fn) {
fn("Hello!");
}
The first part of the jQuery is the selector $("a") which selects and returns object(s) selected from the DOM. In this case, it will return a list of all anchor tag objects on the page.
Then, you are chaining the .click() method to that, jQuery attaches an event listener to all of the anchor tags. When the event listener is attached, it is more or less the equivalent of doing
<a href='..' onclick='someFunction(event)'>some link</a>
...which passes the event object to the function.
For example, compare to this:
<a onclick='blah(event)'>click</a>
<script type='text/javascript'>
function blah(e) {
alert (e.type);
}
</script>
If I click on it, I will see "click" in the alert. In principle, jQuery is doing the same thing.

Can someone explain why this is passing in an object

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');
});
});

Categories