Reputation: 1282
I am doing something as shown bellow:
$("#btn1").click(function(){
$('<div></div>').appendTo('body');
});
It appends the division again and again when I click it, but what I want is when I click other button then there should be no effect of "btn1" means I want to clear the effect of first button after I click the second one.
How I can do this?
Upvotes: 2
Views: 1334
Reputation: 31
When you click first button it append's div tag into body
$("#btn1").click(function(){
$('div').appendTo('body');
});
then when you click second button it remove the div tag from the body and clears the previous one
$("#btn2").click(function(){
$('body').children("div").remove();
});
Upvotes: 2
Reputation: 47976
Well the simplest thing would be a flag:
var btn_is_active = true; // set flag's initial state
$( "#btn1" ).click( function(){
if ( btn_is_active ){ // only perform action if boolean is true
$( "<div></div>" ).appendTo( "body" );
}
});
$( "#btn2" ).click( function(){
// toggle the boolean value
btn_is_active = !btn_is_active;
});
In the above example, #btn2
controls the flag; Each time #btn2
is clicked, the btn_is_active
boolean is toggled from true to false and therefore enables/disables the functionality of #btn1
.
In order to clear whatever action #btn1
has already done, you'll have to be able to track all the '<div></div>'
elements that were added. For this you might want to give them a class attribute and then #btn2
could remove all the elements with that class attribute.
Upvotes: 1
Reputation: 70142
Why not add a class to the div that btn1
adds:
$("#btn1").click(function() {
$("<div class='new-div'></div>").appendTo('body');
});
Then you second button can remove it like so -
$("#btn2").click(function() {
$(".new-div").remove();
});
Upvotes: 2
Reputation: 39243
http://api.jquery.com/click/ says about .click
: "This method is a shortcut for .on( "click", handler )
". So you'll need .off
(http://api.jquery.com/off/) to clear the event handler.
Upvotes: 1
Reputation: 2078
i guess you want to disable the event of #btn1
on first click
$('#btn1").unbind('click');
this will clear the registered click event with that button
Upvotes: 1