Im having some problems with .on() and how to use it instead of .bind() in this situation.
What im trying to do here is i click a link and that is supose to bind another click event, but instead it triggers that event right away. I looked in the documentation/jquery.js file and this is how im suppose to do it.
Demo: http://jsfiddle.net/bNaFV/
$('#click_me').on('click', function(){
$('#show_me').addClass('remain');
//this is only suppose to bind that next time i click anywhere on the document it should hide
// not right away
$(document).on('click', 'html', function(){
$('#show_me').hide();
});
});
$("#click_me").hover(
function () {
$('#show_me').show();
},
function () {
if ($('#show_me').hasClass('remain')){
return;
} else {
$('#show_me').hide();
}
}
);
<a href="#" id="click_me">click me</a><br /><br />
<div id="show_me"></div>
You need to stop the propagation of the event:
This is because the event has been captured at the
#click_meelement. You then bind an event handler for that same event type somewhere higher up the DOM tree. The event then continues bubbling up the tree and reaches thedocument, where it triggers the new event handler.Here’s a working example.
Update (see comments)
As noted by @zerkms in the comments, I think you probably only want to bind the event handler to
documentonce. You could use theonemethod to do so, which unbinds the event handler after it’s been executed once: