Resolving problems with Modal Pop-ups

I have a Modal that I am trying to open with the code below.

The modal opens fine and adds open to the parent class. However, when I click 'close', it does not close and does not add close to the class either.

Can anyone shed light on why this might be happening?

<script type="text/javascript">
jQuery(document).ready(function($) {

    $window = $(window)

    $(".modal-trigger").click(function(e) {
        e.preventDefault()

        var id = $(e.target).attr("href")

        $(id).addClass("open")

        $(id).find('.close').click(function(e) {
            e.preventDefault()
            $(e.target).parent().removeClass(".open")
        });

    })

});

</script>

Here is my Close button in HTML:

<button class="close icon-close"></button>

Answer №1

It seems that using parent() may not direct you to the correct level. Instead, consider removing the .open class from the element where you initially added it, like so: $(id):

$(".modal-trigger").click(function(e) {
    e.preventDefault();

    var id = $(e.target).attr("href");
    $(id).addClass("open");

    $(id).find('.close').click(function(e) {
        e.preventDefault();
        $(id).removeClass("open");
        $(this).off();
    });
});

Furthermore, it is advisable to unbind the click event from the close button to prevent multiple bindings.

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

Transmit data or communications to a webpage while a script is performing operations (Django 4)

Currently, in my Python script with Django, when a user submits a file, I have a series of tasks that are processed which can take several minutes. While the user is waiting, a loading screen in JavaScript is displayed and updates are printed in the consol ...

How to transform HTML input type with identical names into key-value pairs using jQuery

When the addmorefield button is clicked on this form, two more fields with the same name are appended: <form method="post" id="sampleform" action="#"> <div class="input_fields" style="text-align:center"> <input type="text" name="first_name ...

The scroll functionality does not seem to be functioning as intended on mobile devices when

Hey there, I'm currently working on making my navbar sticky and applying it when the page is scrolled. The code I have works flawlessly on desktop, but unfortunately, it doesn't seem to work on the mobile version. Any suggestions? window.addE ...

Begin expanding new circles in jQuery from the exact location where the previous ones ended

A captivating circle animation unfolds before your eyes, featuring dark blue circles that materialize at random points and gradually expand. As these expanding circles cover more than half of the screen, their color shifts to a lighter shade of blue. Exper ...

The webmethod is not being triggered by Ajax

I'm currently working on troubleshooting the loadResources function by placing it behind a button call. The function is being called, however, the ajax always fails (resulting in an alert saying "loading of Engineers failed!") and I am unable to pinpo ...

Is there a way for me to compare a string A1 with a value A2 located in index 0 within an array of values?

In my current task, I am attempting to compare two sets of strings: A1 must match A2 when selected. However, if A1 is chosen along with B1, C1, or D1, the comparison should return false. Similarly, selecting B1 should result in a match with only B2, while ...

React Bootstrap problem

Having trouble with the grid system - I can't seem to make it work. Here's my code: import React from "react"; import {Col, Row} from "react-bootstrap"; const Home = () => { return ( <Row className=&quo ...

What is the best way to send a parameter in pug?

My template with URL parameter is not functioning properly doctype html html head block head meta(charset="utf-8") meta(name="viewport", content="width=device-width") meta(http-equiv="X-UA-Compatib ...

Having problems with CakePHP validation in the view?

Welcome to my first post on this platform! I've been searching for a solution but haven't found anything that works for me yet. I'm relatively new to PHP and CakePHP. Yesterday, I managed to get everything set up without any issues and was ...

Auto-closing dropdown menus in the navbar of a Shiny app with Bootstrap

Is there a way to customize the behavior of a shiny navbarMenu so that when I click inside or outside it, the dropdown does not automatically hide? I have seen mentions of using data-bs-auto-close="false" in the Bootstrap documentation, has anyon ...

Attempting to use the getCurrentUrl() function to retrieve the current URL and subsequently opening it in a new tab

I am attempting to retrieve a URL and open it in 3 new tabs, but encountering errors in the process: browser.getCurrentUrl().then(url => { browser.actions().keyDown(protractor.Key.CONTROL).sendKeys('t').perform(); browser.sleep ...

The function initiates without delay upon meeting the specified condition

I am looking to trigger a function automatically upon certain dynamically changing conditions in my JavaScript code. I attempted using the document.body.onload method, but it did not work as expected. document.body.onload = myFunction() function myFunct ...

Refresh the dataTable once all external data has been successfully fetched

I am struggling to find the correct method for reloading a datatable. Here is my current process: Retrieve data through ajax for specific columns Generate a table with the fetched data Initialize the datatable for the table Make a new ajax request using ...

Is it possible to manipulate videos embedded in an iframe using javascript?

It's common knowledge that JavaScript commands from Google can be used to control YouTube videos, while Vimeo provides its own JavaScript commands for their videos. Both videos are typically embedded within 'iframes' on websites. I'm ...

Displaying the Yii form directly on the page upon loading, rather than enclosed within a jQuery dialog box

After studying this yii wiki page, I encountered an issue where the form is supposed to appear within a jQuery dialog box, but it opens immediately when the page loads instead. Upon further investigation, I discovered that removing the success callback fr ...

I'm having trouble identifying the error in my Vue component that uses recursion. How can I pinpoint the

Currently, I am in the process of creating a questionnaire, and the JavaScript file containing the questions is a lengthy 4500 lines. Unfortunately, I am encountering a type error that is proving difficult to pinpoint within the code. Here is a link to the ...

What could be causing the presence of white space between div elements in every browser except for Chrome?

My HTML Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" ...

Creating a reusable Angular directive that encapsulates a jQuery lightbox functionality

Currently, I am attempting to integrate a customized jquery lightbox within an Angular directive. My goal is to create the directive in such a way that it simplifies the usage of the lightbox without modifying the original jquery code, as it is also used i ...

Navigating through nested JSON objects using JavaScript

Trying to access and display a nested JSON object within the console. This is the JSON data: { "currentUser": { "image": { "png": "./images/avatars/image-juliusomo.png", "webp": "./images/avatars/image-juliusomo.webp" }, "us ...

The Node.js JSON string displays as "[object Object]" in the output

Front End // js / jquery var content = { info : 'this is info', extra : 'more info' } $.ajax({ type: 'POST', url: '/tosave', data: content }); Node // app.js app.post('/tosave', funct ...