简体   繁体   中英

Dropdown Box disappear on click away

This is my first post on here and I'm just learning Jquery so please be kind! :)

I have just created a website - www.wayfairertravel.com and I have some dropdown boxes on my homepage, where users can search 'By Style' etc...

At the moment once those boxes are opened you have to close them manually... I'm just wondering if there is a way to change the code there currently so that when a user clicks elsewhere on the page it disappears.

Any help greatly appreciated. If you you could be as precises in your answer that would be great - Ie where to change the code and what to change to.

Cheers,

Harry

Usually, you add events on body and on the desired dropdown:

$(document.body).on('click', function() {
    dropdown.close(); // .hide(); whatever
});
dropdown.on('click', function(event) {
    event.stopPropagation(); // prevents dropdown from getting closed when clicking on it
});

However, I think there are jQuery plugins for clickOutisde events that you could use too (they probably work like mentioned above, but you don't have to write it yourself).

I took Jakub Michálek advice and applied it your code. I prepared fiddle so you can test it out: http://jsfiddle.net/tmuuS/

This is your javascript you want to have on your page:

$(document).ready(function () {
    $("#expslider").hide();
    $("#expshower").show();
    $('#expshower').click(function () {
        $("#expslider").slideToggle();
    });

    $(document.body).on('click', function () {
        $("#expslider").slideUp();
    });
    $("#expslider").on('click', function (event) {
        event.stopPropagation(); // prevents dropdown from getting closed when clicking on it
    });
    $("#expshower").on('click', function (event) {
        event.stopPropagation(); // prevents dropdown from getting closed when clicking on it
    });
});

Although remember that it's better to have javascript in head tag, not right beside the place where you use it. (hard to look for it later when you need changes)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM