I'm still confused sometimes by the way events are handled. I just wondered how to pass the event to it's handler.
The following example just works fine:
$(document).on('click', "div#foo", function(event) {
event.preventDefault();
});
But how to pass the event to an handler specified by name, like:
// this obviously wont work
$('div#foo').on('click', fooClick);
function fooClick(event){
event.preventDefault();
}
Thanks for your insights!
Your second example is exactly how to do it and that will work just fine.
It is the responsibility of .on() to set up the arguments to the callback it calls and what is passes has absolutely nothing to do with how you declare your callback. The first argument to the callback function will be the event object no matter how the callback is declared.
So, this will work just fine:
function fooClick(event){
event.preventDefault();
}
// this works just fine
$('div#foo').on('click', fooClick);
Working demo: http://jsfiddle.net/jfriend00/BWKde/
What's important to understand is that when you pass fooClick as the second argument to .on(), you are just passing a function reference. It is .on() who decides how to call that function reference and what to pass it.
FYI, your selectors will generally perform better if you pass just #foo, not div#foo unless you specifically want to only match #foo if it's in a div tag. Since id values can only be used once in a given page, you usually don't need to qualify them further and doing so just makes more (unnecessary) work for the selector engine.
your code is ok,
check at http://jsfiddle.net/9266U/ and read more at https://api.jquery.com/on/
$('div#foo').on('click', fooClick);
function fooClick(e){
alert("it work, nevrx");
e.preventDefault();
}
Javascript is synchronous, try to put it like this:
function fooClick(event){
event.preventDefault();
}
$('div#foo').on('click', fooClick);
Related
I have an element in a webpage which has several callbacks on it
// First callback
$("#element").click(fn1);
// Second callback
$("#element").click(fn2);
// Definitions
function fn1(){console.log("1");}
function fn2(){console.log("2");}
Is there a way to remove only fn2 from the list of callbacks triggered by jQuery.
I know I could add an 'if' inside the function and some global variable, but that's not what I'm looking for.
The second parameter in the unbind function specifies the handler to unbind.
$("#element").unbind("click", fn2);
Working Example: http://jsfiddle.net/k73Nx/
Interesting that nobody mentioned namespaces yet. Is there a reason for that?
When attaching your event, you can namespace it. Instead of $(elem).on('click', fn) you would add a namespace to the click event. $(elem).on('click.namespaced', fn)
When unbindung, you can then unbind that exact event, using the namespace as well.
$(elem).off('click.namespaced')
This is most practical when you're defining your event function inline.
One more thing you can do with namespaces is to unbind all event types within a namespae with just a single call: $(elem).off('.namespaced')
Be careful with your syntax here, other answers are very loose with theirs.
If you use:
$('#element').on('click',function() {
//callback code
});
Then you must use:
$('#element').off('click');
You cannot use
$('body').off('click','#element',function() { });
or
$(document).off('click','#element',function() { });
because you originally bound your event to #element, not to document or body.
Use unbind: http://api.jquery.com/unbind/
Example:
$(document).unbind('click', fn2);
use .off
$("#element").off("click",fn2);
working fiddle
So I'm trying to gain advance Javascript skills. So I'm doing a practical JS tutorial on Lynda.com. Chapter 3 is on EventHandlers and I'm a little confused (Note: I've deleted the code that makes the script work in all browsers). I've rewatched the videos and that hasn't been helpful at all.
What is the e referring to? I don't have a variable at all named e or anything else that I can see.
What is false referring to? Is it the same as return false since I'm dealing with a link?
function clickLink(e) {
alert("You Clicked the Link");
}
function linkClicked(e) {
addEventHandler(document.getElementById("clickLink"), "click", clickLink, false);
}
addEventHandler(window, "load", linkClicked, false);
The e just refers to the event that has taken place, you can change it to anything you want. It just passes the event around to the various functions etc. that need to use it.
The false simply means that the event is not 'consumed', i.e. it can be used by other handlers if you have multiple handlers for the same event. So, yes, it is effectively the same as return false. (see my link below about bubbling)
See here for more on consuming events and bubbling.
First of all e is just an argument that you will receive in the function. You could also write something like this:
function evtHandler(){
console.log(arguments[0]);
}
Where arguments[0] is your given e. The handler function is called when the event is fired. Usually in the e argument you have an object with some info about how fire the event.
When you add an event handler, the last argument on that function is a boolean one, which indicates if the handle should or shouldn't bubble in the event handler's chain. It is not as you would return false, but if the event would be handled by other handlers also. If you want to return false or ignore the previous default handling you could call the preventDefault function inside the evtHandler.
P.S. Take care with event handlers because there are some problems with cross-browser compatibility;
if you are talking about e in clickLink(e), then i can say you can declare whatever parameter you want in a javascript function prototype,but when calling it you can provide parameters optionaly.and here in clickLink(e) you can pass a parameter for e or you can simply ignore it.and about the false in addEventHandler check this documentation also check this SO question .
for example if function FO is defined so:
function FO(e){
//function body here
}
then you can call it like this :
FO();
OR
FO("BAR");
How do I clear out anonymous functions that are set to trigger via a jQuery document.ready() call?
For example:
<script type="text/javascript">
//some code sets a doc ready callback
$(document).ready(function ()
{
alert('ready');
});
//my attempt to prevent the callback from happening
window.onload = null;
$(document).unbind("ready");
</script>
The alert happens regardless of my attempts to circumvent it. Is there any way to do this?
You'd probably get the most appropriate answer if you described what problem you're really trying to solve.
jQuery doesn't have a publicly documented way to undo or block document.ready() handlers. If you control the code, you can use a global variable and a conditional like this:
var skipReady = false;
$(document).ready(function ()
{
if (!skipReady) {
alert('ready');
}
});
// skip the document.ready code, if it hasn't already fired
skipReady = true;
Or, if you want to hack into jQuery a bit (beyond the documented interfaces), you can do this:
$(document).ready(function() {
alert("ready");
});
// stop the ready handler
$.isReady = true;
You can see this last one work here: http://jsfiddle.net/jfriend00/ZjH2k/. This works because jQuery uses the property: $.isReady to keep track of whether it has already fired the ready handlers or not. Setting it to true makes it think it has already fired them so it won't every do it again.
This works:
$(document).bind("ready", function () { alert("hey!"); });
$(document).unbind("ready");
Seems like a bug to me - all other events in jQuery are able to be unbound. Omitting this one is inconsistent.
Not a direct answer as to the omission, but here's some related info from jQuery docs:
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
There is also $(document).bind("ready", handler). This behaves similarly to the ready method but with one exception: If the ready event has already fired and you try to .bind("ready") the bound handler will not be executed. Ready handlers bound this way are executed after any bound by the other three methods above.
$(document).ready() is dependent on the onLoad event which is triggered by the browser meaning you can not prevent it from happening. If the alert() is determined by some condition then I would use an if/else statement to decide whether it is called.
Super old question, but came across the need to do this recently to prevent document.ready code I didn't control from running in certain instances. This can be achieved by proxying jQuery's ready function, rather like a test spy. The following will work:
var ready = $.prototype.ready;
// proxy the ready function
$.prototype.ready = function ( fn, allowed ) {
allowed = allowed || false;
if ( allowed ) {
ready.call( this, fn );
}
};
All calls to $( document ).ready will now be ignored. You can override this behaviour by passing true as the second argument: $( document ).ready( fn, true )
In this jsFiddle
am I trying to pass an argument to a function, but it doesn't receive the argument or it isn't executed.
Details
JQuery
$(document).ready(function() {
function addRemove(u) {
alert(u);
}
});
Any ideas what's wrong and how to fix it?
Your function only exists within the scope of the ready event handler, you need to move function addRemove outside of the ready function.
http://jsfiddle.net/EcCTx/2/
Your code was wrapped in an onload event by jsfiddle (drop-down menu on the left). So if you add a function it won't be global, but your onclick event calls a global function by the name addRemove.
You need to define your function outside of the $(document).ready().
I haven't tested it, but my guess is this: things inside of a function can't be accessed from outside of a function. For example,
$(document).ready(function() {
function addRemove(u) {
alert(u);
}
});
console.log(addRemove); // reference error or something similar
You should define addRemove function outside of $(document).ready.
the addRemove function must be outside of $(document).ready(function(){...});
In case Davin doesn't come back, here's the answer: jsFiddle defaults to wrapping your JS in the 'onLoad' method - and we can't allow that.
http://jsfiddle.net/nqbWe/
You had no defined function called addRemove in the Fiddle!
I've added this, and removed the inline javascript calls.
See this for better way of doing it:
http://jsfiddle.net/EcCTx/6/
There is nothing specifically calling that function. In the document ready part you have the function set up, but the anchor will not call that function by itself. In this instance it will only be called when someone clicks on that link.
You could give the link a class and data attribute and use those with jQuery to have something happen on page load.
I have a Javascript module the following Javascript:
EntryController = function$entry(args) {
MainView();
$('#target').click(function() {
alert('Handler called!');
});
}
MainView() has a callback that creates the #target button. Because of the callback the code will pick up and run through the rest of the code $('#target') ... before #target is created. If this is the case the event is never hooked up to the #target. If I put a breakpoint at $('#target') that'll give the callback enough time to return and build the #target, when I press play everything works as expected.
What's the best way to deal with this? I would like all events to take place in the controller so it can choose which view to send it to.
I was thinking about placing the entire $('#target').click ... inside MainView() and instead of alert('Handler called!'); I'd put a references to EntryController.TargetEventRaise(), but that started to look a bit like steady code. What's the best way to approach this?
You're looking for jQuery's live event handlers, which will handle an event on every element that matches the selector, no matter when the element was created.
For example:
$('#target').live('click', function() {
alert('Handler called!');
});
Alternatively, you could make the MainView function itself take a callback, and add the handler in the callback. You could then call the callback in MainView inside of its callback.