Use of Binding after Unbinding - javascript

I found a code as shown below.
Html code:
<div id="myButton">Click Here</div>
JQuery Code:
$("#myButton").unbind("click").bind("click",function(){
alert("Working")
});
What is the need of unbind("click") before binding the element?
It is also working if unbind is not used. like shown below
$("#myButton").bind("click",function(){
alert("Working")
});
Which one is best? what is the difference?

This only makes sure, that there is no other click event listener attached. So your handler will be the only handler acting upon clicking the #myButton
Edit: as #T.J. Crowder noted in the comments, unbind() will not affect handlers attached in different way than by calling bind().
It is also worth noting, that:
as of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements
(excerpt from the jQuery.unbind() doc). In fact, unbind() is implemented internally by the off() method).
Consider:
$("#myButton").bind('click', function () {
console.log('click 1');
});
$("#myButton").unbind('click').bind('click', function () {
console.log('click 2');
});
// When clicked, prints "click 2"
Versus:
$("#myButton").bind('click', function () {
console.log('click 1');
});
// note: no unbind here
$("#myButton").bind('click', function () {
console.log('click 2');
});
// When clicked, prints "clicked 1" followed by "clicked 2"

By unbinding "click" event on an element, you are actually removing all the onclick events associated with that element. i.e. if your html form's input field has an onclick event and it calls a function, it will be unbound. After an unbind, you are binding another click event which will call your function onclick of that element.

$("#myButton").unbind("click").bind("click",function(){
alert("Working")
});
jQuery bind() function is used to attach an event handler to elements, while the unbind() is used to detached an existing event handler from elements. please see a demo http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-bind-unbind-example.html

Without url of this html code , i'm not sure that #myButtonelement whether has other click handler attached ,but what is certain is unbind method remove all the handler on this element , i think the author only want to trigger one click event.
Also, you can see if there is other event handler on debug inspector of browser.
Hope this will help you.

Related

jQuery remove scroll listener after reach certain point [duplicate]

I have an input type="image". This acts like the cell notes in Microsoft Excel. If someone enters a number into the text box that this input-image is paired with, I setup an event handler for the input-image. Then when the user clicks the image, they get a little popup to add some notes to the data.
My problem is that when a user enters a zero into the text box, I need to disable the input-image's event handler. I have tried the following, but to no avail.
$('#myimage').click(function { return false; });
jQuery ≥ 1.7
With jQuery 1.7 onward the event API has been updated, .bind()/.unbind() are still available for backwards compatibility, but the preferred method is using the on()/off() functions. The below would now be,
$('#myimage').click(function() { return false; }); // Adds another click event
$('#myimage').off('click');
$('#myimage').on('click.mynamespace', function() { /* Do stuff */ });
$('#myimage').off('click.mynamespace');
jQuery < 1.7
In your example code you are simply adding another click event to the image, not overriding the previous one:
$('#myimage').click(function() { return false; }); // Adds another click event
Both click events will then get fired.
As people have said you can use unbind to remove all click events:
$('#myimage').unbind('click');
If you want to add a single event and then remove it (without removing any others that might have been added) then you can use event namespacing:
$('#myimage').bind('click.mynamespace', function() { /* Do stuff */ });
and to remove just your event:
$('#myimage').unbind('click.mynamespace');
This wasn't available when this question was answered, but you can also use the live() method to enable/disable events.
$('#myimage:not(.disabled)').live('click', myclickevent);
$('#mydisablebutton').click( function () { $('#myimage').addClass('disabled'); });
What will happen with this code is that when you click #mydisablebutton, it will add the class disabled to the #myimage element. This will make it so that the selector no longer matches the element and the event will not be fired until the 'disabled' class is removed making the .live() selector valid again.
This has other benefits by adding styling based on that class as well.
This can be done by using the unbind function.
$('#myimage').unbind('click');
You can add multiple event handlers to the same object and event in jquery. This means adding a new one doesn't replace the old ones.
There are several strategies for changing event handlers, such as event namespaces. There are some pages about this in the online docs.
Look at this question (that's how I learned of unbind). There is some useful description of these strategies in the answers.
How to read bound hover callback functions in jquery
If you want to respond to an event just one time, the following syntax should be really helpful:
$('.myLink').bind('click', function() {
//do some things
$(this).unbind('click', arguments.callee); //unbind *just this handler*
});
Using arguments.callee, we can ensure that the one specific anonymous-function handler is removed, and thus, have a single time handler for a given event. Hope this helps others.
maybe the unbind method will work for you
$("#myimage").unbind("click");
I had to set the event to null using the prop and the attr. I couldn't do it with one or the other. I also could not get .unbind to work. I am working on a TD element.
.prop("onclick", null).attr("onclick", null)
If event is attached this way, and the target is to be unattached:
$('#container').on('click','span',function(eo){
alert(1);
$(this).off(); //seams easy, but does not work
$('#container').off('click','span'); //clears click event for every span
$(this).on("click",function(){return false;}); //this works.
});​
You may be adding the onclick handler as inline markup:
<input id="addreport" type="button" value="Add New Report" onclick="openAdd()" />
If so, the jquery .off() or .unbind() won't work. You need to add the original event handler in jquery as well:
$("#addreport").on("click", "", function (e) {
openAdd();
});
Then the jquery has a reference to the event handler and can remove it:
$("#addreport").off("click")
VoidKing mentions this a little more obliquely in a comment above.
If you use $(document).on() to add a listener to a dynamically created element then you may have to use the following to remove it:
// add the listener
$(document).on('click','.element',function(){
// stuff
});
// remove the listener
$(document).off("click", ".element");
To remove ALL event-handlers, this is what worked for me:
To remove all event handlers mean to have the plain HTML structure without all the event handlers attached to the element and its child nodes. To do this, jQuery's clone() helped.
var original, clone;
// element with id my-div and its child nodes have some event-handlers
original = $('#my-div');
clone = original.clone();
//
original.replaceWith(clone);
With this, we'll have the clone in place of the original with no event-handlers on it.
Good Luck...
Updated for 2014
Using the latest version of jQuery, you're now able to unbind all events on a namespace by simply doing $( "#foo" ).off( ".myNamespace" );
Best way to remove inline onclick event is $(element).prop('onclick', null);
Thanks for the information. very helpful i used it for locking page interaction while in edit mode by another user. I used it in conjunction with ajaxComplete. Not necesarily the same behavior but somewhat similar.
function userPageLock(){
$("body").bind("ajaxComplete.lockpage", function(){
$("body").unbind("ajaxComplete.lockpage");
executePageLock();
});
};
function executePageLock(){
//do something
}
In case .on() method was previously used with particular selector, like in the following example:
$('body').on('click', '.dynamicTarget', function () {
// Code goes here
});
Both unbind() and .off() methods are not going to work.
However, .undelegate() method could be used to completely remove handler from the event for all elements which match the current selector:
$("body").undelegate(".dynamicTarget", "click")
I know this comes in late, but why not use plain JS to remove the event?
var myElement = document.getElementById("your_ID");
myElement.onclick = null;
or, if you use a named function as an event handler:
function eh(event){...}
var myElement = document.getElementById("your_ID");
myElement.addEventListener("click",eh); // add event handler
myElement.removeEventListener("click",eh); //remove it
This also works fine .Simple and easy.see http://jsfiddle.net/uZc8w/570/
$('#myimage').removeAttr("click");
if you set the onclick via html you need to removeAttr ($(this).removeAttr('onclick'))
if you set it via jquery (as the after the first click in my examples above) then you need to unbind($(this).unbind('click'))
All the approaches described did not work for me because I was adding the click event with on() to the document where the element was created at run-time:
$(document).on("click", ".button", function() {
doSomething();
});
My workaround:
As I could not unbind the ".button" class I just assigned another class to the button that had the same CSS styles. By doing so the live/on-event-handler ignored the click finally:
// prevent another click on the button by assigning another class
$(".button").attr("class","buttonOff");
Hope that helps.
Hope my below code explains all.
HTML:
(function($){
$("#btn_add").on("click",function(){
$("#btn_click").on("click",added_handler);
alert("Added new handler to button 1");
});
$("#btn_remove").on("click",function(){
$("#btn_click").off("click",added_handler);
alert("Removed new handler to button 1");
});
function fixed_handler(){
alert("Fixed handler");
}
function added_handler(){
alert("new handler");
}
$("#btn_click").on("click",fixed_handler);
$("#btn_fixed").on("click",fixed_handler);
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn_click">Button 1</button>
<button id="btn_add">Add Handler</button>
<button id="btn_remove">Remove Handler</button>
<button id="btn_fixed">Fixed Handler</button>
I had an interesting case relevant to this come up at work today where there was a scroll event handler for $(window).
// TO ELIMINATE THE RE-SELECTION AND
// RE-CREATION OF THE SAME OBJECT REDUNDANTLY IN THE FOLLOWING SNIPPETS
let $window = $(window);
$window.on('scroll', function() { .... });
But, to revoke that event handler, we can't just use
$window.off('scroll');
because there are likely other scroll event handlers on this very common target, and I'm not interested in hosing that other functionality (known or unknown) by turning off all of the scroll handlers.
My solution was to first abstract the handler functionality into a named function, and use that in the event listener setup.
function handleScrollingForXYZ() { ...... }
$window.on('scroll', handleScrollingForXYZ);
And then, conditionally, when we need to revoke that, I did this:
$window.off('scroll', $window, handleScrollingForXYZ);
The janky part is the 2nd parameter, which is redundantly selecting the original selector. But, the jquery documentation for .off() only provides one method signature for specifying the handler to remove, which requires this middle parameter to be
A selector which should match the one originally passed to .on() when attaching event handlers.
I haven't ventured to test it out with a null or '' as the 2nd parameter, but perhaps the redundant $window isn't necessary.

How to unbind and rebind an event based on selector change

This is more a learning piece for me around how event listeners bound to jQuery selectors are handled.
So say I have the following code:
<html>
<div class = "one">one</div>
<div class = "two">two</div>
</html>
<script>
$(".one").click(function() {
$(this).removeClass("one").addClass("two");
console.log("one");
})
$(".two").click(function() {
console.log("two");
})
</script>
On the first click of one, the selector is no longer valid (as the class is now two instead of one). However the event is still bound to this element. This element will also not fire the ".two" handler as this has already been bound.
What would be the easiest way to unbind a handler with the initial click and then rebind afterwards?
Bind the events on the document, no need to unbind and rebind the events.
$(document).on("click", ".one", function() {
$(this).removeClass("one").addClass("two");
console.log("one");
});
$(document).on("click", ".two", function() {
console.log("two");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="one">one</div>
<div class="two">two</div>
$(".one").unbind("click");
$(".one").bind("click", fn);
You can use unbind() to remove an event added with bind() (or binded like above)
https://jsfiddle.net/7yn7apte/ No re-binding
https://jsfiddle.net/7yn7apte/1/ Re-binding
Well, this answer your question. But, you'd better use on() and off() as bind() calls on() and unbind() calls off().
You can find a more exhaustive explanation here https://stackoverflow.com/a/9113835/6341631

Manually click a child link (and navigate) when clicking parent [duplicate]

Recently I found jQuery cannot trigger the native click event on an anchor tag when I'm clicking on other elements, the example below won't work:
html
<a class="js-a1" href="new.html" target="_blank">this is a link</a>
<a class="js-a2" href="another.html" target="_blank">this is another link</a>
javascript
$('.js-a1').click(function () {
$('.js-a2').click();
return false;
});
And here is the jsfiddle - 1. Click on the first link won't trigger native click on the second one.
After some searches, I found a solution and an explanation.
Solution
Use the native DOM element.
$('.js-a1').click(function () {
$('.js-a2').get(0).click();
return false;
});
And here is the jsfiddle - 2.
Explanation
I found a post on Learn jQuery: Triggering Event Handlers. It told me:
The .trigger() function cannot be used to mimic native browser events, such as clicking on a file input box or an anchor tag. This is because, there is no event handler attached using jQuery's event system that corresponds to these events.
Question
So here comes my question:
How to understand 'there is no event handler attached using jQuery's event system that corresponds to these events'?
Why is there not such corresponding event handler?
EDIT
I update my jsfiddles, it seems there's and error on the class name.
there is no event handler attached using jQuery's event system that corresponds to these events
This means, at this point of the learning material, no jQuery event handlers has been attached to these elements using .click(function() {} or .bind('click', function () {}), etc.
The no-argument .click() is used to trigger (.trigger('click')) a "click" event from jQuery's perspective, which will execute all "click" event handlers registered by jQuery using .click, .bind, .on, etc. This pseudo event won't be sent to the browser.
.trigger()
Execute all handlers and behaviors attached to the matched elements for the given event type.
Check the updated jsFiddle example, click on the two links to see the difference. Hope it helps.
First of all you need to prevent the default behaviour of link
$('.js-a1').click(function (e) {
e.preventDefault();
$('.js-a2').get(0).click();
return false;
});
And to trigger the click event you can also use .trigger('click') better way
And the event handler is used like this:
$(document).on('click', '.js-a1',function(){//code in here});
// here now .js-a1 is event handler
i think you forgot to read documentation.
Document says :
// Triggering a native browser event using the simulate plugin
$( ".js-a2" ).simulate( "click" );
Old question, but here's a nifty and simple solution:
You can basically "register" a native JS event with jQuery by assigning the DOM element's onEvent handler to be the native event. Ideally, we would check first to ensure the onEvent handler has not already been set.
For example, 'register' the native JS click event so it will be triggered by jQuery:
$('.js-a1').click(function (e) {
$('.js-a2').click();
e.preventDefault();
});
var trigger_element = $('.js-a2')[0]; // native DOM element
if (!trigger_element.onclick) {
trigger_element.onclick = trigger_element.click;
}
Here is a fiddle: http://jsfiddle.net/f9vkd/162/
You have to use $("selector").trigger('click')

jQuery click events overriding each other

I have the following jQuery:
$('.io-sidebar-section').click(function () {
console.log('Section Clicked');
$(this).next().fadeToggle('fast',function(){});
});
$('.io-sidebar-section-advanced-toggle').click(function(){
$(this).parent().next().children('.io-sidebar-link-advanced').fadeToggle('fast',function(){});
});
the advanced toggle is inside of a sidebar section. When I click on the advanced toggle, it executes the sidebar section click.
How can I seperate these two out?
You can use the stopPropagation method of the event object inside the click event handler for the child element:
$('.io-sidebar-section-advanced-toggle').click(function(e){
e.stopPropagation();
$(this).parent().next().children('.io-sidebar-link-advanced').fadeToggle('fast',function(){});
});
From the jQuery docs, here's what stopPropagation does:
Prevents the event from bubbling up the DOM tree, preventing any
parent handlers from being notified of the event.
As mentioned in the comments, if you prefer you can alternatively use return false in the event handler (in this particular case, as far as I can tell anyway - it will also cause preventDefault which may not be what you want to happen). My personal preference is to use stopPropagation but it's completely up to you.
You can avoid events bubbling up by using jQuery's bind function and preventBubble argument.
http://api.jquery.com/bind/

In jQuery, is there any way to only bind a click once?

I have an ajax app that will run functions on every interaction. I'd like to be able to run my setup function each time so all my setup code for that function remains encapsulated. However, binding elements more than once means that the handler will run more than once, which is obviously undesirable. Is there an elegant way in jQuery to call bind on an element more than once without the handler being called more than once?
User jQuery one function like Tom said, but unbind the handler each time before binding again. It helps to have the event handler assigned to a variable than using an anonymous function.
var handler = function(e) { // stuff };
$('#element').unbind('click', handler).one('click', handler);
//elsewhere
$('#element').unbind('click', handler).one('click', handler);
You can also do .unbind('click') to remove all click handlers attached to an element.
You could attach the event to document with the one() function:
$(document).one('click', function(e) {
// initialization here
});
Once run, this event handler is removed again so that it will not run again. However, if you need the initialization to run before the click event of some other element, we will have to think of something else. Using mousedown instead of click might work then, as the mousedown event is fired before the click event.
You can also use .off() if unbind doesn't do the trick. Make sure the selector and event given to .off exactly match the ones initially provided to .on():
$("div.selector").off("click", "a.another_selector");
$("div.selector").on("click", "a.another_selector", function(e){
This is what worked for me in resolving the same ajax reloading problem.
The answer from Chetan Sastry is what you want. Basically just call a $(element).unbind(event); before every event.
So if you have a function like loadAllButtonClicks() that contains all the
$(element).on("click", function (){});
methods for each button on your page, and you run that every time a button is clicked, this will obviously produce more than one event for each button. To solve this just add
$(element).unbind(event);
before every
$(element).on("click", function (){});
and it will unbind all events to that element, then add the one click event.

Categories