Search code examples
javascriptjquerytogglemouseup

jquery toggle class & mouseup button issues


I am using 2 script's, as shown below.

The 1st script open's a div when a button is clicked with the class of "bookaviewing".

I need the div with the class "booking-form" to close when someone click's outside of the "booking-form" div - the 2nd script does this.

My issue is when you click the button more than once (as it's outside of the "booking-form" div), it won't close the "booking-form"... it just keeps opening.

I need to combine the 2 below scripts & need assistance.

Script 1

<script type="text/javascript">
// set click/toggle event on bookaviewing button to show form
$('.bookaviewing').click(function () {
    $('.booking-form').slideToggle(400).toggleClass('opened');
    return false;
});
</script>

Script 2

<script type="text/javascript">
// close booking-form when click outside of div
$(document).mouseup(function (e){
    var bookingform = $(".booking-form");
    if (!bookingform.is(e.target) && bookingform.has(e.target).length === 0){
        bookingform.hide();
    }
});
</script>

Solution

  • You need to exclude the booking form and the toggle button, to avoid the toggle open/closing at the same time:

    http://jsfiddle.net/TrueBlueAussie/4vnvpcjb/3/

    // set click/toggle event on bookaviewing button to show form
    $('.bookaviewing').click(function () {
        $('.booking-form').slideToggle(400).toggleClass('opened');
        return false;
    });
    $(document).on('mouseup', function (e){
        var bookingform = $(".booking-form");
        if (!bookingform.is(e.target) 
             && bookingform.has(e.target).length === 0 
             && !$(e.target).is('.bookaviewing'))
        {
            bookingform.slideUp();
        }
    });
    

    Note: I changed the click outside, from hide() to slideUp as well, as hide was a bit jarring.