Home › Forums › JavaScript › How to make a toggle element close when clicking off it?
- This topic is empty.
-
AuthorPosts
-
October 9, 2013 at 7:25 am #152471Historical Forums UserParticipant
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
October 9, 2013 at 2:32 pm #152534JoshParticipantThe 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 adiv
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
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.