javascript - Click outside element without using event.stopPropagation -
i know there lots of ways detect click outside of element. of them use event.stoppropagation
. since event.stoppropagation
break other stuff, wondering if there way achieve same effect. created simple test 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 click outside $html.on( 'click', clickoutside ); // there 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 ); } } });
this works, because stop bubbling event.stoppropagation();
. how can rid of event.stoppropagation();
in case?
it can done in simpler way, can't be? why complicate things when simple below 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"); } });
Comments
Post a Comment