Revising code of jQuery.reveal plugin (http://www.zurb.com/playground/reveal-modal-plugin) and trying to understand how it handles the modal behaviour, I see that it binds the closeModal function (that closes the popup) to the event 'click.modalEvent'.
But I can't find any information about this event, I don't know if it belongs to javascript itself or if it's part of jQuery
If the event type contains a period, it means it is namespaced and it will come in handy when you want to unbind the event. Without event namespaces, the only way to unbind a function is to unbind all events from the element, or to keep a reference to the function itself.
With namespaces, you can easily remove inline functions as well.
Assume we bind two events:
$('#element').bind('click.myEvents', function(){ /* inline function */ });
$('#element').bind('keypress.myEvents', function(){ /* inline function */ });
You can easily unbind the event using the namespace without having to create a named function:
$('#element').unbind('click.myEvents');
You can also unbind all events under the same namespace at once:
// This will get rid of both the click and keypress handlers.
$('#element').unbind('.myEvents');
For more information, see the jQuery documentation page for unbind().
it's probably custom event.
See this post.
Related
I have a jQuery plugin, and inside of it I have an init function. Inside of this init-function I attach some events:
(function ( $ ) {
$.fn.gallery = function(options) {
var init = function(self) {
var main += '<input id="gallery-search">';
//click event for the filter checkboxes
$("body").on('click', self.selector+" .gallery-filter-checkbox",function(event) {
self.data(filter( self ));
});
//capture input in the search box
$('#gallery-search').keyup(function(){
console.log('test');
});
self.html(output);
}
}( jQuery ));
}
The first one works just fine, but the second one doesn't work at all. I have tested it outside of the plugin scope and it works just fine so there is no syntax error, but probably an error in the way I try and attach the event?
Since #gallery-search is created dynamically, you can use delegated event handler:
$(document).on('keyup', '#gallery-search', function() { ... });
If self represents static HTML element at page, you can use a little better (for performance) version:
self.on('keyup', '#gallery-search', function() { ... });
Or you can place event handler in code after element's insertion, if HTML will not be modified later:
self.html(output);
$('#gallery-search').keyup(function()
{
console.log('test');
});
keyup() is a shortcut for bind('keyup',callback) which will register some event handler on the elements that are already present in the DOM (not necessarily rendered). It won't work if the element is not present in DOM when it's defined. To do that you need to use delegate() which will attach some handler on an element which is currently available or in might be available in future.
From jQuery 1.7 onwards, it's recommended to use on() as it combines the functionality of bind / delegate / live.
on() can be used in two ways
$(selector).on('event',callback);
$(parentSelector).on('event','someChildSelector', callback);
First one is direct handler and second one is called delegated handler.
If you're using first one to register event handlers, you've to make sure that element is present in the DOM at the time of registering just like bind(). So if you're adding new elements, you have to attach that handler again.
If you're using the second way, you don't have to worry about registering the handler again
$(document).on('click','.row',callback);
As document is always available, you callback will be registered as click handler for all the existing rows and any new row that you might add in the future.
I strongly recommend you read the Direct and delegated events section here. They even explain about the performance benefits.
Now that you know how it works, you can fix it using on() either as a direct handler or as a delegated handler.
EDIT : It's better to use closest static parent than document/body when using on() to register delegated handlers. Thanks to Regent for suggesting that :)
$('closestStaticParent').on('keyup','#gallery-search',function(){
console.log('test');
});
I ask a specific question about jquery scroll events, but it seems like the answer could have implications to jquery events in general (which I am also interested in knowing).
Suppose that jquery plugin A (e.g., jquery.scrollspy.js) binds a scroll event to $(window)
Now say that some site imports plugin A, but it also has its own custom javascript file B, which binds another .scroll() event to $(window).
Later on, javascript file B wants to unbind its own scroll event, and leave jquery plugin A intact. How is this done?
and...
Is this method universal to all jquery events?
jQuery recommends to use on and off instead of bind and unbind.
function scrollEvent()
{
}
$(window).on('scroll',scrollEvent);
$(window).off('scroll',scrollEvent);
http://api.jquery.com/on/
Best to use jQuery's .on() and .off() methods rather than .bind() and .unbind().
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.
You can also namespace the event by adding a custom suffix to the event name. You can then access that particular event later (to unbind for example)...
$(window).on('scroll.myscroll', function () {
// do something on scroll event
});
an den...
$(window).off('scroll.myscroll'); // unbind my namespaced scroll event
See https://css-tricks.com/namespaced-events-jquery/
This is easy. Didn't do enough research before asking question:
var fileBScrollEvent = function() {
// do something on scroll event
}
$(window).bind('scroll',fileBScrollEvent);
...later on in the code...
$(window).unbind('scroll',fileBScrollEvent);
Suppose i have a component, inputType="text" with id ="cmp";
In a js file ,
$("input[type='text']").bind('keypress', function(e) {
//Case 1
});
In my jsp file,
$("#cmp").keypress(function() {
//Case 2
});
Now I need to remove only one keypress event.
Is it possible to remove the keypress event for id ="cmp" that is registered from js file.
But we should not not remove event that is registered from jsp file.
Note:
According to my requirement, I cannot change .js file.
you can use off of jquery method to remove events Jquery OFf
The off() method removes event handlers that were attached with .on().
See the discussion of delegated and directly bound events on that page
for more information. Specific event handlers can be removed on
elements by providing combinations of event names, namespaces,
selectors, or handler function names. When multiple filtering
arguments are given, all of the arguments provided must match for the
event handler to be removed.
$('#cmp').off('keypress');
use off()
off: Remove an event handler.
$('#cmp').off('keypress');
You will want to use either .unbind() or .off() (jQuery 1.7+) depending on how the event was originally attached and what version of jQuery you are using.
// Prior to jQuery 1.7
$("#cmp").unbind("keypress");
// jQuery 1.7+
$("#cmp").off("keypress");
If you can modify the original location where you are binding the event handler, you might also be able to use event namespaces to remove only a specifically named event.
// Original binding
$("#cmp").on("keypress.someName", function() {
...
});
// Unbinding
$("#cmp").off("keypress.someName");
EXAMPLE
this code in book jQuery in action page 131
i don't understand
.trigger('adjustName');
what is adjustName
and Simple explanation for trigger()
thanks :)
$('#addFilterButton').click( function() {
var filterItem = $('<div>')
.addClass('filterItem')
.appendTo('#filterPane')
.data('suffix','.' + (filterCount++));
$('div.template.filterChooser')
.children().clone().appendTo(filterItem)
.trigger('adjustName');
});
It is a string, the name of a custom event you defined.
E.g. it would trigger the event handler bound by:
el.bind('adjustName', function(){...});
For more information I suggest to have a look at the documentation:
Any event handlers attached with .bind() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user.
Without knowing the context of the code, I would say that calling .trigger() here has no effect, as it is called on the cloneed elements and the event handlers are only cloned if true is passed to clone.
Maybe the original jQuery manual could be helpful?
Description: Execute all handlers and
behaviors attached to the matched
elements for the given event type.
It allows you to trigger, or run, an event. For instance if you wanted the code to mimic the clicking of a button, you could write....
$("#myButton").trigger('click');
This would then run exactly as if you had clicked the button yourself.
'adjustName' is a custom event. So the trigger function is running that custom event. The custom event is assigned using the jQuery bind function.
$("#someElement").bind('adjustName', function() {/* Some Code */});
You might create a customer event for clarity. Perhaps your application opens a document, so you might want an event called 'openDocument' and 'closeDocument' assigned to the element containing the document.
I have a site that uses AJAX to navigate. I have two pages that I use a click and drag feature using:
$(".myDragArea").mousedown(function(){
do stuff...
mouseDrag = true; // mouseDrag is global.
});
$("body").mousemove(function(){
if (mouseDrag) {
do stuff...
}
});
$("body").mouseup(function(){
if (mouseDrag) {
do stuff...
mouseDrag = false;
}
});
I just type that out, so excuse any incidental syntax errors. Two parts of the site use almost identical code, with the only difference being what is inside the $("body").mouseup() function. However, if I access the first part, then navigate to the second part, the code that runs on mouseup doesn't change. I have stepped through the code with Firebug, and no errors or thrown when $("body").mouseup() is run when the second part loads.
So, why doesn't the event handler change when I run $("body").mouseup() the second time?
Using $("body").mouseup( ... ) will add an event handler for the body that is triggered at mouseup.
If you want to add another event handler that would conflict with current event handler(s) then you must first remove the current conflicting event handler(s).
You have 4 options to do this with .unbind(). I'll list them from the least precise to the most precise options:
Nuclear option - Remove all event handlers from the body
$("body").unbind();
This is pretty crude. Let's try to improve.
The elephant gun - Remove all mouseup event handlers from the body
$("body").unbind('mouseup');
This is a little better, but we can still be more precise.
The surgeon's scalpel - Remove one specific event handler from the body
$("body").unbind('mouseup', myMouseUpV1);
Of course for this version you must set a variable to your event handler. In your case this would look something like:
myMouseUpV1 = function(){
if (mouseDrag) {
do stuff...
mouseDrag = false;
}
}
$("body").mouseup(myMouseUpV1);
$("body").unbind('mouseup', myMouseUpV1);
$("body").mouseup(myMouseUpV2); // where you've defined V2 somewhere
Scalpel with anesthesia (ok, the analogy's wearing thin) - You can create namespaces for the event handlers you bind and unbind. You can use this technique to bind and unbind either anonymous functions or references to functions. For namespaces, you have to use the .bind() method directly instead of one of the shortcuts ( like .mouseover() ).
To create a namespace:
$("body").bind('mouseup.mySpace', function() { ... });
or
$("body").bind('mouseup.mySpace', myHandler);
Then to unbind either of the previous examples, you would use:
$("body").unbind('mouseup.mySpace');
You can unbind multiple namespaced handlers at once by chaining them:
$("body").unbind('mouseup.mySpace1.mySpace2.yourSpace');
Finally, you can unbind all event handlers in a namespace irrespective of the event type!
$("body").unbind('.mySpace')
You cannot do this with a simple reference to a handler. $("body").unbind(myHandler) will not work, since with a simple reference to a handler you must specify the event type ( $("body").unbind('mouseup', myHandler) )!
PS: You can also unbind an event from within itself using .unbind(event). This could be useful if you want to trigger an event handler only a limited number of times.
var timesClicked = 0;
$('input').bind('click', function(event) {
alert('Moar Cheezburgerz!');
timesClicked++;
if (timesClicked >= 2) {
$('input').unbind(event);
$('input').val("NO MOAR!");
}
});
Calling $("body").mouseup(function) will add an event handler.
You need to remove the existing handler by writing $("body").unbind('mouseup');.
jQUery doesn't "replace" event handlers when you wire up handlers.
If you're using Ajax to navigate, and not refreshing the overall DOM (i.e. not creating an entirely new body element on each request), then executing a new line like:
$("body").mouseup(function(){
is just going to add an additional handler. Your first handler will still exist.
You'll need to specifically remove any handlers by calling
$("body").unbind("mouseUp");