2

I have a form with different sections and when the user clicks inside a specific section, I want a progress bar to show up. The bar is initially hidden with display:none. When clicked anyhwere outside the form section, the progressbar shall hide. I know there are lots of questions here that are similar but I can't get it to work for my case.

The problem for me is to target not only the form section id but also all of its children, for example inputs and such. Simply everything which is within the section frame.

Here is my code:

$(document).ready(function(){
  
  $(function() {
      $(document).on('click', function(e) {
          if (e.target.id == 'form-section' ) {
              $('#progressbar').show();
          } else {
              $('#progressbar').hide();
          }
      })
  });
  
});
#progressbar {
  width:50%;
  background:green;
  height:auto;
  margin-bottom:10px;
  display:none;
  }

#form-section {
  background: #eee;
  padding:10px;
  }
<div id="progressbar">progressbar</div>

...there are many elements between progressbar and section...<br><br>

<div id="form-section">
  <h3>form section heading</h3>
  <input type="checkbox" value="check1"/><label>check1</label>
  <p><div class="inner-section"/>
  <input type="radio" name="radio1"/><label>radio1</label>
  <input type="checkbox" name="check2"/><label>check2</label>
  
  </p><span>some content</span></div>
  
  ...many nested elements inside the section
</div>

This code has an effect but it seems to me that the progressbar only shows up when clicked directly into the form-section div but not on any of its children. Can that be?

UPDATE: Now I did some research again and found this answer which turned out to work well on my site: https://stackoverflow.com/a/7385673/5063672

Community
  • 1
  • 1
Thorin
  • 23
  • 8

1 Answers1

0

Try binding the events to the form section element, like so:

$('#form-section').on('click', function(e) {

That should bind to all child elements. I can't really think of a great way to close it by only clicking outside of that area, code below might work, but I have no way to test it. And it's ugly.

 $(document).on('click', function(e) {
     if ($('#progressbar').is(":visible")){
         if !(e.target == $('#form-section') || e.target.parents('#form-section').length)
             $('#progressbar').hide();
         }
    }
} 
Jordan Davis
  • 1,271
  • 14
  • 24
  • If I understand your code correctly then it makes the progressbar show up (tested and works, thanks!) but how can it be hidden on a click outside of the form section div? Sorry I'm anything but a pro when it comes to jQuery. – Thorin Jul 05 '15 at 06:38
  • I tested and it does not work afaik. Thanks anyway for your approach! – Thorin Jul 05 '15 at 07:19