Normally to bind multiple events to an element, one would use .on():
$("select#id").on("click change").function(){
// do actions
});
However, the use of ready with .on() is deprecated as of jQuery 1.8:
// Deprecated
$(document).on("ready", handler)
.on("ready") also behaves differently from .ready(). Specifically, handlers will not execute if .on("ready") is bound to elements after they are ready, whereas .ready() will execute even when called after the elements are ready.
You could accomplish it with a named function:
var myFunction = function(){
// do actions
};
$(document).ready(myFunction);
$("select#id").change(myFunction);
but that is less than ideal. Using a single anonymous function would be cleaner.
One method is:
$(document).ready(function(){
$("select#id").change(function(){
// do actions
}).change();
});
This will define the handler for the change event and then immediately call the change event. Because it's inside of the ready() handler, it will be executed for both ready and change events.
Sorry, you simply can't do it in more recent versions of jquery.
Your code as-is doesn't really make any sense, there's no reason to ever use anything other than document inside of $() when you're using .ready because .ready will simply ignore whatever is currently selected and perform it's action as if document were selected.
$(document).ready(function(){
$("#theid").change(changeHandler).change();
});
If the only goal is to only use 1 anonymous function, event delegation will do it, however it's probably overkill.
$(document).on('change','#theid',thehandler);
where thehandler is an anonymous function or a named function, you choose.
Related
Example 1
Example 2
...Both of these use (from what I can tell) jquery's clone on a function block, as the outermost element of the script. Why is it done this way? What would be lost if that were omitted?
P.S. Is this like instantiating an object from a class?
It is needed to call the function when the document is ready.
As of http://api.jquery.com/ready/
$(document).ready(function() {
// Handler for .ready() called.
});
Which is equivalent to calling:
$(function() {
// Handler for .ready() called.
});
that obviously is equal to
jQuery(function() {
// Your code using failsafe $ alias here...
});
here jQuery is used instead in order to not conflict with $ in case it's used by another library.
This is basically the DOMReady event. The function with your code is the code to be executed when the DOM is ready, but before all resources are loaded.
This ensures that all the HTML elements in your source code would be ready for manipulation in JS. Otherwise you may miss elements that are otherwise in your source code when trying to select them.
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 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.
I have setup onclick event handler in the following manner:
element.onclick = function() { /*code */ }
Imagine there are event handlers setup using jQuery method bind() or similar handlers.
$('element').bind('click', function(){/*another function*/})
How can I prevent invoking handler defined with jQuery from the handler I have described in the beginning?
NB stopPropagation() and etc. jQuery's methods doesn't work from that function, because it is passed with native event object.
I'm not 100% sure what you're asking but maybe this will help:
You can create a new event object (compliant with W3C DOM) via jQuery's exposed Event constructor:
For example:
element.onclick = function(e) {
var aBetterEventObject = jQuery.Event(e);
// Now you can do what you want: (Cross-browser)
aBetterEventObject.preventDefault()
aBetterEventObject.isDefaultPrevented()
aBetterEventObject.stopPropagation()
aBetterEventObject.isPropagationStopped()
aBetterEventObject.stopImmediatePropagation()
aBetterEventObject.isImmediatePropagationStopped()
}
EDIT: Reading through your question again, I don't think propagation is the problem - you seem to want to cancel an event handler from running within an event handler - I'm not sure this is possible. You could just unbind all handlers (jQuery(elem).unbind('click')) but I don't think that's what you're after...
try to add the following line in the jQuery event handler:
return false;
Following on from JimmyP's answer. I've tried this
$('#x').click( function(e){
alert('hello');
});
document.getElementById('x').onclick = function(){
$('#x').unbind('click');
alert("goodbye");
}
The jQuery event runs once in this example. I don't think you can rely on the order of handlers being invoked however you define them, so I guess you'll have to accept that the jQuery event might fire once. Adding the onclick first does prevent the jQuery event from firing at all but, as I said, I don't think that's reliable.
Jquery has a method for namespacing events. http://docs.jquery.com/Namespaced_Events
You can add, trigger and remove separate functions bound to the same event via namespaces:
$("a").bind("click.custom1",function(){ ... });
$("a").bind("click.custom2",function(){ ... });
$("a").trigger("click.custom2");
$("a").unbind("click.custom2");
As long as you unbind the namespaced event your normal onclick should be unaffected. You may have to bind two separate namespaces to the click event as above if that doesn't work.