removeeventlistner not working on button click - javascript

document.getElementById('divv').addEventListener("click",func)
function func(a){
alert("oooo");
}
function abc(){
document.getElementById('divv').removeEventListener("click",function(){func()});
}
<div id="divv">This is vivek</div>
<button onclick="abc()">Remove</button>
I have a button and I want to remove the onclick event on a div after I click on the button.

Just like that:
document.getElementById('divv').removeEventListener("click", func);
See the explanation about removeEventListener
document.getElementById('divv').addEventListener("click", func)
function func(a) {
alert("oooo");
}
function abc() {
document.getElementById('divv').removeEventListener("click", func);
}
<div id="divv">This is vivek</div>
<button onclick="abc()">Remove</button>

You are not adding and removing the same function, and that is why it doesn't work.
You are adding like this: .addEventListener("click", func")
And you are removing like this: .removeEventListener("click", function(){func()})
func and function(){func()} do not refer to the same function, even though they have the same result, when called.
You need to remove exactly the same way as you remove; otherwise removing won't "find" the original function you added:
function abc(){
document.getElementById('divv').removeEventListener("click",func);
}

Related

jQuery 3.x .off() after .on()

I simply used .off() method after .on() method for .click() method.
I'm really confused why click() event fires!
$('span').on('click', function () { $('p').text("You Clicked!") });
$('span').off('click', function () {
$('p').text("Ha Ha Ha!") });
span{
background-color:#ac0;
padding:5px;
cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<span>Click Me!</span>
<p>*****</p>
You're trying to remove a different handler function than was originally assigned.
Instead, create a reference to the function and add/remove it by that reference:
var clickHandler = function () { $('p').text("You Clicked!") };
$('span').on('click', clickHandler);
$('span').off('click', clickHandler);
You've misunderstood what the function is for at the end of the off() method. It isn't a callback, it's an event handler.
That function is supposed to be the same event handler function as the one you set initially. This is done this way so that you can remove an individual click handler.
function handlerA(e) {
console.log('heard by A');
}
function handlerB(e) {
console.log('heard by B');
}
// add both handlers to click events
$('span').on('click', handlerA);
$('span').on('click', handlerB);
// remove the first click event only, leaving the second
$('span').off('click', handlerA);
The above would only log heard by B when clicked.
To remove all click handlers, you need to omit the function entirely.
$('span').off('click');

Perform click event for only one button under a CSS class

I have some JavaScript to execute logic i.e. doSomething() when a button is clicked. I know the class of the buttons, but there are multiple buttons on the page with this same class. The problem with my code below is that the doSomething() function is executed once for every button on the page when I only want it to execute one time only.
var myButtonClass = $(".my-button-class");
if (myButtonClass) {
myButtonClass.click(function (event) {
if (someCondition) {
doSomething();
}
});
}
I know it would be better to select by button div, but the button div names all vary based on how many there are (i.e. #my-button-div1, #my-button-div2, etc.) and the number of buttons is indefinite.
Is there a way to only do this event once? I don't care which button in the class happens to be clicked, I just need the event to fire once and then it's done.
UPDATE: To be clear, I still want the logic to execute if the user clicks another button on the page again, so I don't want to completely unbind the event. I just don't want it to execute once for every button on the page. For example, let's say I have 4 buttons. Right now it's doing something like the following when just one button is clicked:
alert!
alert!
alert!
alert!
I only need ONE of those alerts. Basically, whenever the user clicks any of the buttons on the page, I need it to go alert! only once per click.
Revised so that you don't have weird if statements, and allows for other click handlers to happily work if binded elsewhere
UPDATED:
var clickHandler = function handleClick(event) {
doSomething();
}
var bindClicks = true;
function doSomething() {
alert('alert!');
}
function doTheBinding() {
if (bindClicks) {
$('.my-button-class').on('click', clickHandler);
bindClicks = false;
}
}
// as many times as you want but it will still call once
doTheBinding();
doTheBinding();
doTheBinding();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="my-button-class">Click me!</button>
<button class="my-button-class">Click me!</button>
<button class="my-button-class">Click me!</button>
<button class="my-button-class">Click me!</button>
You can use on() and off() to bind and unbind the event on an element respectively.
$('.my-button-class').on('click', function (event) {
if (someCondition) {
doSomething();
// Unbind the event on all the elements having the class
$('.my-button-class').off('click');
// To unbind the event on only the clicked element
// $(this).off('click');
}
});
Sidenote: if (myButtonClass) { will always evaluate to true. jQuery returns an object even when the element is not found and an object is always truthy. To check if an element exists in DOM, use length property on the jQuery object $('someSelector').length > 0.
If you give the handler a local boolean variable that is protected with a closure, you can create a function that will execute only once. See this SO answer.
Run the code snippet below to see it in action.
$(".my-button-class").click(function() {
var executed = false;
return function() {
if (!executed) {
executed = true;
doSomething();
}
};
}());
function doSomething() {
alert("You should only see me once!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="my-button-class">Click me!</button>
<button class="my-button-class">No click me!</button>
UPDATE: To address a different issue of the click event getting bound more than once. Just do a similar thing with:
var bind = function() {
var bound = false;
return function() {
if (!bound) {
bound = true;
$(".my-button-class").click(function() {
if (someCondition)
doSomething();
});
}
};
}();
bind();
bind(); // won't execute second time
var someCondition = true;
function doSomething() {
$("#output").append("<br>alert!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="my-button-class">Click me!</button>
<button class="my-button-class">No click me!</button>
<span id="output"></span>

Event handler sequence in jQuery

I'm dynamically binding event to a text element. This is my code:
<input type="text" id="myTxt" />
<script type="text/javascript">
function attachEvent1(element){
element.keyup(function(){
console.log("Event:"+event.keyCode);
});
}
function attachEvent2(element){
element.keyup(function(){
console.log("Value:"+this.value);
});
}
attachEvent1($('#myTxt'));
attachEvent2($('#myTxt'));
</script>
What I need it, I want the second event handler (attched by attachEvent2) to get called first, even if it is binded after attachEvent1.
Is it possible in jQuery?
What about something like this:
function handler1()
{
console.log("Event:"+event.keyCode);
}
function handler2()
{
console.log("Value:"+this.value);
}
function attachEvent1(element)
{
element.keyup(handler1);
}
function attachEvent2(element)
{
element.unbind('keyup', handler1);
element.keyup(handler2);
element.bind('keyup', handler1);
}
attachEvent1($('#myTxt'));
attachEvent2($('#myTxt'));
If you want something fancier, you could keep a list of the handlers, and do the rebinding in a loop, etc. but this basic idea of re-binding the events, has the desired effect.

How to get the id of a button that fired a function?

I have a button
<button onclick="DeletaItem('template','1234')" id="btn">Deletar_func</button>
And the function
function DeletaItem(tipo,id_cripto){
alert(tipo+id_cripto);
alert($(this).attr('id'));
}
Why the second alert is undefined?
The second alert is undefined because this does not refer to the button, it actually refers to the window object.
You need to either send this to the function, change the onclick to the following:
onclick="DeletaItem(this, 'template', '1234')"
and also change the function as follows:
function DeletaItem(button, tipo, id_cripto) {
alert(tipo + id_cripto);
alert(button.id);
}
or leave the onclick as it is and use event.target within the function instead of this.
function DeletaItem(tipo, id_cripto) {
alert(tipo + id_cripto);
alert(event.target.id);
}
try this:
$('#btn').click(function(){
alert(this.id);
});
OR
<button onclick="DeletaItem(this,'template','1234')" id="btn">Deletar_func</button>
function DeletaItem(obj,tipo,id_cripto){
alert(tipo+id_cripto);
alert($(obj).attr('id'));
alert(obj.id);
// alert(this); if uncomment this, you will see it is eqaul window object
}
when function called with onclick attribute, it's don't became an object like first one, so you can't use this; here this is window objectm but in first one, jQuery object will be passed

jQuery unbind click event function and re-attach depending on situation

The code below I use to create a sliding menu. I need to know how to unbind the function attached to the click event and re-attach it some other time. (using jQuery 1.7.2)
$(document).ready(function(){
$('.section').hide();
$('.header').click(function(){
if($(this).next('.section').is(':visible'))
{
$('.section:visible').slideUp()
$('.arrows:visible').attr("src","right.gif")
}
else
{
$('.section').slideUp();
$(this).next('.section').slideToggle();
$(this).find('.arrows').attr("src","down.gif")
});
});
The code below is what I have so far
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').unbind('click');
}
else
{
//else re-attach functionality?
}
});
Thanks
Simply make a named function. You can go low tech here and back to basics to unbind and reattach specific events.
function doStuff()
{
if($(this).,next('.section').is(':visible'))
...
}
$('.header').on('click', doStuff);
$('.header').off('click', doStuff);
Instead of unbind and re-bind, I suggest you to add a simple class to .header and check for the class in the click handler. See below,
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').addClass('dontClick');
} else {
$('.header').removeClass('dontClick');
}
});
And in your .header click handler,
$('.header').click(function(){
if ($(this).hasClass('dontClick')) {
return false;
}
//rest of your code
If you insist on having a unbind and bind, then you can move the handler to a function and unbind/bind the function any number of time..
You can try something like this.
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').addClass('clickDisabled');
}
else
{
$('.header').removeClass('clickDisabled');
}
});
And then in the click handler check for this class.
$(document).ready(function(){
$('.section').hide();
$('.header').click(function(){
if(!$(this).hasClass('clickDisabled')){
...
...
}
});
});
Why not make that top section a function, and then call it in your else statement?
You could try setting a variable as a flag. var canClick = ($('#formVersion').val() != 'Print'); Then in the click handler for your .header elements check to see if canClick is true before executing your code.
If you still want to remove the handler you can assign the events object to a variable. var eventObj = #('.header').data('events'); That will give you an object with all the handlers assigned to that object. To reassign the click event it would be like $('.header').bind('click', eventObj.click[0]);
After trying so hard with bind, unbind, on, off, click, attr, removeAttr, prop I made it work.
So, I have the following scenario: In my html i have NOT attached any inline onclick handlers.
Then in my Javascript i used the following to add an inline onclick handler:
$(element).attr('onclick','myFunction()');
To remove this at a later point from Javascript I used the following:
$(element).prop('onclick',null);
This is the way it worked for me to bind and unbind click events dinamically in Javascript. Remember NOT to insert any inline onclick handler in your elements.
You could put all the code under the .click in a separated function
function headerClick(){
if($(this).next('.section').is(':visible'))
{
$('.section:visible').slideUp()
$('.arrows:visible').attr("src","right.gif")
}
else
{
$('.section').slideUp();
$(this).next('.section').slideToggle();
$(this).find('.arrows').attr("src","down.gif")
}
}
and then bind it like this:
$(document).ready(function(){
$('.section').hide();
$('.header').click(headerClick);
});
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').unbind('click');
}
else
{
$('.header').click(headerClick);
}
});

Categories

Resources