JSFiddle - React, Tailwind, and code Playground

by rpflorence

HTML

<button id=click>Click me</button>
<div id=container style="height: 100px; background: #ccc">

JavaScript

// cache elements for performance!
var container = $('#container').hide();
var button = $('#click');
var doc = $(document);

// a pointer to the function we want to fire when
// the doc is clicked, it will only be around when
// we want it to, so the browser doesn't fire it
// every time the doc is clicked regardless of what
// the user is interacting with
var handler = function(event){
    if (event.target != container[0]){
        // if the container was NOT clicked, do something
        // store the state on the container, much faster than
        // checking if it's visible or not
        container.data('shown', false);
        // fade it out, since we clicked outside of it (even the button!)
        container.fadeOut(function(){
            // callback, to get rid of the click handler on the document
            // because we dont' want to be listening anymore, we dont' care
            doc.unbind('click', handler);
        });
    }
}

// bind click to the button
button.bind('click', function(){
    // check if the container is shown
    if (!container.data('shown')){
        // it's not, so show it
        container.data('shown', true);
        container.fadeIn(function(){
            // call back to bind the event to the document
            doc.bind('click', handler);
        });
    }
});