Sample: Close Fly-In on Background Click

by | Feb 23, 2023 | Samples

Summary

This page contains a Fly-In Area with a close button.

Additionally, the page contains a small JS snippet to close the open Fly-In when clicking anywhere on the page. Also, try to click inside the Fly-In to make sure the Fly-In can receive clicks without closing.

Steps

  1. Create a Fly-In and insert a Code module into it.
<script>
(function($) {
  DiviArea.addAction('init_area', function(area) {
    if (! area.hasId('my-area-id')) { return; }

    // Observe all clicks on the current page.
    $(document).click(maybeCloseArea);
    
    function maybeCloseArea(event) {
      // If the Area is not visible, ignore the click.
      if (!area.isVisible()) {
        return;
      }
    
      // If the user clicked outside of the area, then close it.
      var target = $(event.target);
      var wrap = area.getWrap();
      if (!target.closest(wrap).length) {
        area.hide();
      }
    }
  });
})(jQuery);
</script>