Reputation: 111
Can you please let me know why I am not able to control the event on div
until button click event happen?
Basically what I need to is only one event happens on div
after the button
clicked
I tried to control this with Boolean clickEvtHandler
but it didnt go through
var clickEvtHandler = false;
var i = 1;
$("button").on("click", function() {
clickEvtHandler = true;
if (clickEvtHandler) {
$("div").on("click", function() {
$(this).append(i++);
clickEvtHandler = false;
});
}
});
div {
height: 300px;
width: 300px;
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
Enable Event On Div
</button>
<div></div>
Upvotes: 1
Views: 365
Reputation: 126
var clickEvtHandler = false;
var i = 1;
$("button").on("click", function() {
clickEvtHandler = true;
if (clickEvtHandler) {
$("div").on("click", function() {
if (clickEvtHandler)
$(this).append(i++);
clickEvtHandler = false;
});
}
});
Upvotes: 0
Reputation: 4539
If you want to use event only once then go for
$( "#div" ).one( "click", function() {
alert( "This will be displayed only once." );
});
Above code will make sure that event bonded to given div will execute exactly once.
Upvotes: 4
Reputation: 138257
Maybe use two seperate handlers:
var clickEvtHandler = false, i = 1;
$("button").on("click", function() {
clickEvtHandler = true;
});
$("div").on("click", function() {
if (!clickEvtHandler) return;
$(this).append(i++);
clickEvtHandler = false;
});
Upvotes: 0