Basically I'd like to bind function A to all inputs. Something like this:
$('input').bind('change', function() { bla bla bla });
And then later I would like to bind something different in addition like this:
$('#inputName').bind('change', function() { do additional processing..});
Is that possible? Does it work? Am I missing the syntax? Is that fine actually fine (meaning I have a bug elsewhere that's causing one of these not to bind)?
The short answer to your question is YES.
If you wish to bind additional functionality to the change event of #inputName, your code sample should work.
If you wish to alter the function that handles the event you can unbind all handlers of the change event before you rebind any new event handlers like so...
$('#inputName').unbind('change');
but be careful... w/o trying this out I am unsure of any of the side affects.
Why don't you create a function that call them both, and then bind this new function to the event?
In your code, one is input, and the other inputName, is that a typo?
Searched, there is a similar question here.
$(document).ready(function() {
$("input").change(function() {
console.log("function1");
});
$("input").change(function() {
console.log("function2");
});
});
assuming the above is resolved (i.e. you're trying to bind a function to the same object), yes, you can bind multiple event handlers to the same one.
to make your life easier, look into namespaces for this as well (so you can group event handlers for the same event).
It works fine to bind both. Where it gets slightly interesting is when you're trying to prevent default behavior by returning false. The bound functions cannot prevent each other from running that way, but they can prevent parent elements' event handlers from running.
Related
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.
To hopefully head off the "primarily-opinion-based" close-button-clickers, I'm not looking for opinions on the "best" way to do this; I'm just wondering if there is a more straightforward solution that I'm missing.
My goal is to add the same onclick method to all of the (hundreds of) checkboxes on my page. My first attempt at a jQuery solution was this:
$('input[type="checkbox"]').prop('onclick', function(){alert("Boop!");})
But that runs into the computed-value behavior of $.prop() and calls the function immediately for each checkbox.
So I can do this:
$('input[type="checkbox"]').prop('onclick', function(){return function() {alert("Boop!");}})
But that feels awfully workaround-y. Alternatively, I could do this:
$('input[type="checkbox"]').each(function(_, cb) {
cb.onclick = function(){alert("Boop!");};
});
But that seems uncharacteristically manual for jQuery.
So am I missing a more straightforward solution?
Declare the function and then simply refer to it by name:
function handler() { alert("Boop!"); }
$("input[type='checkbox']").on("click", handler);
Note that you shouldn't be setting up event handlers by setting the "onfoo" properties.
edit — if what you want to avoid is adding the handler over and over again, use delegation:
$("body").on("click", "input:checkbox", handler);
That creates only one event handler registration. As "click" events bubble up the DOM to the body, jQuery will check to see which ones targeted elements that match the selector, and invoke your handler for those that do. (Opinion — I've mostly adopted the practice of exclusively using body-level delegation for all events. It makes things a lot less messy.)
you have to write event no use prop:
$('input:checkbox').on('click', function(){alert("Boop!");})
i will suggest to use change event for checkbox not click:
$('input:checkbox').on('change', function(){
if(this.checked)
{
alert("checked");
}
});
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.
I'm talking about the following:
.unbind().click(function () {
// Do something
}
It looks a bit dodgy to me, however it makes sense: the developer wants to first remove any events bound to the element and then bind a click event.
Is there a better solution for this issue? Or correct my way of thinking.
It's not really good practice, because you do not control which click events get unbound. There are two different approaches to improve this:
Use event namespaces (faster)
You can use a namespace to control you unbind just the click event you're going to bind again:
$(selector).off('click.namespace').on('click.namespace', function(e) { //...
Use classes (fastest)
Use classes added to the link to mark it as registered (this does not unbind previously bound events, but it helps preventing multiple event bindings, which is the issue in most cases you would use off (unbind) before on (bind):
$(selector).not('.registered').addClass('registered').on('click', function(e) { //...
You can even turn this into a little sexy plugin, writing:
$.fn.register = function(register_class) {
register_class || (register_class = 'registered'); // lets you control the class
return this.not('.' + register_class).addClass(register_class);
};
Like this, you can just call register on every selector:
$(selector).register().on('click', function(e) { //...
Or with a specific class, if «registered» is taken:
$(selector).register('special_handler_registered').on('click', function(e) { //...
Performance?
If you wonder about the performance of the different handlers:
Check out this performance test here
I followed this approach whenever I had to "renew" some button, link, ect., behavior, and I think there's nothing wrong with it.
But be aware that with your code you'd be removing every handler attached to the element(s). So, instead:
$(selector).unbind('click').click(function(){
// do something
})
Well, at least it is good practice to specify which event handlers should be unbinded. So if there was some click event hendler and we want to unbind only it, then we can use unbind('click').
As there can be some other handlers in addition to yours, it make sense to use namespaces.
$(selector).off('click.myns').on('click.myns', function() {....})
or
$(selector).unbind('click.myns').bind('click.myns',function() {...})
This way you will only touch your own handler and not some others, for instance added by jquery plugins
I usually try to used named event functions where ever possible in order to be able to unbind them explicitly:
$('a').unbind('click.myfunc').bind('click.myfunc', function(evt) { ... });
This way you could add this binding to an init-function that could be executed multiple times (handy for situations where you can't use delegate for whatever reason).
In general I would't try to unbind every event or even every handler of a certain event if I don't need to.
I'm also trying to stay current and replace all the bind/unbind calls with on/off ;-)
I want to make 'select' element to behave as if it was clicked while i click on a completely different divider. Is it possible to make it act as if it was clicked on when its not??
here is my code
http://jsfiddle.net/fiddlerOnDaRoof/B4JUK/
$(document).ready(function () {
$("#arrow").click(function () {
$("#selectCar").click() // I also tried trigger("click");
});
});
So far it didnt work with either .click();
nor with the .trigger("click");
Update:
From what i currently understand the answer is no, you cannot. Although click duplicates the functionality it will not work for certain examples like this one. If anybody knows why this is please post the answer below and i will accept it as best answer. Preferably please include examples for which it will not work correctly.
You can use the trigger(event) function like ("selector").trigger("click")
You can call the click function without arguments, which triggers an artificial click. E.g.:
$("selector for the element").click();
That will fire jQuery handlers and (I believe) DOM0 handlers as well. I don't think it fires It doesn't fire handlers added via DOM2-style addEventListener/attachEvent calls, as you can see here: Live example | source
jQuery(function($) {
$("#target").click(function() {
display("<code>click</code> received by jQuery handler");
});
document.getElementById("target").onclick = function() {
display("<code>click</code> received by DOM0 handler");
};
document.getElementById("target").addEventListener(
'click',
function() {
display("<code>click</code> received by DOM2 handler");
},
false
);
display("Triggering click");
$("#target").click();
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
And here's a version (source) using the onclick="..." attribute mechanism for the DOM0 handler; it gets triggered that way too.
Also note that it probably won't perform the default action; for instance this example (source) using a link, the link doesn't get followed.
If you're in control of the handlers attached to the element, this is usually not a great design choice; instead, you'd ideally make the action you want to take a function, and then call that function both when the element is clicked and at any other time you want to take that action. But if you're trying to trigger handlers attached by other code, you can try the simulated click.
Yes.
$('#yourElementID').click();
If you added the event listener with jquery you can use .trigger();
$('#my_element').trigger('click');
Sure, you can trigger a click on something using:
$('#elementID').trigger('click');
Have a look at the documentation here: http://api.jquery.com/trigger/
Seeing you jsfiddle, first learn to use this tool.
You selected MooTools and not jQuery. (updated here)
Now, triggering a "click" event on a select won't do much.
I guess you want the 2nd select to unroll at the same time as the 1st one.
As far as I know, it's not possible.
If not, try the "change" event on select.