JSFiddle - React, Tailwind, and code Playground
HTML
<div class="click">Click me</div>
CSS
.click {
background: red;
width: 200px;
height: 200px;
}
.is-clicked {
background: green;
}
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 );
}
}
});