Choose the window element using JQuery version 2

I am attempting to close a modal when the user clicks outside of it, using JQuery instead of plain JavaScript like in the W3C website example. The $modal variable contains the jQuery object representing the HTML div used for the modal.

I came across this code on stackoverflow, but it did not work:

let $window = $('window', opener.document);
window.parent.$window.on('click', function(event){
    if (event.target == $modal){
        $modal.css({display:'none'});
    }
});

This is what I tried myself:

let $window = $('window');
window.on('click', function(event){
    if(event.target == $modal){
        $modal.css({display:'none'});
    }
}

Trying to mix Plain JavaScript with JQuery:

let $window = $('window');
window.onclick = function(event){
    if(event.target == $modal){
        $modal.css({display:'none'});
    }
}

Is there something I am overlooking?

Answer №1

Hey there, I'm not entirely sure what you're asking about regarding $modal, but here's a guide on how to create a basic modal using CSS and jQuery:

var modal = $('#myModal'),
  span = $(".close")[0],
  btn = $('#mybtn');
  $(span).on('click',function() {
$(modal).css("display", "none");
});
      
  $(document).on('click', function(event) {
if (event.target == $(modal)[0] ) {
$(modal).css("display", "none");
}
})
      
      $(btn).on('click', function(e) {
e.preventDefault();
$(modal).css("display", "block");
})
/**
* Modal CSS
**/
/* Modal Background */
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}

/**
* Modal Box
*/
.modal-content {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
width: 50%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.4s
}


@-webkit-keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}

@keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}


.close {
color: white;
float: right;
font-size: 28px;
font-weight: bold;
}

.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}

.modal-header {
padding: 2px 16px;
background-color: #4a7ac9;
color: white;
}

.modal-body {padding: 2px 16px;}

.modal-footer {
padding: 2px 16px;
background-color: #4a7ac9;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myModal" class="modal">

<!--Content-->
<div class="modal-content">
<div class="modal-header">
<span class="close">&times;</span>
<h2 id="consultTechnician"></h2>
</div>
<div class="modal-body" id="modalForm">

<p>Hello World</p>


</div>
<div class="modal-footer">
</div>
</div>
</div>
  
  <input type="button" id="mybtn" value="Show Modal">

It seems like the issue might have been here :

if(event.target == $modal)

Your modal was stored as the first element of your jQuery object.

I hope this clarifies things for you!

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

Using jQuery to insert HTML content into a div element by replacing a specific string

I am faced with a situation where I have <div class="test">hello everyone</div> and the challenge is to replace each instance of "hello" within this div with <h1>helllo</h1> In my attempt, I used $(this).text().replace("hello" ...

Strategies for handling divisions while resizing the browser界面 manipulating divisions during

Here's the HTML/CSS code I'm working with: .container { max-width: 900px; margin: 0 auto; margin-top: 30px; } .divisions { border: 1px solid Black; } .Fisrt-Line { height: 180px; } .First { background-color: Green; width: 32.2% ...

The strict mode in React reveals unexpected changes in state with double rendering

While working with React, I've noticed that it renders twice in Strict mode during development to ensure the function remains pure without any side effects. However, I'm facing some inconsistency in retrieving the state in my case. It seems like ...

Upon page refresh, products are automatically added to the cart

While developing a shopping cart code, I encountered an issue where refreshing the page automatically added a product to my cart without any action from me. For instance, my website displays three products: Apple, Banana, Orange. When I click on Apple, it ...

I Tried Adding Up All the Numbers, but It Doesn't Seem to Work for Every Dynamic Total Field

In my project, I am utilizing Laravel 5.7 and VueJs 2.5.*. The issue I am facing is that when I input values, the Total field calculates correctly. However, when I dynamically add rows for items, the calculation only works for the first row and not for the ...

The AngularJS modal is sending back the results before updating the parent scope

When launching a modal from my web page, I am updating an array passed from the parent. However, when closing the modal and sending back the updated results, the parent scope object is also being updated. If the user decides not to update and cancels the ...

Tips for sending a string variable into a JavaScript function

Here is the code snippet I am working with: JSP : String userId = rs.getString("user_id"); <center><a href="#" onclick="edit(\'' + userId + '\');">Edit</a></center> JavaScript : function edit(id) ...

The jQuery Ajax form binding will occur only once when submitting the form

I am facing two issues. When I directly load my page, the form only submits once. However, if I load the form in a modal, it does not submit at all. After a successful submission, I want to redisplay the form (loaded via ajax) and ensure that the script r ...

What sets apart Object.assign {} from Object.assign []?

While reviewing code done by a previous developer who is no longer with us, I observed that they sometimes used Object.assign({}, xyz) and other times they used Object.assign([], abc); Could there be a distinction between the two methods? ...

Sending information from the Controller to a JavaScript function

Within my controller, the following code is present: public async Task<IActionResult> Index() { HttpResponseMessage responseMessage = await _httpClient.GetAsync(_getDataControlerApiUrl + "/getUserData"); string stringDat ...

Retrieve base64 encoded data from several content attributes

Is there a way to optimize the use of base64 data in CSS by defining it once and referencing it in multiple content properties? div#my_id1 { content: url(data:image/png;base64,...); } div#my_id2 { content: url(data:image/png;base64,...); } Using ...

Having trouble retrieving directive parameters in Vue.js?

Vue.directive('customselect', { params: ['selectedTask'], bind: function () { var that = this; $(this.el) .select2() .on('change', function () { that.set(this.value); if (!this.name.matc ...

What is the best way to execute 2 statements concurrently in Angular 7?

My goal is to add a key rating inside the listing object. However, I am facing an issue where the rating key is not displaying on the console. I suspect that it might be due to the asynchronous nature of the call. Can someone help me identify what mistak ...

Using asynchronous import statements in Vue allows for more efficient loading of components

I am using Vue and have a method in my file called load.js. async function loadTask(x) { return await x; // Some async code } export { loadTask }; In one of my Vue components, I call the method but encounter an issue where the use of await prevents the ...

Can someone help me troubleshoot why the form for my Django LoginView is not showing up on my website?

After spending nearly an hour going through the documentation, I still can't figure out why the LoginView form is not displaying properly. The template seems to be rendering correctly but the form itself is missing from the HTML tags. urls.py from dj ...

Accessing parent libraries from an Iframe: A step-by-step guide

Currently, I'm developing a web application utilizing an embedded web server that restricts me from modifying the HTTP header to enable file caching. One issue I've encountered is that whenever I update the src of an iframe in my app, it forces a ...

Jest's testing coverage does not include branch coverage

I've been working on creating a unit test for my API and have put in every possible test I could come up with. However, when running jest for coverage, I am still not getting 100% coverage. The report indicates that certain statements, branches, and l ...

locating the truth value of the data in an array retrieved from MongoDB

When returning from the mongoose find() function, I need to ensure that is_reqestor = true is checked. However, when updating the document, I pass the id which needs to be updated. let filter = { is_reqestor: true } if (!is ...

When using FormData to send data, Laravel's Ajax function Input::all() may not return the expected values

As I work on developing an application using Laravel 4, I encountered a situation where I needed to add a model through a modal (Bootstrap) and utilize Ajax to send my form data. After setting up the route and controller action, as well as creating the for ...

Adding a new property to a JSON object in a specific position

This might be a Repeat: Does JavaScript Guarantee Object Property Order? I am curious about inserting a property into a JSON object at a specific location. Consider this Javascript object: var data = { 0: 'lorem', 1: 'dolor sit&apo ...