carlsednaoui / ouibounce

Increase your landing page conversion rates.
MIT License
2.31k stars 373 forks source link

close modal with click anywhere outside the modal? #56

Closed pjrvs closed 10 years ago

pjrvs commented 10 years ago

i've used OUI on my site, pjrvs.com, for a while and i love it. only complaint i get from folks is trying to click anywhere off the modal and it not closing. that'd be the only thing i wish it did. cheers!

jescalan commented 10 years ago

Hi @pjrvs!

Ouibounce won't do this automatically, it's only responsible for detecting and firing the event when the user is about to leave. The modal logic is on you to code :grinning:

The good news is that you can actually make this happen yourself fairly easily, just attach a click event handler to the body element that fires the modal close event. If you want to prevent the event bubbling from also closing the modal when you click anywhere inside the modal, you can attach a second click handler to the modal that calls stopPropagation.

carlsednaoui commented 10 years ago

@pjrvs the example page has this behavior. As @jenius said, this is something that would need to be implemented on your end.

Here's how I implemented this:

    <!-- Example page JS        -->
    <!-- Used to fire the modal -->
    <script>

      // if you want to use the 'fire' or 'disable' fn,
      // you need to save OuiBounce to an object
      var _ouibounce = ouibounce(document.getElementById('ouibounce-modal'), {
        aggressive: true,
        timer: 0,
        callback: function() { console.log('ouibounce fired!'); }
      });

      $('body').on('click', function() {
        $('#ouibounce-modal').hide();
      });

      $('#ouibounce-modal .modal-footer').on('click', function() {
        $('#ouibounce-modal').hide();
      });

      $('#ouibounce-modal .modal').on('click', function(e) {
        e.stopPropagation();
      });
    </script>

The key is this little bit here:

     $('body').on('click', function() {
        $('#ouibounce-modal').hide();
      });

Combined with this to ensure users can click on the modal content without having it close on them:

      $('#ouibounce-modal .modal').on('click', function(e) {
        e.stopPropagation();
      });

Closing this issue for now — let me know if you have any problems implementing this on your end :smile: