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()
Related
I am wondering if anyone can help with understanding this Javascript syntax.
Lets say I have the following:
<script>
$(function(){
$("#contactbutton").click(function(event){
$("#dialog").dialog({width:500});
});
});
</script>
I understand that the first line is testing if the DOM is ready and loaded. It then passes control to the inside function.
This inside function gets the element with an ID of contactbutton and for the click event, passes control to the next function.
This inner function, gets the elemnt with an ID of dialog and calls the .dialog method to display the dialog box. However, I am not sure about:
function(event)
What is the event parameter here, and why do we need it? Also, can this be renamed to anything we want?
Thanks,
This is actually an object that is accessible within that function. Usually it is called the event reference. The object holds details, functions, variables, etc., about the function and event, allowing you to handle the event and access properties of it. You are able to access it once you set a name to the first argument of the handler, that is function(event) { }
In a certain case, say you wanted to prevent the default event of an anchor link which would be to navigate the page to stackoverflow.com. preventDefault is a function that can do this, that is, prevent the default event. In this case that would be to prevent the navigation to stackoverflow.com. You are able to access the preventDefault function using the syntax event.preventDefault() if you have assigned the name event to the first argument of the handler.
For another example, in an onkeydown event you can access which key has been pressed with event.keyCode.
In $.ready() I have declared a click function as shown below
$(document).ready(function(){
$("#btnClk").click(function(clkevent){
//Doing Something Here
clkevent.preventDefault();
});
});
I want to remove this click() from $("#btnClk") in another javaScript function. How can I do this?
One of the problems with the proposed solutions is they remove all click event handlers registered, which may not be desired.
A solution to this is to separate the handler method out to a common scope shared by the both the participating methods then use that method reference along with .off() to resolve this
function btnclickHandler(clkevent){
//Doing Something Here
clkevent.preventDefault();
}
$(document).ready(function(){
$("#btnClk").click(btnclickHandler);
});
$("#btnClk").off('click', btnclickHandler);
Old School
$("#btnClk").unbind('click');
New School
$("#btnClk").off('click');
To register a click handler you should be using .on('click', ...) instead of .click - the latter can cause confusion because the same function is also used to trigger a click event.
To unregister the handler, use .off('click')
Please see the caveats at http://api.jquery.com/off/ regarding function handlers, name spaces, etc (my emphasis):
If a simple event name such as "click" is provided, all events of that type (both direct and delegated) are removed from the elements in the jQuery set.
and
A handler can also be removed by specifying the function name in the handler argument.
Note that in the latter case you can't specify the function name if the function never had a name in the first place, as in the code in the question where the handler is an anonymous function.
You can use unbind for this .
$('#btnClk).unbind('click');
almost same question
You can do this using off():
$('#btnClk').off('click');
This will remove all click event handlers from the btnClk.
So, there are two important details to this question:
its inside the scope of document ready's callback function
the element that the event is attached to does not actually exist in the DOM
Here's a visual representation of the scenario
$(document).ready(function() {
$('#myNonExistentElement').on('click', function() {
//do something
});
});
Is it possible to programatically trigger that click event (via console or something else) under those circumstances?
I think the simple answer is no.
There are two cases which might, however, fit with your question:
1) If you just want to execute the event handler code, use a named function (instead of an anonymous function) and call it whenever you need to.
2) If you want to bind a click handler to an object that does not yet exist in the DOM but you know will in the future, you can use code like:
$(document).ready(function() {
$('body').on('click', '#myNonExistentElement', function() {
//do something
});
});
See the section about delegated events at http://api.jquery.com/on/
If you try to bind an event to an element that doesn't exist via jQuery (or at the very least, .on) no new event will be bound.
Sample case here.
*event code stolen from here because I'm lazy.
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>
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
}