Daniel Daniel - 6 months ago 23
Javascript Question

Click outside element without using event.stopPropagation

I know there are lots of ways to detect the click outside of an element. Mostly all of them use

event.stopPropagation
. Since
event.stopPropagation
will break other stuff, I was wondering if there is another way to achieve the same effect. I created a simple test for this:

HTML:

<div class="click">Click me</div>


Javascript:

$(function() {
var $click = $('.click'),
$html = $('html');

$click.on( 'click', function( e ) {
$click.addClass('is-clicked').text('Click outside');

// Wait for click outside
$html.on( 'click', clickOutside );

// Is there any other way except using .stopPropagation / return false
event.stopPropagation();
});

function clickOutside( e ) {
if ( $click.has( e.target ).length === 0 ) {
$click.removeClass('is-clicked').text('Click me');

// Remove event listener
$html.off( 'click', clickOutside );
}
}
});


http://jsfiddle.net/8p4jhvqn/

This works, but only because i stop the bubbling with
event.stopPropagation();
. How can i get rid of
event.stopPropagation();
in this case?

Answer

It can be done in a simpler way, can't it be? Why complicate things when something as simple as below could work.

$(document).click(function(e){
    var elm = $('.click');
    if(elm[0] == e.target){
       elm.addClass("is-clicked").text("click outside");
    } else { elm.removeClass("is-clicked").text("click inside"); }
});

DEMO

Comments