Utilizing jQuery to close a modal when clicking outside of its container

Trying to target elements in my practice layout but struggling to figure out the right approach:

BASIC HTML

<button id="opencontact" type="button" name="button">
  <i class="far fa-envelope fa-2x"></i>
</button>

<section id="contact-section">
  <div class="contact-container">
    <div class="contact-content">
      <h2>Contact Us</h2>
      <label for="">Email</label>
      <input type="text" name="" value="">
      <label for="">Name</label>
      <input type="text" name="" value="">
      <label for="">Message</label>
      <textarea name="name" rows="8" cols="80"></textarea>
      <button type="button" name="button">Submit</button>
    </div>
  </div>
</section>

CSS STYLES:

body {
  padding: 0;
  margin: 0;
  font-family: Helvetica;
  box-sizing: border-box;
}

#opencontact {
  bottom: 10px;
  right: 10px;
  position: fixed;
}

#contact-section {
  height: 60%;
  width: 40%;
  position: absolute;
  top: 20%;
  left: 30%;
  display: none;
  align-items: center;
  justify-content: center;
  background-color: red;
}

#contact-section.show {
  display: flex;
}

.contact-container {
  height: 90%;
  width: 90%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.contact-content {
  height: 90%;
  width: 90%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

JQuery SCRIPT to open the contact-section when #opencontact is clicked:

<script type="text/javascript">

  $("#opencontact").click(function() {
    $("#contact-section").toggleClass("show");
  });

</script>

Need help with a script to close the modal when clicking outside the #contact section. Existing solutions tried didn't work, so looking for suggestions.

Answer №1

To start, you need to set up a click listener for the entire website. Each time a click occurs, you will check if the element you are interested in is clicked. Despite the fact that an if statement is executed for every click, this does not pose a performance issue and is the correct way to address this situation.

Your code should resemble the following (without using jQuery). For reference, you can view the snippet here.

const contactSection = document.querySelector('#contact-section');
let isContactSectionShowed = false;

window.addEventListener('click', function (e) {
  if (e.target === contactSection && !isContactSectionShowed) {
    contactSection.classList.add("show");
    isContactSectionShowed = true;
  } else if (e.target !== contactSection && isContactSectionShowed) {
    contactSection.classList.remove("show");
    isContactSectionShowed = false;
  }
});

Answer №2

$(document).ready(function() {

  const modal = $('#contact-section');

  $("#opencontact").click(function() {
    modal.toggleClass("show");
  });

  $(document).click(function(event) {
    // Check if NOT click on modal or button
    if (!$(event.target).closest("#contact-section, #opencontact").length) {
      modal.removeClass("show")
    }
  });

});
body {
  padding: 0;
  margin: 0;
  font-family: Helvetica;
  box-sizing: border-box;
}

#opencontact {
  bottom: 10px;
  right: 10px;
  position: fixed;
}

#contact-section {
  height: 60%;
  width: 40%;
  position: absolute;
  top: 20%;
  left: 30%;
  display: none;
  align-items: center;
  justify-content: center;
  background-color: red;
}

#contact-section.show {
  display: flex;
}

.contact-container {
  height: 90%;
  width: 90%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.contact-content {
  height: 90%;
  width: 90%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/all.min.js" integrity="sha256-KzZiKy0DWYsnwMF+X1DvQngQ2/FxF7MF3Ff72XcpuPs=" crossorigin="anonymous"></script>

<button id="opencontact" type="button" name="button">
  <i class="far fa-envelope fa-2x"></i>
</button>

<section id="contact-section">
  <div class="contact-container">
    <div class="contact-content">
      <h2>Contact Us</h2>
      <label for="">Email</label>
      <input type="text" name="" value="">
      <label for="">Name</label>
      <input type="text" name="" value="">
      <label for="">Message</label>
      <textarea name="name" rows="8" cols="80"></textarea>
      <button type="button" name="button">Submit</button>
    </div>
  </div>
</section>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Convert a String to JSON using either JavaScript or jQuery

Currently, I am developing a JavaScript animation script and I am aiming to allow individuals to define behavior declaratively within the HTML. This is the format I envision for my HTML: <div data-animation="top: 600, left: 600, opacity: 1, start: 0.2 ...

The webpage appears fine on the local server, but displays incorrectly on IIS (Internet Explorer 11)

My project looks great when I run it locally on my computer and open the page in Internet Explorer 11: https://i.stack.imgur.com/yZvo2.png However, when I deploy the page to an IIS server and navigate to the page, it appears differently in Internet Explo ...

Google Chrome extension with Autofocus functionality

I developed a user-friendly Chrome extension that allows users to search using a simple form. Upon opening the extension, I noticed that there is no default focus on the form, requiring an additional click from the user. The intended behavior is for the ...

Identify the mouse's location in relation to its parent element, not the entire webpage

A script I've been working on detects the mouse position relative to the page, taking into account a movement threshold of 100px before triggering certain actions. // Keep track of last cursor positions var cursorDistance = 0; var lastCursorX = null; ...

retrieve the current image source URL using JavaScript

In the template below, I am looking to extract the current img src URL and utilize it in a fancybox button. For example, in the template provided, there are 3 images from https://farm6.staticflickr.com. When clicking on these images, the fancybox will ope ...

Tips for using a JavaScript function to navigate to a specific division (<div>) on an HTML page

I am facing an issue where I need to redirect within the same HTML page that includes a add-form div. What I want is that when I click on a button, my redirection should be to a specific div containing some code. Currently, I have code that redirects to a ...

Tips for adding a solid background color to a div element

I am struggling with trying to make a full width background-color for a div in my ruby on rails app. Despite setting the background color and margin to 0, I still end up with unwanted margins on the left, right, and top. Below is the code snippet: <!D ...

What's the best way to ensure uniform card height in Material-UI?

Is there a way to ensure consistent card height in Material-UI without setting a fixed height? I want the card heights to dynamically adjust based on content, with all cards matching the tallest one on the website. How can this be achieved while also addin ...

Surprising behavior of translateZ in Framer Motion

Trying to position elements in a circular layout has led to unexpected behavior when using framer motion's translateZ. By applying styles with a template literal without shorthand for transforms, the desired effect is achieved: transform: ` rotateY( ...

A guide to setting an href using variable values in jQuery through manual methods

I have a datepicker set up where each day, month, and year is stored in a variable. I then display this information in the desired format. Below is the jQuery code: jQuery(document).ready( function($){ alert('alert function'); var txtFr ...

Guide to positioning multiple <img> elements within a single <div> container

I'm having trouble aligning these 6 images inside a div using CSS. They are currently aligned vertically, but I want them to be side-by-side. div#menu-lixos img{ margin-left: auto; margin-right: auto; ...

Tips for adjusting the vertical position of an image within a bootstrap column by a small amount

Apologies in advance if this question has already been addressed, and I am struggling to adapt it to my specific scenario. My objective is to adjust the positioning of the two images shown in the screenshot example below so that they align with the grey b ...

Preventing event propagation in jQuery's click handler

Is it possible to prevent the propagation of a click event on a dynamically created div within its parent div? HTML <div id = "parent"> Some Stuff </div> Jquery $('#parent').click(function(){ $(this).append('<div class = ...

Managing the vertical positioning of grid items: tips and tricks

Is there a way to make the hexagons in my grid responsive to the layout, so that their height and width remain fixed relative to their container? Currently, they are overflowing from the grid container as shown in this jsfiddle: https://jsfiddle.net/gv5wc1 ...

Is there a way I can appropriately display an image in a specific size box?

Check out the code snippet I wrote below: import React from 'react' function OurCourse() { return ( <div className='w-full '> <div className='w-full h-[390px]' style={{ backgroundImage:&apos ...

The JQuery code is failing to remove the dynamically added field when the delete icon is clicked

Information: I am currently navigating the world of programming and attempting to build a To-Do List feature. When the create list button is clicked, a dynamically generated div with the class 'wrap' is created. This div contains two nested divs: ...

Calling a C# Webmethod using jQuery AJAX is not working as expected

I'm currently facing an issue calling a web method that I created. The problem lies in the fact that the ajax call isn't reaching my web method, which is puzzling to me because I have another web method in the same file with the same return type ...

Creating a webpage that utilizes varying headers for each section can help to

When trying to print a multi-page webpage, I encounter an issue with the headers. How can I ensure that different headers appear on each page after the first one? Specifically, my problem arises when a label on the first page spans across to the second pa ...

Position the larger element in the center of the smaller container element

Is there a way to center an image without it covering up the paragraph below? Using position: absolute; or float: left; can lead to layout issues. <p>This is the first paragraph</p> <p><img src="http://placekitten.com/600/280"/>&l ...

I am experiencing an issue where the jquery sleep function is not being executed during

I currently have an Ajax request that is awaiting a response from another process. function checkProcess() { var flag = 0; while (flag === 0) { $.ajax({ url: "cs/CheckForProcess", async: false, success: ...