Trouble encountered when attempting to programmatically dismiss a modal following a confirmation alert

When the user clicks on the close button, I want to display a confirmation alert to confirm if they really want to close the modal. However, I have encountered an issue with hiding the modal and preventing it from being hidden in the two solutions that I have tried.

Here is how the modal is set up (excerpt of code)

<div class="modal fade" id="viewTicketModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="vertical-alignment-helper">
            <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable vertical-align-center">
                <div class="modal-content">
                    <div class="modal-header">

This is how the modal is shown

<a><i class="voyager-eye viewBtn" data-toggle="modal" data-target="#viewTicketModal"/></i></a>

Solution Attempt 1 (Closing modal using hide function)

This is how the modal is hidden

<button type="button" class="btn cancelModalBtnColor" onclick="closeTicketDetailsModal(event)">Close</button>

The function to close the modal

   function closeTicketDetailsModal(e){
        if(enteredEditModeBefore){
            let text = "Proceeding will discard all changes that you may have made\nDo you wish to continue?";
            e.preventDefault();
            if (confirm(text) == true) {
                console.log("Forgoing Changes!");
                $('#viewTicketModal').modal('hide');
                return;
            } else {
                console.log("You still want your changes!");
                return false;
            }
        }
        else{
            console.log("HIDING MODAL");
            $('#viewTicketModal').modal('hide');
            return;
        }
    }

Issue with this solution

While it successfully hides the modal, it prevents the modal from being displayed when the triggering button is clicked again.

Solution Attempt 2 (Closing modal by using data-dismiss)

This is how the modal is hidden

<button type="button" class="btn cancelModalBtnColor" data-dismiss="modal">Close</button>

The function to close the modal

$('#viewTicketModal').on('hide.bs.modal', function(e) {
        e.preventDefault();
        return false;
    });

Issue with this solution

Despite trying to prevent the modal from being dismissed, it doesn't work as expected.

What could be going wrong?

Answer №1

Understanding code can be challenging without a central working example. However, I will demonstrate the use of the "event delegation" technique to allow multiple buttons to perform the same actions. Additionally, I'll showcase the functionality of modal windows and modal overlays as mentioned by @vanowm.

document.addEventListener("DOMContentLoaded",()=>{
            let popup = document.querySelector(".popup"),
                overlay = document.querySelector(".overlay")

            document.addEventListener("click",(ev)=>{
                if(ev.target.closest(".js-call-popup")){
                    popup.classList.add("active")
                    overlay.classList.add("active")
                }

                if(ev.target.closest(".js-hide-popup")){
                    popup.classList.remove("active")
                    overlay.classList.remove("active")
                }
            })
        })
button{
  background-color: transparent;
  border: none;
  cursor: pointer;
}
.site{
    width: 100vw;
    height: 100vh;
    background-color: #d3d3d3;
}
.btn{
    padding: 5px 15px;
    background-color: #e4cff3;
    border: 1px solid purple;
    border-radius: 8px;
}
.btn:hover{
    box-shadow: rgba(100, 100, 111, 0.2) 0px 7px 29px 0px;
}
/*  popup   */
.popup{
    position: fixed;
    width: 30vw;
    background-color: #fff;
    top: 50vh;
    left: 50vw;
    transform: translate3d(-50%, -40%, 0) scale(.8);
    padding: 2vw 3vw;
    border-radius: 16px;
    box-shadow: rgba(17, 12, 46, 0.15) 0px 48px 100px 0px;
    opacity: 0;
    visibility: hidden;
    transition: .3s opacity, .3s visibility, .3s transform;
}
.popup.active{
    transform: translate3d(-50%, -50%, 0) scale(1);
    opacity: 1;
    visibility: visible;
}
.popup__close-btn{
    position: absolute;
    top:  1vw;
    right:  1.4vw;
}
.popup__confirm-btn-cont{
    text-align: center;
    margin-top: 2vw;
}
.popup__confirm-btn{
    font-size: 20px;
    text-decoration: underline;
    text-decoration-color: red;
}
/* overlay */
.overlay{
    position: fixed;
    width: 100vw;
    height: 100vh;
    top: 0;
    left: 0;
    background-color: #000;
    opacity: 0;
    visibility: hidden;
    transition: .3s opacity, .3s visibility;
}
.overlay.active{
    opacity: .4;
    visibility: visible;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modal window demonstration</title>
</head>
<body>
    <main class="site">
        <button class="btn js-call-popup">Call popup</button>
        <button class="btn">Show product</button>

    </main>

    <div class="overlay"></div>
    <div class="popup">
        <button class="popup__close-btn js-hide-popup">
            &#x274C;
        </button>
        <p class="popup__message">Lorem ipsum dolor sit, amet consectetur, adipisicing elit. Dolores in sed consectetur error adipisci quisquam sapiente sint accusantium, atque commodi.</p>
        <div class="popup__confirm-btn-cont">
            <button class="popup__confirm-btn js-hide-popup">Accept</button>
        </div>
    </div></td>
     </body>
     </html>
The beauty of this code lies in its modernity, functionality, and absence of reliance on jQuery. In 2022, staying up-to-date with modern technological practices is essential.

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

An issue has arisen where I encounter the error message: 'TypeError: callback is not a function', even though the function appears to be continuing to run successfully

Encountering an error message 'TypeError: callback is not a function' while attempting to execute a particular function. Here is the code snippet in question: const api = require('axios'); getData(printData); async function getData ...

Error: webpack-cli encountered an unrecognized argument along with a syntax error

Hello, I am currently delving into the realm of prestashop theme development. After setting up my local environment successfully, everything seems to be working fine. My next step is to create a new theme based on the classic default theme. Upon navigat ...

Switching background images with Javascript through hovering

I am currently working on implementing a background changer feature from removed after edits into my personal blog, which is only stored on my local computer and not uploaded to the internet. However, I am unsure of what JavaScript code I need to achieve t ...

Import the information into a td tag's data-label property

I have implemented a responsive table design that collapses for smaller screens and displays the table header before each cell. body { font-family: "Open Sans", sans-serif; line-height: 1.25; } table { border: 1px solid #ccc; border-collapse: co ...

Searching for two fields of an object in Angular using ng-repeat

Let's imagine we have this array $scope.myArr = [{ name: 'Marc Rasmussen', phone: 239470192, title: 'It Dude', description: 'Hello my name is Marc i am testing the fact that i can search for two fields in an o ...

Tips for creating a high-performing algorithm to locate a specific word within a JSON file

I am in the process of creating a word game that involves users typing letters on a board to form meaningful words. If the typed word matches any word in a JSON file, the user earns a point. I have successfully implemented the basic functionalities of the ...

Achieving Perfect Alignment in Dreamweaver: Crafting a Stylish Header Container

Hello, I am currently working on a Dreamweaver site and have created a CSS style sheet within my template that includes a div tag called #HeaderBox. My goal is to make this box 40% of the screen's size, with specific pixel dimensions if necessary. I a ...

CSS tooltip box with embedded HTML for interactive content display

After doing some research, I came across a code that almost does what I need. The code allows me to hover over text and display a tooltip box with HTML content such as images and links. It worked perfectly with jQuery, but the challenge is that eBay doesn ...

Issue with .css() function failing to apply width attribute

My goal is to shift the width of a div as specific images load in my application. I have tried reading the div's current width, adding 128 to it, and then using the .css() function to update the div's new width. However, I have encountered an iss ...

selenium tutorial: accessing checkbox state for frost

There is a frost checkbox that I have defined as follows: <div id="protocol_input" class="ember-view frost-checkbox small"> <input id="protocol_input" class="input ember-view" type="checkbox"> <label class="label" tabindex="0" for="proto ...

Coinciding titles within flot pie chart

I am facing an issue with overlapping labels in my pie charts generated using jquery flot, especially when the chart pieces are very small. Is there a recommended solution to prevent this overlap? Below is the configuration for my current pie chart: ser ...

What is the best way to retrieve every single element stored in an Object?

On a particular page, users can view the detailed information of their loans. I have implemented a decorator that retrieves values using the get() method. Specifically, there is a section for partial repayments which displays individual payment items, as d ...

how to execute Vue-Js method just one time

Is there a way to add a random number (ranging from 0 to the price of an item) to one of the data properties in Vue.js, but only once when the page is initially loaded? I am unable to use mounted and computed because I need to pass a parameter to the funct ...

What is the process for refreshing the vis.js function to clear or reset the selection of a node or edge?

Begin by checking out this resolved issue. Building upon that, I am encountering an issue when trying to utilize the selectNode or selectEdge function in the same page and JS file. For some reason, the function is unresponsive when clicked after the previo ...

Using Angular: How to reference the same ng-template with a component in a single HTML file without making a copy

Currently, I am facing a challenge while developing a web application using Angular. My task involves creating a search form with multiple fields as a component. Below is the code snippet for this component: <ng-template #filter> <app-articles-f ...

Resetting radio buttons in Firefox when the cache is refreshed

(I previously posted a question on StackOverflow (https://stackoverflow.com/questions/1544479/checking-if-radio-buttons-are-checked-in-firefox), but this is a follow-up that delves into a different issue. I believe this warrants its own discussion separate ...

Several radial progress charts in JavaScript

While attempting to recreate and update this chart, I successfully created a separate chart but encountered difficulties with achieving the second progress. The secondary chart <div id="radial-progress-vha"> <div class="circle-vha ...

Make sure to always select the alternative option in ajax

I am trying to create a condition where if the value of id=type_investor is either 1 or 6, an email should be sent using a different controller. Here is my complete code: function (isConfirm) { if (!isConfirm) return; $.ajax({ ...

Error: Failed to parse the given color specification

My chrome extension is showing an error message: Unchecked runtime.lastError: The color specification could not be parsed. This error seems to be in the popup.html: 1 -> <! DOCTYPE html> line. Can anyone explain what this means and how to fix ...

Tips on incorporating a plus symbol (+) into a list using the <li> tag?

Is it possible to use a plus sign as the list style instead of Disc or Circle in <li> elements? li {list-style: disc...} ...