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
  • #152471

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

    $(".form-btn").click(function(event) {

    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 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" />

    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?



    The simplest solution might be just to do something like:

    $(".form-btn").on('click', function() {
    $(document).on('click', function() {
    $('.form-popup, .form-btn').on('click', function(e) {

    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:

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