smack-a-bro smack-a-bro - 2 months ago 12x
jQuery Question

Make accordion close once click occurs anywhere on the page

I have an small div that once revealed shows important data that needs to stay hidden from view unless otherwise chosen.

I'm having trouble getting it to work how I need.

Essentially this code slides out that div when the button is double clicked. However, if the div is open I would like to close it after 5 seconds or if another click takes place anywhere on the page. I tried playing around but cannot get it to work at all.

$( "#button" ).dblclick(function() {
$( "#item" ).toggle("accordion");

The problem I run into is that the additional jquery I add doesn't check to see if the div is open so the actions are just overlapping.


I think you are looking for something like this...

$( "#button" ).on( 'click', function() {
    $( "#item" ).toggle('accordion');
    var autoClose = setTimeout( function() { $( "#item" ).toggle('accordion'); $( window ).unbind( 'mousedown' ); } , 5000);

    $( window ).on( 'mousedown', function( event ) {
        $( "#item" ).toggle('accordion');
        $( window ).unbind( 'mousedown' );

Here's a fiddle...