Toggle div - Hide on body.click()

Toggle a div when a button is clicked. If anywhere outside of the div is clicked, it should slide back up.

by Craig Haywood

HTML

<a href="#" id="button">Click me</a>
<div id="butcontent">This is some div content</div>

CSS

body { height: 600px; }
#content { background: salmon; display: none; height: 300px; width: 100%; }

JavaScript

$(document).ready(function(){
    
    $('#button').click( function(e) {
        
        e.preventDefault(); // stops link from making page jump to the top
        e.stopPropagation(); // when you click the button, it stops the page from seeing it as clicking the body too
        $('#butcontent').toggle();
        
    });
    
    $('#butcontent').click( function(e) {
        
        e.stopPropagation(); // when you click within the content area, it stops the page from seeing it as clicking the body too
        
    });
    
    $('body').click( function() {
       
        $('#butcontent').hide();
        
    });
    
});