Ways to adjust the visibility of a div element multiple times using javascript and css

I implemented a popup feature in my application:

<div id="modal"></div>

let modal = document.getElementById('modal')
modal.innerHTML = `
            <button class="close-button" onclick="close_modal()">Close</button>
        `

#modal{
        width: 30em;
        height: 24em;
        overflow: hidden;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        visibility: hidden;
    }

Upon clicking a specific button, a function is triggered that contains modal.classList.add('open-modal').

.open-modal{
        visibility: visible !important;
    }

The close_modal function looks like this:

function close_modal(){
        modal.classList.add('close-modal')
    }

Here's the CSS for handling modal closing:

.close-modal{
        visibility: hidden !important;
    }

Initially, the popup functionality works correctly as I can open and close it. However, on attempting to open it for the second time, the popup does not appear. What could be causing this issue and how can it be resolved?

Answer №1

When you introduce a new class, it is important to remove the existing class from the element's classlist. Otherwise, having both classes at the same time can cause issues with functionality, such as in the case of modals.

For example:

function toggleVisibility(modal) {
 if(modal.classList.contains('show')) {
   modal.classList.remove('show');
   modal.classlist.add('hide');
 } else {
    modal.classList.remove('hide');
    modal.classList.add('show');
 } 
} 
 

Answer №2

For those who are looking to implement modals, utilizing HTML's <dialog> element is highly recommended (Additionally, refer to HTMLDialogElement). MDN provides a comprehensive tutorial on this topic.

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

HTML and JQuery Image Slide Show

Help! I'm struggling with this image slider that's meant to showcase images fading in and out every 5 seconds. Being a beginner in coding, I could really use some assistance with getting it to work properly. Currently, I'm stuck on the firs ...

Utilize jQuery to dynamically add or remove elements by referencing specific HTML elements

My goal is to dynamically add an element to a dropdown menu and then remove it after selection. I initially attempted to define the htmlElement reference in this way: (Unfortunately, this approach did not work as expected) var selectAnOption = "<option ...

Safari experiencing hang after successful CORS OPTIONS request

Safari (10 - OSX El Capitan) Issue with CORS Encountering a problem with CORS while performing a POST request from an AngularJS front-end to a Laravel back-end. In Chrome and Firefox, both OPTIONS and POST requests return http status 200 OK In Safari 10 ...

Display data in a template upon receiving a response from the server

Hello, I am currently in the process of developing my very first Angular application and could use some assistance. Specifically, I am working on a component that serves as an image search box. When a user inputs a search query, a request is sent to an API ...

What is the best way to update a collection item while maintaining non-existing values in the query?

Consider this straightforward example, where an item is saved as: { "test": { "a1": "a1" } } When collection.updateOne is called with $set and the following object: await collection.updateOne(doc, {$set: {"test&q ...

What is the best way to concatenate two different values in React JSX using the "+" operator?

I have a situation where I need to take a value from an input, add 10% to it, and display the result. For example, if a person inputs 1000, the 10% of 1000 is 100, so the total result should be 1100. Currently, when I use the "+" operator, it concatenates ...

What steps can I take to modify my webpage, like a dashboard, on the internet?

Whenever I click on a menu item in the sidebar of my HTML file, I want only the body section to change without affecting the navigation or sidebar content. For instance, if I select the "Coding Convention" menu in the sidebar, I would like the page to swi ...

incorrect calculation of date difference using momentjs

Currently utilizing countdown.js for a project where I need to add 60 days to a date fetched from the database. Successfully implemented this in the targetDay variable and it's functioning properly. However, when attempting to calculate this date fro ...

Exploring JSON array handling with jquery

Here is the JSON data I am working with: { "category": { "category_identification": "1", "category_name": "C1", "image_one": "1.PNG", "image_two": "1_.PNG", "logo": "LOGO_1.PNG", "category_description": "DESCRIPTION" }, "responseCo ...

Troubleshooting: Why Won't My Basic JQuery POST Request Work?

Can someone help me figure out how to use JQuery to send a POST request and display the data in a PHP file? Here is the HTML file: <html> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> ...

Looking to incorporate AAD calling functionality in a React and Node application by utilizing the Graph API for communication/calls

As a newcomer to Microsoft Azure and its services, I recently registered an application with Azure. However, when attempting to integrate a call feature in my Web App using the graph API '/communication/calls', I encountered the following error m ...

Guide to highlighting input field text using Angular

I've set up an angular page that includes an input field within its template. My goal is to highlight the text in the input field when a specific function is triggered. When I refer to "highlighting the text," I mean (check out the image below) https ...

Create a hyperlink field that relates to many values

Looking to update categories within the API; my category and books models are connected using a many-to-many relationship. Code: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id&apo ...

Can I programmatically retrieve a comprehensive list of all global HTML attributes available?

Exploring the extensive list of global HTML attributes can be overwhelming, especially when considering how it continues to evolve with browser updates. Can JavaScript be leveraged to dynamically generate a complete list of these attributes without the ne ...

How can you center the body of a webpage while using the zoom in and zoom out features in HTML5?

What is the best way to maintain body alignment while zooming in and out on a web page? <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> body { font-family: 'Merriweather Sans&apos ...

How can a parameter be added to a query string only when there is a value present in a textbox using JavaScript?

Hello everyone, I am looking to add parameters to a URL only if the search text box value is different from the default. I have three search text boxes and I want to include them in the URL. Below is my code snippet: $("#search-btn").click(function (e) { ...

Is there a way for my React application to detect changes in an npm package?

I am currently customizing an npm package for my application, but I am facing issues with it not being detected when starting my development server. Previously, I was able to resolve this by removing the library and reinstalling it, followed by replacing t ...

Guide to verifying the presence of cookies by name in the browser and granting access to the specific page accordingly

In the process of developing an authorization system with Express, Node, and MySQL, I decided to utilize JWT tokens for user authorization. After successfully storing the JWT token in cookies, my next step is to verify if the token exists in the cookie b ...

What are the best scenarios for utilizing the Bootstrap class “.embed-responsive-item”?

I'm hoping for some help understanding the purpose of the ".embed-responsive-item" class in the code snippet below (Bootstrap code for responsive iframes, videos, etc.). It seems redundant to apply this class to the iframe element when it works just f ...

Is it possible to use an angular expression as the ng-click function?

I have been searching everywhere for the answer to this question. Within my code, there is an angular object called column.addOnParams. This object includes a child element named rowClick, which can be accessed using column.addOnParams.rowClick. The val ...