Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a click-event-handler inside a click-event

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?

like image 692
Lars Ebert Avatar asked Sep 11 '13 08:09

Lars Ebert


People also ask

What are the different methods to associate an event handler explain all for click event of a button?

There are three ways to assign an event handler: HTML event handler attribute, element's event handler property, and addEventListener() .


2 Answers

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/

like image 156
Kevin Bowersox Avatar answered Sep 29 '22 23:09

Kevin Bowersox


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;
}
like image 33
Shakti Patel Avatar answered Sep 29 '22 22:09

Shakti Patel