jquery off not working - javascript

I can't unbind event use off.
I was trying to bind click event, then bind mouseleave event and callback unbind click, but not working.
el is dom create and append by script that's why I use document.on... el
so I tried below include commented code for test not working too.... do I miss understand something?
jquery-1.11.1.min.js
https://jsfiddle.net/70t6jtns/
var el = $('div')
$(document).on('click', el, function() {
console.log('oncli')
});
//$(document).on('mouseleave', el, function() {
//$(document).off('click', el, function() {
//console.log('offcli')
//});
//$(document).off('click', el);
el.off('click');
//});

First, on doesn't accept jQuery objects as the second argument, so $(document).on('click', el, function() {... doesn't make sense.
The main issue is that you're using event delegation in one case but expecting a directly-attached handler in the other case. You're attaching your click handler to document, but then trying to detach it from a specific element (el). You have to remove it from the same thing you attached it to.
If you want to attach the handler to el and detach it later, use el consistently as the target:
el.on("click", function() { ...
then
el.off("click");
If the handler has to be delegated, you'll want to be sure, again, that you're removing the same thing you're adding. So for instance,
$(document).on("click", "selector-for-the-element", function() { ...
then
$(document).off("click", "selector-for-the-element");

I was facing the same issue. Because i added the on listener on document and trying off with element. that was the issue in my case.

Related

Turning Off Specific Click Event

JSFIDDLE: http://jsfiddle.net/w55usyqk/
When you click the div there are two separate click events fired. They print out "click" and "clicked" respectively in the console log.
$("div").on("click", function() { console.log("click"); });
$("div").on("click", function() { console.log("clicked"); });
If you tap on the button it will remove both event declarations from the div object
$("button").on("click", function() { $("div").off("click"); });
However, what if I just needed to remove a single click event? Is this stored in some sort of event array where I could do something along the lines of $("div").off("click")[1]; or is it impossible to turn off one without turning off the other as well?
I did try looking for the answer if it's been posted before. I think this is one of those questions that's hard to word, so though there may be an answer out there, it's difficult to pin down.
You can use namespaces to easily do this. When you create your event handlers, add the namespace after the event. Ex:
$("div").on("click.namespace1", function() { console.log("click"); });
$("div").on("click.namespace2", function() { console.log("clicked"); });
then for your button, use the namespace of the event to remove:
// remove only the event for namespace2
$("button").on("click", function() { $("div").off(".namespace2"); });
jsFiddle example
Some more on namespaces for events:
An event name can be qualified by event namespaces that simplify
removing or triggering the event. For example, "click.myPlugin.simple"
defines both the myPlugin and simple namespaces for this particular
click event. A click event handler attached via that string could be
removed with .off("click.myPlugin") or .off("click.simple") without
disturbing other click handlers attached to the elements. Namespaces
are similar to CSS classes in that they are not hierarchical; only one
name needs to match. Namespaces beginning with an underscore are
reserved for jQuery's use.
Use named functions as event handlers, so you can then reference what handler you want to unbind:
function clicOne() {console.log("click");};
function clicTwo() {console.log("clicked");};
$("div").on("click", clickOne);
$("div").on("click", clicTwo);
$("button").on("click", function() { $("div").off("click", clickOne); });

Click function not working in .each() function

I want to use click() as eventhandler and that event handler is not working you can see code below
$('.ajax-close').click(function( event ){
event.preventDefault();
alert('hi');
$( '.ajax-live-on' ).removeClass('ajax-live-on');
});
I have used all the code to initialize the jquery no problem , all right. But this piece of code not working
Here is the jsBin link
http://jsbin.com/doxeravizo/1/edit?html,css,js,output
The $('.ajax-close') collection doesn't contain the elements taking that class after the binding.
Change
$('.ajax-close').click(function( event ){
to
$(document.body).on('click', '.ajax-close', function( event ){
You should also move that binding outside of the loop, there's no reason to do it at every iteration.
Note also that in order to have your span clickable, it must have some content.
Demonstration (I added the jQuery library to make the fiddle work)
I'm guessing that because you're using ajax, your .ajax-close is not created when the event listener is being created.
You're going to want to delegate your click function:
$(document).on('click', '.ajax-close', function(event) {
event.preventDefault();
alert('hi');
$('.ajax-live-on').removeClass('ajax-live-on');
});
This article will help, but just for reference, this bit in particular:
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
One option is to listen on the click event using a delegate, like so:
$(document).on('click', '.ajax-close', function( event ){
//your code
});
Another option might be to move your click listener inside the original click listener, which creates the "Close" button, while the reason the issue arises is that the click event on "ajax-close" is bound too soon (before the <span> is appended to the DOM even):
ajaxcontent.click(function(event) {
event.preventDefault();
$( '.ajax-live' ).addClass('ajax-live-on');
$( this ).after('<span class="ajax-close animated bounceInRight">Close</span>');
$('.ajaxshow').append().load(ajaxUrl);
$('.ajaxshow').addClass('animated bounceInUp');
// Move this section here, which was previously located below
$('.ajax-close').click(function( event ){
event.preventDefault();
alert('hi');
$( '.ajax-live' ).removeClass('ajax-live-on');
});
});
Make sure to include some content in your "ajax-close" span to be able to click it like the word "Close".
Add JQuery library to your HTML head :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
In your given link you are adding element dynamically, so need to use event delegate for dynamically created elements event binding.
$(document).on('click', '.ajax-close', function( event ){
//your code
});

How to remove an event handler passed as a property of an object in jQuery?

I'm using a plugin that I cannot modify directly, but I'd like to remove some event handlers from DOM elements that this plugin is attaching.
The plugin does this:
var openOnClick = function() {
$('#selector').on({
click: function(e) {
e.preventDefault();
plugin.showPanel($(this));
}
})
};
It later calls openOnClick();
I want to remove this event completely. I tried $('#selector').off('click'), but this does not work. I assume this is because it is not just a simple 'click' event attached to the #selector.
What are my options to get rid of this event?
Did you try an
e.stopPropagation()
or just an
return false;
in the body of your click handler function ?

Reattach a removed event handler doesn't work

I want to remove the click of an element when it is clicked (I'm using off() for this), and want to reattach the click when the element isn't clicked ('actived'). To indicate it is not clicked, I'm using a class named 'disabled'.
But when I remove, I cant add it again. It just doesn't attach the event again!
This is what I'm trying to do:
$('.my-element').on('click', function() {
$('.my-element').off('click');
});
var disabled = setInterval(function() {
if($('.my-element').hasClass('not-clicked')) {
$('.my-element').on();
}
}, 1000);
I'm using setInterval() to watch whether the element isn't clicked. If it isn't, it can be using on() again.
I have even tried to remove the event handler in the browser console:
$('.my-element').off();
But when I try to reattach the event handler...
$('.my-element').on();
It doesn't work, and will not repeat the behavior.
jQuery.on() doesn't remember removed events, but you can save the current events before removing them with:
var handlers;
$('.my-element').on('click', function() {
handlers = $.extend(true, {}, $._data( this, "events" ));
$('.my-element').off('click');
});
and then attach with:
$(".my-element").on("click", handlers.click[0].handler);
Using on and off without any parameters has no effect. Ideally you should pass the name of the event and it's handler to those methods.
var handler = function() {
// ...
}
$('.my-element').on('click.namespace', handler);
// ...
$('.my-element').off('click.namespace', handler);
If the handler should be called only once you could also consider using the one method. Also using setIntevarl here is a bad idea. You should bind the handler right after adding the class. In this case I'd suggest using event delegation technique:
$('#aStaticParent').on('click', '.my-element.not-clicked', function() {
// the handler is called only if the element has `not-clicked` className
$(this).removeClass('not-clicked');
});

JQuery bind event after adding element dynamic

I have an issue after adding a element dynamically it doesn't have the click event, so i have the following:
$(".myclass > li").click(function () {
...
});
so basically when i click on LI element something should happen and it works.
But when i add a new LI element to myclass which is UL element, this newly added element doesn't call this function.
My question how do i rebind or bind this newly element to this function ..?
Because the other elements when i click on them they work, but only the new element doesn't ... i suppose it is that the binding happens on postback or somethnig but in my case there is no postback :/
You need to use Event Delegation. You have to use .on() using delegated-events approach.
i.e.
$(document).on('event','selector',callback_function)
In your case
$(document).on('click', '.myclass > li', function () {
...
});
OR if you want to apply to ALL list items:
$(".myclass").on('click', '> li', function () {
...
});
need to use event delegation to support dynamic elements
$(".myclass").on('click', '> li' function () {
...
});
Since the element is added after you bind the event, it doesn't have the handler attached and the bind function doesn't listen for any new elements that might be added.
Thus, you need to use event delegation. When an event triggers, it will bubble up all the way to the parent document. Using the jQuery .on() function you can listen for events that have bubbled up from their target.
In your case, you should use the following:
$(parent).on("click", "li", function() { ... });
The above will listen for click events that occur on li elements and bubble up to parent. Inside the event handler this will refer to the li element on which the event triggered. In case you don't know the parent, you can listen on document.
You can learn more about the .on() function here.

Categories