Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript How to make a toggle element close when clicking off it?

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #152471
    aaron118
    Participant

    I have a group of classes which toggle. The code is this:

    $(".form-btn").click(function(event) {
        event.preventDefault();
        $(this).next().toggle(0);
    });
    

    With the HTML as so:

        <div class="form-btn-wrapper">
            <div class="form-btn" id="buy-or-rent">Buy or Rent <i class="icon-caret-down"></i></div>
            <div class="form-popup radio">
                <input id="check1" type="radio" name="buy-or-rent" value="To Buy">
                <label for="check1">To Buy</label>
                <input id="check2" type="radio" name="buy-or-rent" value="To Rent">
                <label for="check2">To Rent</label>
            </div>
        </div>
        <div class="form-btn-wrapper">
            <div class="form-btn" id="price">Price <i class="icon-caret-down"></i></div>
            <div class="form-popup">
                <input type="text" name="min-price" class="small price-input" placeholder="Min" /> to <input type="text" name="max-price" class="small price-input" placeholder="Max" />
            </div>
        </div>
    

    This works fine but to close each toggle (form-popup class) you must click again its respective form-btn. How can I change the jquery so that the form-popups close when you click anywhere?

    Thanks

    #152534
    Josh
    Participant

    The simplest solution might be just to do something like:

    $(".form-btn").on('click', function() {
        $(this).next().toggle(0);
    });
    
    $(document).on('click', function() {
        $('.form-popup').hide(0);
    });
    
    $('.form-popup, .form-btn').on('click', function(e) {
        e.stopPropagation();
    });
    

    You don’t need event.preventDefault() on .form-btn unless it’s an anchor link, which would make sense, but since in your example it’s a div I removed that call. The last block is to prevent any clicks on .form-popup from propagating up to the document level and closing it. Pretty straightforward.

    Here’s a quick CodePen to demonstrate: http://codepen.io/JoshBlackwood/pen/xdChn

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.