JavaScript: parameters for unnamed functions - javascript

In the following jQuery JavaScript code, what value does the parameter "e" take on within the function? I'm having difficulty understanding this because this function cannot be passed an argument elsewhere in the code so how would having a parameter work? And how would I use parameters in such functions that are not named and not called anywhere else in the code?
$(document).ready( function() {
$('div').each(function() {
$(this).click(function(e){
//some code
});
});
});

click sets the event handler. The click handler gets called by the browser when the event occurs, and the e parameter contains information about that event.
For keypress events, it contains which keys were pressed and what modifiers were pressed at that time (shift, control, etc.).
For mouse events, it contains the position of the click and which button was used.
See http://www.quirksmode.org/js/events_properties.html for more information about the properties of the event structure.

e is an eventObject as you can see in the jQuery click documentation.
I do not know what you can do with it however, but it should contain information about the click event. Maybe it's the standard DOM event.

That anonymous function is called when the event is fired, and e is an eventObject:
click( fn )
// fn, a function to bind to the click event on each of the matched elements.
function callback(eventObject) {
this; // dom element
}

Related

Accessing event object in event handler javascript

I have a code snippet
$(document).on("click", "div[data-role=button]", myfunc);
function myfunc(e){
alert(event.target);
alert(e.target);
alert(event.currentTarget);
alert(e.currentTarget);
}
Each of them give different outputs when i click on the
element.
e is of type object
event is oftype MouseEvent
The e.currentTarget seems to give the correct answer.
My question is if i decided to add another parameter to my handler, how will i get to access the "e", parameter which gives the right answer.
EDIT:
I want to do
function myfunc(e,str){
}
How can i access e inside my function and how do i pass the two arguments?
EDIT 2
I found another interesting thing,
this
this correctly gives the target, even though i expected it to give the document any idea why?
You access e the same way you are already doing, I guess what you mean is how to set the handler in the click event. How about like this:
$(document).on("click", "div[data-role=button]", function(e) { myfunc(e, "some string"); });
Of course that doesn't make "some string" very flexible (unless you are rebinding the event when it changes), so it could just as easily be fixed in the myfunc function.
If you want it to be based on something, perhaps an attribute of the element being clicked, then perhaps you want:
$(document).on("click", "div[data-role=button]", function(e) { myfunc(e, $(this).data("string")); });
which will get the value of a data-string attribute, for example:
<div data-role="button" data-string="my string 1"></div>
Inside myFucnc e is a local variable that refers to the event object. event probably refers to a closure or a global variable.
The difference between target vs currentTarget is the following:
Identifies the current target for the event, as the event traverses the DOM. It always refers to the element the event handler has been attached to as opposed to event.target which identifies the element on which the event occurred.
https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

Basic jQuery understanding

What is the event
$(document).ready(function(){
$("a").click(function(event){
alert("Thanks for visiting!");
});
});
and also this one
$(document).ready(function(){
$("a").click(function(){
alert("Thanks for visiting!");
});
});
these two JS blocks are doing the same thing, but one with an event, if someone could explain what is function(event), also I saw something like function(e),function(g), what are those? Is there a tutorial I could learn?
The callback function that you're providing to $("a").click is a function that takes an argument. This argument is an event object containing details about the object. Your function declaration can take this argument with any name you like — event, e, g... and it can also simply leave it out since you're not using it inside of your function.
Consider that these two functions are essentially the same:
function foo(hi) {
alert(hi);
}
function foo(bye) {
alert(bye);
}
And that you may leave out the argument if it's not used:
function bar() {
alert("hello!");
}
bar(12345);
Event is an object that represents the... event that produced that function to be executed.
Here's more information about the topic:
http://api.jquery.com/category/events/event-object/
It is often used to prevent default behaviour of a certain event, or to stop the propagation of the event to parent objects:
function(e){
e.stopPropagation();
e.preventDefault();
}
The event in the first example is an unused argument.
jQuery passes various arguments into each event handler - you can find details of what these arguments are in the documentation (e.g. http://api.jquery.com/click/).
As you do not need to use the event object (or e, or g - you can give the parameter any name you want) then it doesn't matter whether or not you include it
However, if you needed to use the handler for some reason (e.g. to call event.preventDefault() to prevent the default click behaviour from happening) then you would need to include it.
jQuery passes eventObject to the handler/callback function which is not used in your example.
You could read more about the eventObject in JQuery.
Events : An event in JavaScript is something that happens with or on the webpage.
Example of events:
A mouse click
The webpage loading
Mousing over a hot spot on the webpage, also known as hovering
Selecting an input box in an HTML form
A keystroke etc...
Events in Jquery
Using e is just a short for event.You could use any variable say g instead of e
$('#xyz_id').click(function(g){
var clicked_target = g.target;
});
You could have a look at events in jquery further at
http://api.jquery.com/category/events/event-object/
event argument is a optional parameter and it can be any valid variable name. Based on your requirement you can pass or ignore it.
Visit http://api.jquery.com/click/ for more info.
.click( handler(eventObject) )
handler(eventObject)A function to execute each time the event is triggered.
version added: 1.4.3.click( [eventData], handler(eventObject) )
eventDataA map of data that will be passed to the event handler.
handler(eventObject)A function to execute each time the event is triggered.
version added: 1.0.click()

Why do you have to pass the event object as a parameter?

I'm learning how to manipulate events in JavaScript and I'm wondering "why do you have to pass the event object as a parameter (argument) into a function when using event handling?"
Here's an example of what I am talking about:
<script type="text/javascript">
document.getElementById('button_1').onclick = (function (event) {
alert("The event is: " + "on" + event.type);
});
</script>
I wrote the code above and I pretty much understand what it does. I just don't understand the whole (event) passing. I thought of this as a way of assigning an anonymous function to the button_1.onclick event handler. Does the event handler try to pass in an event before it gets assigned or?... I'm having a difficult time understanding this. If someone could please clarify this for me I would be grateful.
[I tried searching it on Google but found very complex explanations and examples. Only a simple-to-intermediate explanation would help.] =)
The Ever-Present Event, Whether You Like it or Not
The event is always present, even when you don't provide a name:
$(".foo").on("click", function(){
alert( arguments[0].type );
});
That is the same as saying this:
$(".foo").on("click", function(event){
alert( event.type );
});
The event object is already being passed to your callback (whether your provide a name for it or not), you can choose to not use it if you like. For instance, if we looked to a jQuery onClick method:
$(".foo").on("click", function(){
/* Do stuff */
});
Making Use of It
You'll note that I have no event object referenced in my callback. I'm not required to. However, if I want to use it, for whatever purpose, I should give it a name:
$(".foo").on("click", function(myEvent){
myEvent.preventDefault();
myEvent.stopPropagation();
});
Now that I have granted myself access to the event details, I can prevent the default behavior that would result from the event, and I can also stop the event from bubbling up the DOM to other elements.
Practical Example
Suppose we wanted to listen for click events on an element:
$("#bigSquare").on("click", function(event){
/* Do something */
});
Click events happen on an element when you click the element itself, or any of its children. Now suppose this element had two children:
<div id="bigSquare">
<div id="redSquare"></div>
<div id="blueSquare"></div>
</div>
Clicking any of these, the big square, the red square, or the blue square will cause the "click" event on the big square - after it causes the click event on whichever element you clicked first (events bubble up the DOM).
We could determine which element was the target in any click event via the event itself:
$("#bigSquare").on("click", function(event){
alert( event.target.id );
});
Note here how we're accessing the ID of the target that raised the event. If you click on the red square, when that event bubbles up to the big square, we will see alerted "redSquare". The same goes for the blue square. If you click that, the event will bubble up to the big square and we will see alerted "blueSquare".
You can test this online via the following demo: http://jsbin.com/ejekim/edit#javascript,live
Try clicking the orange, red, or blue square to see what is alerted.
You are not passing the event parameter anywhere. You are just making a function that takes one parameter, called event.
When the browser calls the event handlers, it calls the function(s) assigned to it, and passes the event object to it as the 1st parameter.
P.S. You don't need the () around your function.
document.getElementById('button_1').onclick = function (event) {
alert("The event is: " + "on" + event.type);
};
You aren't passing an event into the function, you are naming the first parameter passed to your function event.
The browser is the one that is going to call your function and it passes an event object when it calls your function. You can choose not to name that parameter function(){} but the browser is still going to pass the event object in, you can use it or not use it as you see fit.
Simply put, the Event object passed to a handler contains details about the event. For example, a KeyboardEvent contain info about the key pressed, the corresponding character, and any modifier keys (alt, shift, control, meta) that were held down.
Does the event handler try to pass in an event before it gets assigned or?
The handler is your function, so it's the receiver of event, not the passer.
The event handler is bound when you assign it to the element's onclick property (or by calling addEventListener, the modern, preferred method), which is before the handler is invoked.
The Event object is passed when the handler is invoked, which is when the event fires.
So, when a user clicks on your #button_1, this causes a "click" event to fire on the button, which invokes the button's "click" handler, which is passed a MouseEvent.
For more information, read about event-driven programming.
To add to the others answers and comments, your code will not work with IE. For cross-browser capability, you need to test the existence of the first argument:
<body>
<button id="button_1">Click Me!</button>
<script type="text/javascript" >
document.getElementById('button_1').onclick = (
function(event) {
var e = event ? event : window.event;
alert("The event is: " + "on" + e.type);
});
</script>
</body>

Mootools events, callable?

So I have an element that has an onClick event thusly:
var foobar = $('element').addEvent('click', function() {
// some code here
});
But I want to call the action from somewhere else in the script, would it be possible to do such a thing, i.e."
foobar.click
?
You can fire events in mootools:
$('element').fireEvent('click');
http://mootools.net/docs/core/Element/Element.Event#Element:fireEvent
In addition you can pass in parameters or a delay, chain the event to other events, or bind another element or function with the event.
If you have more than one 'click' event on the element, it will fire all of them.
Check out the docs.
Yes. From http://mootools.net/docs/core/Element/Element.Event#Element:fireEvent :
foobar.fireEvent('click');

JQuery explanation on document.ready

I have question will the click event or any other event run in document.ready() for the first time?
I mean will it reach after loading DOM elements to the comment without clicking first time? :)
$(document).ready(
$(#foo).click(
function()
{
// "It reached here after DOM is loaded!"
}
)
)
document.ready fires when the DOM is fully loaded, so you would be correct.
The 'click' event, however, will not fire unless the bound element is clicked or the click event is explicitly called using click() or Events/trigger:
$('#foo').click();
$('#foo').trigger("click");
Have you read the manual page for document.ready? See:
http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
No, the function will not be executed.
There are a few errors:
$(document).ready() takes a function as an argument.
'#foo' should also be a string.
$(document).ready(function() {
$('#foo').click(
function()
{
// "It reached here after DOM is loaded!"
}
)
})
If you want the function to be evaluated at least once, after the dom loads. Then probably the easiest way is to name your function.
eg:
$(document).ready(function() {
$('#foo').click(
function myfunction()
{
// "It reached here after DOM is loaded!"
}
);
myfunction();
})
If you need the function to execute in the scope of $('#foo') you can do so with Function.call() method.
eg:
$(document).ready(function() {
$('#foo').click(
function myfunction()
{
// "It reached here after DOM is loaded!"
}
);
myfunction.call($('foo'));
})
That would make it behave more like as it were triggered by a DOM event. I'm sure JQuery has a specific method of triggering an event registered through it's DOM event functions. It would also be an option to use that as it would probably also emulate the Event Object passed to "myfunction".
To generalize the question, JavaScript events are handled by associating an event type (onclick, onkeyup, onfocuse, etc) with a function (or multiple functions). The function is, of course, parsed, but is not evaluated until the associated event occurs. Also, the "function," in this context, is often referred to as an event handler or event callback.

Categories

Resources