stef67 stef67 - 4 months ago 10
Javascript Question

automatic close function for selection

I have a button which creates a pulldown in which you can select several categories.
Now i want this to close automatically when i click outside the pulldown.
Something like a lightbox or modal popup which closes if you click anywhere else on the page.
Now i have to click the button again to close it. If i dont and go elsewhere on the page, the dropdown stays visible (until i click it)

This is the code of the button:

$(function(){
$('#browse-btn').click(function(){
$('#browse-content').toggle('1000');
$(this).toggleClass('active');
if ($(this).hasClass('active')) $(this).find('span').html('▲')
else $(this).find('span').html('▼')
});

$(".scroll-top").scrollToTop();

$("#category_id").selectbox();
});


Is this possible?
thanks

Answer

Using jquery this is the code I used for a similar case scenario sometime ago:

$(document).click(function(event) { 
    if(!$(event.target).closest('.pulldown').length) {
        if($('.pulldown').is(":visible")) {
            $('.pulldown').slideUp()
        }
    }        
})

You can read more about this in the original post How to detect a click outside an element? submitted by Art.

Comments