I have encountered some strange behavior when dealing with click-events in jQuery.
Have a look at this Fiddle
$('#button').click(function() {
$(document).one('click', function() {
alert('clicked');
});
});
This code is binding a click-event-handler to some button. On clicking this link, an event-handler should be added to the document, alerting "clicked" when the document is next clicked.
But when clicking this button, "clicked" gets immediately alerted without another click. So apparently the click-event which binds the new handler to the document gets bubbled to the document and immediately runs the just assigned hndler.
This behavior seems very counter-intuitive. My intention was showing an element when clicking on the button and hiding it again on clicking outside this element.
$('#button').click(function() {
// Show some element
$(document).one('click', function() {
// Hide the element again
});
});
But this results in the element being hidden immediately.
Does anyone have a solution to this problem?
There are three ways to assign an event handler: HTML event handler attribute, element's event handler property, and addEventListener() .
The event can be prevented from propagating up the DOM.
$('#button').click(function(e) {
e.stopPropagation();
$(document).one('click', function(e) {
alert('clicked');
});
});
JS Fiddle: http://jsfiddle.net/7ymJX/6/
can you please check this code Demo
HTML Code
<button id="button">Click me!</button>
<div id="new_div"></div>
Jquery
$('#button').click(function(e) {
e.stopPropagation();
$('#new_div').css('display', 'block');
$('document, html').click( function() {
alert('clicked');
$('#new_div').css('display', 'none');
});
});
Css
#new_div {
height: 100px;
width: 200px;
border:1px solid black;
display : none;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With