Im trying to bind/live a click event when an other is done. So I’m using .on() and .off(). The way is suppose to act is that when
- i click the
a.nav-linka div shows up, - and when it does i pin a
clickevent to the document, - it binds a click event that when ever i click anywhere in the html it close the div and off() the document behavior
now it works fine for one round but next time i click the a.nav-link it performs all the tasks at once, so what I’m i doing crazy here?
Demo: http://jsfiddle.net/xHNQ3/1/
<div id="container">
<header>
<div class="nav">
<a href="#" id="nav-link">click me</a>
</div>
<div class="sub-nav"></div>
</header>
</div>
$('#nav-link').on('click', bindOnClick);
function bindOnClick() {
$('.nav').addClass('isVisible');
$('.sub-nav').show(function(){
$(document).on('click', 'html', function(){
alert('done');
$('.sub-nav').hide();
$(document).off('click', 'html', bindOnClick);
});
});
}
EDIT: what I’m trying to do here is basically that whenever i click outside the two divs the one that shows up .sub-nav should hide.
This line is your problem,
bindonclickis associated with the link, not with the document click.http://jsfiddle.net/xHNQ3/4/
If you want to prevent clicking of link from causing a double event fire then turn it off/on too.
http://jsfiddle.net/xHNQ3/9/