Reputation: 215
I have some jquery code that I want to bind based on if a box isVisible or not. If its is visible, I want a specific function to be called. If it is not visible, I want the function to change. I have the code below that I believe in theory- should work. What am I missing?
if ($(box).is(':visible')) {
$("#prev2").bind('click', test);
} else{
$("#prev2").bind('click', test1);
}
$("#b").click(function () {
$("#box").hide();
});
function test() {
alert("clicked");
}
function test1() {
alert("clicked again!");
}
#box {
position:absolute;
width:100px;
height:100px;
background-color:black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="prev2">prev</button>
<button id="next2">next</button>
<br>
<br>
<button id="b">Button</button><br><br>
<div id="box"></div><br>
Upvotes: 0
Views: 42
Reputation: 5679
you should first unbind any event attached to the element. use
if ($(box).is(':visible')) {
$("#prev2").unbind('click');
$("#prev2").bind('click', test);
} else{
$("#prev2").unbind('click');
$("#prev2").bind('click', test1);
}
The above will unbind any event and rebind the new handler. You would need to change the handler once the box is hidden.
Update
The following fiddle shows how the events get bind upon the user click on the buttons. The function should be run once so the initial events are bound to the element. Then it's rerun when the div is hidden.
Upvotes: 1