Reputation: 461
I am unbinding the click event of a button on the same button click. I want to bind the above button click again on some other button click. But it is not working.
$("#showSelection").bind("click", function () {
alert("in");
//unbinding the button click
$('#showSelection').unbind('click');
});
$("#kendowindow").click(function(){
alert("in2");
//want to bind the click event again but not working
$('#showSelection').bind('click');
});
Upvotes: 0
Views: 2421
Reputation: 24638
You can use a named function as follows:
function bindUnbind() {
console.log("in");
//unbinding the button click
$(this).unbind('click');
}
$("#showSelection").bind("click",bindUnbind);
$("#kendowindow").click(function(){
console.log("in2");
//want to bind the click event again but not working
$('#showSelection').unbind('click').bind('click',bindUnbind);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="showSelection">Show Selection</div>
<div id="kendowindow">Kendo Window</div>
Upvotes: 0
Reputation: 506
You can use jQuery's .one() in order to run your first click event only once:
$("#showSelection").one("click", function(){
alert("in");
});
$("#kendowindow").click(function(){
alert("in2");
$("#showSelection").on("click", function(){
alert("new event bound");
});
});
However, I am not sure exactly what the scenario is that you are trying to accomplish. With this code, if the user clicks the kendowindow FIRST, then it will be assigning a second event to your showSelection click. I'm not sure if that is what you want or not.
Upvotes: 0
Reputation: 318182
You can't really just rebind it, you'll have to add the entire callback function once more.
To make that easier you can use a named function, and for newer versions of jQuery you should be using on()
and off()
, and there's even one()
if you just want the event handler to fire once per element, and as you're using ID's, you only have one matching element, so :
function doStuff() {
alert("in");
});
$("#showSelection").one("click", doStuff);
$("#kendowindow").on('click', function(){
alert("in2");
$("#showSelection").off('click').one("click", doStuff);
});
Upvotes: 2