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.
Related
I have a button. I registered a function to treat the click event. However, I want to call it if another event happens. How do I call it from another asynchronous (or synchronous) event?
My first idea was to write the function with a name. That way, I can bind it to the click event to my button and also call it whenever I want to. However, in the case I wrote an anonymous function, what are my options?
Example (pseudo-code):
create button b;
assign some function f to b to execute on click;
b.invoke(args); //invoke runs f without the need to click
You can fire the "click" event on the element.
$('#MyButton').trigger('click');
EDIT: sorry, I misunderstood the question. But, you can still trigger the event and let the function to use some global variable so you can access everywhere.
I just got through figuring out that I need to watch out for duplicate event handlers in jquery if I'm dynamically assigning them multiple times as described here: http://www.parallaxinfotech.com/blog/preventing-duplicate-jquery-click-events
Do I need to watch out for this or handle it somehow if I'm declaring a function dynamically within another function multiple times? How does JavaScript really handle this? Does it only use the last function that was called or does it only instantiate a function once at load time? From what I can tell it's not running the function multiple times.
$(document).on("click",".button",function() {
function alertThem()
{
alert('Clicked!');
}
alertThem();
});
JavaScript will remember every function you're assigning it.
$('button').click(function(){
alert('hi')
})
$('button').click(function(){
alert('hi')
})
The code above will alert "hi" twice. If you're assign new function and you want to clear the old one, you can do unbind().click(). what it will do is it will unbind all events, or you can do unbind('click') which will unbind just the click. see https://jsfiddle.net/rznbtc1p/
$('button').click(function(){
alert('hi')
})
$('button').unbind().click(function(){
alert('hi')
})
The link you provided does not work (gives me timeout) so I hope I understood what you asked.
About what happens there:
In your script you created a closure and bound it to a click event. Each time you click on the element with class button, the anonymous function is triggered. Each time is triggered it defines function alertThem(), and calls it. Only once defines it, only once calls it. The scope of that function is its parent, the closure. That function is not defined outside that scope, so no need to worry about double definition.
Side note here: Personally as a rule of thumb don't think is a good idea to define functions like this, but if it suits your project... go for it.
Now about duplication. Since I cannot see the link, I think you are referring to double event binding.
In js can bind any number of events to the same element. You can for example bind on click something that says "Hi, you clicked me", then bind also on click something that says "Hi, you received a message before saying you clicked me". When you click that element, you will see both messages.
This can actually become a problem. You have 3 options:
Be really careful how you bind events
Keep tracking of what you bound
Check if events are already bound (although that is a bit unreliable). You can check how here: jQuery find events handlers registered with an object
In your code snippet, you aren't creating duplicate event handlers.
What is happening in your snippet is that you are creating a new function alertThem within the scope of your click handler function and then executing it in the line below.
I have a situation where a click eventlistener is being set on on a dynamic element using jQuery's .on:
$('body').on('click', '#email-me', function() {
call my code....
});
and later on in the page, I have to remove this listener - but - and here's the catch - I DON'T have access to jQuery anymore (long story), which means pure js...
so, I can't use unBind(), and even if i name my anonymous function up there, it still won't remove the event listener.
How do I remove the bind, so this element isn't clickable anymore?
Thanks for reading!
You can't. jQuery events are handled differently than normal javascript events.
When you add an event to an element with jQuery, these steps are followed:
If the element hasn't been initialized with an internal (internal to jquery) datacache, it gets initialized with a datacache, then the datacache is returned.
If this is the first event handler added for that event type, a special event is added to the element for that event type that executes jQuery.event.dispatch.
Finally, the handler(s) that you passed in are added to the datacache.
Therefore, the only way for you to remove this event is to get ahold of the special event handler that jQuery bound that triggers jQuery.event.dispatch, but since you don't have access to jQuery, there's no way you will get that event handler. (even with access to jQuery, I don't think you can get that handler.)
You need to instead find a way to retain access to jQuery, or don't use it at all.
I could not make preventdefault to prevent action. I apologize if the answer is too easy but I simply cant find the error. why is it not preventing from entering the link? jsfiddle given below.
http://jsfiddle.net/zwY5p/34/
$('#theForm').click(function(e) {
event.preventDefault();
alert('FORM!');
});
e != event
$('#theForm').click(function(event) {
event.preventDefault();
alert('FORM!');
});
The parameter passed to the handler function is what you need to execute preventDefault on. In your code, you are passing e but calling preventDefault on event.
preventDefault prevents the default browser action. It does not cancel the inline JavaScript, since that runs first. If you have to override that, just remove it (no event listener necessary):
$('#theForm').removeAttr('onclick').
your event parameter name e and the variable you are using event are different,
$('#theForm').click(function(event) {
event.preventDefault();
alert('FORM!');
});
Other than the errors pointed out on other answers there's another small issue, specifically in your markup declaration:
<!-- Use either the closing tag or the slash (/) in the opening tag -->
<button id="theForm" onclick="location.href='http://www.example.com'" />
go to google
</button>
On the topic, you have two different handlers attached to the button element, they are both handling the click event but they are still different and separate things. jQuery won't know about the handler defined in the markup:
var btn = document.getElementById('theForm');
jQuery._data( btn, "events" );
will return an array with a single element which is the handler added via jQuery.
Now you have to re-evaluate the need of two different handlers for the same element and event and apply conditions. Do you really need to do it this way?
You're using 2 'click' events.
You end up using preventDefault once, and it's used after the 1st click event has ran.
If you make your button an href, then your preventDefault will be working.
It will also make more sense, as the JS will be separated from the HTML markup.
Also, of course you must use the same parameter name. (function(event), with event.preventDefault for example).
If you are passing "e" as an event to the function then you should prevent the default action only for that "e" that you have passed and not for "event".
$('#theForm').click(function(e) {
e.preventDefault();
alert('FORM!');
});
jQuery preventDefault() method: http://api.jquery.com/event.preventDefault/
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()