title: Attach Click Event to HTML after Menu Click
body: <p>I've got a dropdown menu on a site I'm working on that has different classes added to it when it is activated. It's built into a WordPress theme so I'm having to build a workaround on it for iPad landscape mode. The site navigation displays the same as desktop when on landscape so I need to create some touch events to mimic the behavior.</p>
  
  <p>The first thing I'm having to do is to deactivate the link on the first click and then reactivate it if it's clicked again. This works fine. </p>
  
  <pre><code>if ('ontouchstart' in document.documentElement) {
      $('#masthead nav ul &gt; li:has(.sub-menu) a').click(function(e){
          e.preventDefault();
          $('li.clicked_link').on('click', function(){
              var this_link = $(this).find('&gt; a').attr('href');
              document.location.href=this_link;
          });
  
          $(this).parent().addClass('clicked_link');
      });
  }
  </code></pre>
  
  <p>The problem is that when you click on the <code>li.sub-menu</code> it adds a class of <code>sub-hover</code> onto it which activates a dropdown menu. It's a CSS/jQuery dropdown menu so it's based on the presence of that <code>sub-hover</code> class. It works fine when I first click but I then want to remove that class when you click outside of it. It deactivates it if I click another link in the dropdown but I'd like to bind a click event to the <code>html</code> or <code>body</code> elements so if you click anywhere outside of it, it will remove the <code>sub-hover</code> class, thus removing the dropdown.</p>
  
  <p>I tried to do this:</p>
  
  <pre><code>if ('ontouchstart' in document.documentElement) {
      $('#masthead nav ul &gt; li:has(.sub-menu) a').click(function(e){
          e.preventDefault();
          $('li.clicked_link').on('click', function(){
              var this_link = $(this).find('&gt; a').attr('href');
              document.location.href=this_link;
          });
  
          $(this).parent().addClass('clicked_link');
  
          $('html').on('click',function(){
              $('#masthead nav ul &gt; li:has(.sub-menu)').removeClass('sub-hover').removeClass('clicked_link');
          });
      });
  }
  </code></pre>
  
  <p>It doesn't work though because it seems to fire the first click function and then immediately fire the html click function. I tried to use <code>bind</code> as well but the same thing happened. I also tried it outside of the initial click function but, as you can guess, it fires the two click events simultaneously which doesn't work.</p>
  
  <p>How do I get it to bind but not fire the click event only after the initial click event takes place?</p>