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
Related
I see how you might do this with an onclick event: How do you override inline onclick event?
However there is an event which seems to be bound to a specific HTML element that I would like to remove/nullify.
Here is how it is bound with jQuery:
$('.play-control').bind('click', function(evt){
player.play();
});
Using the SE link I provided above does not "disassociate" the original binding. Seems to only work with onclick events.
How then would I "unbind" an event binding in Javascript (or jQuery)?
You can unbind all click handlers hooked up with jQuery using unbind or, with more up-to-date versions of jQuery, off:
$('.play-control').unbind('click');
// or
$('.play-control').off('click');
But unless you can change that code hooking up that handler, you can't unhook just that specific one without delving into jQuery internal data structures which can change without notice between dot releases.
If you can change that code, here are two ways you could target just that handler:
1. Use a named function:
Hooking it up:
function playClick(evt){
player.play();
}
$('.play-control').on('click', playClick); // Or use `bind`
Unhooking it:
$('.play-control').off('click', playClick); // Or use `unbind`
2. Use an "event namespace":
Hooking it up:
$('.play-control').on('click.play', function(evt){ // Or use `bind`
player.play();
});
Unhooking it:
$('.play-control').off('click.play'); // Or use `unbind`
Note the .play added to click.
More in the documentation: on, off
Event handlers attached with .bind() can be removed with .unbind().
(As of jQuery 1.7, the .on() and .off() methods are preferred to
attach and remove event handlers on elements.) In the simplest case,
with no arguments, .unbind() removes all handlers attached to the
elements: http://api.jquery.com/unbind/
According to Jquery, use of off and on is preferred
$(document).bind('click', '.play-control', function(evt){
player.play();
})
$('.play-control').off('click');
My understanding is that when using the unbind and off jQuery methods, I should be able to remove an event handler from an element as follows
The textbox created in the view, with an onkeypress event handler applied
#Html.TextBoxFor(Function(m) m.sometext, New With {.onkeypress = "eventhandler();", .id = "theID"}
The JavaScript which is trying to remove the event
function eventhandler()
{
alert("should only hit once");
// this doesnt unbind the event
$("#theID").unbind("onkeypress");
// Nor does
$("#theID").off();
//???
}
My thinking could be that the unbind only works with bind and the off only works when on is used. I say this as the jQuery API website states
The .off() method removes event handlers that were attached with .on()
If this is the case, can I not apply the handler in the view at all?
I'd like to add I want to do this in the view and I want to apply a unique ID which is from the ViewModel
Any help would be helpful
Thanks
You can use either removeAttr()
$('#theID').removeAttr('onkeypress');
or set the event handler to null
$('#theID'')[0].onkeypress = null;
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');
});
Currently with jQuery when I need to do something when a Click occurs I will do it like this...
$(".close-box").click( function() {
MoneyBox.closeBox();
return false;
});
I was looking at some code someone else has on a project and they do it like this...
$(".close-box").live("click", function () {
MoneyBox.closeBox();
return false;
});
Notice it seems to do the same thing as far as I can tell except they are using the live() function which is now Deprecated and jQuery docs say to use on() instead but either way why use live/on() instead of my first example?
Because you might have a dynamically generated elements (for example coming from an AJAX call), you might want to have the same click handler that was previously bound to the same element selector, you then "delegate" the click event using on() with selector argument
To demonstrate:
http://jsfiddle.net/AJRw3/
on() can also be synonymous with click() if you don't have a selector specified:
$('.elementClass').click(function() { // code
});
is synonymous with
$('.elementClass').on('click', function() { // code
});
In the sense that it only add the handler one time to all elements with class elementClass. If you have a new elementClass coming from, for example $('<div class="elementClass" />'), the handler won't be bound on that new element, you need to do:
$('#container').on('click', '.elementClass', function() { // code
});
Assuming #container is .elementClass's ancestor
There are a lot of answers, each touching on a few points - hopefully this can give you your answer, with a good explanation of what's what and how to use it.
Using click() is an alias to bind('click' ...). Using bind() takes the DOM as it is when the event listener is being set up and binds the function to each of the matching elements in the DOM. That is to say if you use $('a').click(...) you will bind the function supplied to the click event of every anchor tag in the DOM found when that code runs.
Using live() was the old way in jQuery; it was used to bind events just like bind() does, but it doesn't just bind them to elements in the DOM when the code runs - it also listens to changes in the DOM and will bind events to any future-matched elements as well. This is useful if you're doing DOM manipulation and you need an event to exist on some elements that may get removed/updated/added to the DOM later but don't exist when the DOM is first loaded.
The reason that live() is now depreciated is because it was poorly implemented. In order to use live(), you had to be able to select at least one element in the DOM initially (I believe). It also caused a copy of the function to run to be bound to each element - and if you have 1000 elements, that's a lot of copied functions.
The creation of the on() function was to overcome those problems. It lets you bind a single event listener to an object that will not change in the DOM (so you can't use on() on an element that will be removed/added to the DOM later - bind it to a parent object), and simply apply an element "filter" so that the function is only run when it is bubbled up to an element that matches the selector. This means you have just one function that exists (not a bunch of copies) bound to a single element - a much better approach to adding "live" events in the DOM.
... and that is what the differences are, and why each function exists and why live() is depreciated.
$("a").live() --> It will apply to all <a>, even if it is created after this is called.
$("a").click() --> It will only apply to all <a> before this is called. (This is a shortcut of bind(), and on() in 1.7)
$("a").on() --> Provides all functionality required for attaching event handlers. (Newest in jQuery 1.7)
Quotes:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().This method provides a means to attach delegated event handlers to the document element of a page, which simplifies the use of event handlers when content is dynamically added to a page. See the discussion of direct versus delegated events in the .on() method for more information.
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.
For earlier versions, the .bind() method is used for attaching an event handler directly to elements.
click() is a shortcut to the non delegation method of on(). So:
$(".close-box").click() === $(".close-box").on('click')
To delegate events with on(), ie. in dynamic created objects you can do:
$(document).on('click', '.close-box') // Same as $('.close-box').live()
But, on() introduces delegation in any static element, not just document as live() does, so:
$("#closestStaticElement").on('click', '.close-box')
You should read up on the difference between live and bind.
In a nutshell, live uses event delegation, allowing you to bind to elements that exist now and in the future.
In contrast, handlers attached via bind (and its shortcuts, like click) attach handlers directly to the DOM elements matching the selector, and therefore are only bound to elements that exist now.
A consequence of live's flexibility is decreased performance, so only use it when you need the functionality it provides.
$el.click(fn) is a shortcut for $el.on('click', fn)
See http://api.jquery.com/click/ and http://api.jquery.com/on/ for more info.
When you need to bind some event handlers to dynamically added elements you have to use live (deprecated) or on make the it working. Simply $('element').click(...); won't work on any dynamically added element in to the DOM.
More on The Difference Between jQuery’s .bind(), .live(), and .delegate().
$.click() is merely a shortcut for either bind or on. From jQuery docs:
In the first two variations, this method is a shortcut for .bind("click", handler), as well as for .on("click", handler) as of jQuery 1.7. In the third variation, when .click() is called without arguments, it is a shortcut for .trigger("click").
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. The click() method binds an event handler to the "click" JavaScript event, or triggers that event on an element.
In the plain .click(... if the target of the selector changes on the fly (e.g via some ajax response) then you'd need to assign the behavior again.
The .on(... is very new (jQuery 1.7) and it can cover the live scenario using delegated events which is a faster way to attach behavior anyway.
In on method, event handler is attached to the parent element instead of target.
example: $(document).on("click", ".className", function(){});
In above example, click event handler is attached to document.
And it uses event bubbling to know whether someone clicked on the target element.
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.