Photo for Click Outside Element To Close

Here is a little jQuery snippet that allows you to click/touch outside of an element to close it.

<div id="myElement">
    Hide this when we click outside of it
</div>

<script>
    jQuery(document).ready(function($) {
        $('#myElement').on('click touchstart', function(e) {
            e.stopPropagation();
        });
        $(document).on('click touchstart', function() {
            $('myElement').hide();
        });
    });
</script>

Working Example

example markup and code

<div class="clearfix">
    <div id="wrapper" class="pull-left">
        <div id="example" style="display:none;">Click outside to hide</div>
        <button id="exampleTrigger" class="btn btn-default">Open Element</button>
    </div>
</div>

<script>
    jQuery(document).ready(function($) {
        var trig = $('#exampleTrigger');
        var block = $('#example');
        $('#wrapper').on('click touchstart', function(e) {
            e.stopPropagation();
        });
        trig.on('click', function(e) {
            block.show();
            trig.hide();
            $(document).on('click.clickOffEvents touchstart.clickOffEvents', function() {
                block.hide();
                trig.show();
                $(document).off('clickOffEvents');
            });
        });
    });
</script>

About The Author

James Olson

James is a graduate of the University of Colorado with a degree in business management. After college, he worked for a small advertising company that focused on the Real Estate Industry where his main focus was on web advertising and email campaigns.

In 2008, James joined booj as a member of the Deployment team and quickly moved through the ranks to become the lead front-end developer. In 2012, he was named the Director of Research & Development where he continues to push the envelope of new web technologies.



Similar Posts

Photo for jQuery Plugin Boilerplate

jQuery Plugin Boilerplate

Below is a pretty powerful jQuery plugin boilerplate. Simply replace the "MyPluginObject" with your ...

Photo for Useful JavaScript Snippets

Useful JavaScript Snippets

I can't remember everything so, I've posted a bunch of JavaScript snippets I constantly use and refe...