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.
Related
I have some JavaScript/jQuery code that needs to call the checkbox's click handler after it completes.
I can use trigger() to call that handler; however, I see that this also causes the checkbox's checked state to toggle (as though it had been clicked).
Is there any way to call a click handler without actually performing a click on the checkbox?
Is there any way to call a click handler without actually performing a click on the checkbox?
Yes
The handler is just a function. Call the function:
function example() {
$(this)...do something...
}
$(...selector...).on('click', example);
...elsewhere...
$(...another selector...).each(example)
If you don't have a reference to the function, and you want to trigger all handlers on the element without triggering the native behaviors, you can use jQuery's .triggerHandler() method.
$(...selector...).on('click', function () {...})
...elsewhere...
$(...another selector...).triggerHandler('click')
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 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.
I have a function called A(), this function contains addEventListener for button click. As per my application, function A() is called before button has created. So button is being templated after function A() called. What's happen is addEventListener for button click is not working inside A() when I click on button. If I call function A() after button been created, addEventListener for button click inside function A() is working.
How can I make work addEventListener for button click inside A() when I click on button, but function A() should be called before button template
You could use something like jQuery's solution for listening on dynamic elements. The idea is to listen for the click event on a parent of the button that is in the document when you add the listener, worst case scenario being the document itself. In the click handler check if the target of the event is the button you are interested in and if it is, do the actual work you want it to do.
Another potential solution is to "record" the handlers you want to place and apply them after the elements you are interested in are added to the document.
What does event binding mean? I always come across this word whenever I search around the internet and whatever I try to look for the meaning, it's still vague to me #_#
A while ago, while reading some blogs regarding JavaScript I see people using this sacred word that I cannot grasp.
Event binding refers to telling the browser that a particular function should be called whenever some 'event' occurs. Events mostly relate to user input, such as clicks.
An example of binding to an event in jQuery can be the following:
$("#elem").bind("click", function() {
alert("Clicked!");
});
This binds a function to click event of DOM object with identifier elem. When user clicks it, an alert (message box) will be shown. Binding is done by invoking the jQuery bind function but there are other means to do that, (e.g. jQuery click function in case of binding to click event).
When you bind something to an event, it will be triggered when the event is fired. It's like gluing a fog horn to the brake pedal on your car.
When you perform an action on a web page, it will trigger an event. This might be something like:
Click a button
Select a value from a drop down
Hover the mouse over an item
These events can be captured in your JavaScript code.
A common (and often misguided) way of capturing events is to do so on the HTML element itself (as shown in the onclick attribute below)
<input id="MyButton" type="button" value="clickme" onclick="Somefunction()" />
So, when the user clicks the button, the SomeFunction function will be executed.
However, it is considered a better approach to adopt a technique called 'late-binding'. This ensures that your HTML and JavaScript are kept completely separate.
So, we can modify the above exmample like so:
document.getElementById("MyButton").onclick = function(){
//functionality here.
}
jQuery makes this even easier:
$("#MyButton").click(function(){
//functionality here.
});
Binding in JS, is to capture some events (like focus, click, onmouseover, etc) and perform some other stuff before the actual process starts.
Detailed explanation:
http://triaslama.wordpress.com/2008/07/22/four-ways-javascript-binding-event-listeners/
http://api.jquery.com/bind/