What is the best way to darken the background when an alert is displayed and disable the dimming effect when the alert is closed?

Here's the JavaScript snippet I'm using:

reset.addEventListener("click", function(){
    document.querySelector("#body").classList.add("darkenPage");
    myReset();
    alert("Reset Successful!!");
    document.querySelector("#body").classList.remove("darkenPage");
});

And this is the corresponding CSS:

.darkenPage {
    background: rgba(0, 0, 0, 0.5);
}

Despite trying a CSS snippet I found online, the background doesn't get darker. The browser I'm using is Chrome.

.darkenPage {
    height: 100%;
    width: 100%;
    position:fixed;
    top: 0px;
    left: 0px;
    background-color: rgb(0, 0, 0);
}

Answer №1

Why not give this a shot: Modify the default alert() function and utilize the same classes to customize it as per your needs.

This way, you can easily trigger the alert wherever required, causing the page to dim.

var originalAlert = window.alert;
window.alert = function(args) {
  document.querySelector("html").classList.add("darkenPage");
  setTimeout(function() {
    originalAlert(args);
    document.querySelector("html").classList.remove("darkenPage");
  });

}
body {
  background-color: white;
  margin: 0px;
}

html.darkenPage {
  background-color: black;
}

html.darkenPage body {
  opacity: 0.5;
}
Content<br>Content<br>Content<br><br>
<button onclick="alert('Hello World')">Alert</button>
<br><br><br> Content
<br>Content<br>Content<br>Content<br>Content<br>Content<br>Content<br>Content<br>Content<br>Content<br>Content<br>Content<br>Content<br>Content<br>Content<br>

Answer №2

To achieve the desired outcome, simply follow these steps in the correct sequence:

reset.addEventListener("click", function(){
    // Apply dark overlay to the page
    document.querySelector("#body").classList.add("darkenPage");

    // Display an alert box (this temporarily halts Javascript execution)
    alert("Reset Successful!!");

    // Remove the dark overlay from the page
    document.querySelector("#body").classList.remove("darkenPage");
});

If the above method does not produce the expected result and you wish to ensure that the CSS takes effect first, consider introducing a slight delay before displaying the alert using setTimeout.

reset.addEventListener("click", function(){
    // Apply dark overlay to the page
    document.querySelector("#body").classList.add("darkenPage");

    // Ensure the dark overlay is rendered before showing the alert
    setTimeout(function(){
        // Display an alert box (this pauses javascript execution)
        alert("Reset Successful!!");

        // Remove the dark overlay from the page
        document.querySelector("#body").classList.remove("darkenPage");
    }, 0);
});

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

Obtaining data from a callback function within a NodeJS application

There is a function in my code that performs a backend call to retrieve an array of names. The function looks something like this: module.exports.getTxnList = function(index, callback) { ....some operations ..... .... callback(null, respon ...

The JavaScript array slideshow is experiencing some glitches in its transition

After diving into JavaScript recently, I managed to center a div and make it fullscreen as the window resizes. However, things got tricky when I added a script I found online to create an image transition using an array. Unfortunately, these scripts are co ...

Is there a way to stop the Firebase web client from altering the error message generated by an https.onRequest function?

I am facing an issue where I cannot retrieve the original message I sent from an "https.onRequest" function in Firebase. The firebase client is rewriting the message based on the error code, making it difficult for me to recover the originally sent body or ...

What is the best approach to determine the value of a textbox in an array for each row of

I am trying to display the total sum of values for each row in a data array. There are 5 rows of data, and I need to calculate the results for each one. Can someone assist me in solving this? function calculateTotalValue(){ var total = (document.get ...

Discovering more about this topic

Looking for a way to create an expandable box that enlarges when "read more" is clicked, revealing text below it. And also looking to add a button that closes the expanded text back up. Experimented with the toggletext JavaScript command, as found on this ...

Disable the movement and dragging functionality of the scroll feature in Google Maps using React

I have a map.jsx file in my React application that contains the code below: import React from 'react'; import GoogleMapReact from 'google-map-react'; import './map.css'; const Map = ({ location, zoomLevel }) => ( <d ...

Limit the input to a maximum number of characters

I am in need of input boxes that only accept hexadecimal characters and I also want to set a maximum length for the input. Although I have successfully implemented accepting hex characters only, I am facing an issue when pasting a string - the invalid cha ...

AngularJS JSON data computation

As I delve into learning angularjs (not 2), one of the challenges I face is calculating the total amount for a customer order. The data I'm working with is structured as follows: var clients = [ { id: 1, jo ...

Avoiding memory leaks when using three.js with a large number of shapes

My code is devouring memory at an alarming rate and ultimately crashing. After some investigation, I've determined that the issue seems to be related to the torus generation/removal portion of the code. Despite efforts to manage the scene array and t ...

Using Telerik Grid in MVC to access the object that is passed to ClientEvent functions on the Javascript side

Here's a challenging question I have. I'm working with a Telerik Grid that has some ClientSide Events: .ClientEvents(events => events .OnDataBinding("SetAjaxParameter") ) Within the SetAjaxParameter function, I am setting parameters for ...

Incorporating words into the core of a pie chart: Highcharts

Is there a way to display the total value in the center of a pie chart? I've attempted some methods but haven't been successful. The goal is to show the sum of all y values. Input export const data = [ { y: 15, name: "Category 1&q ...

Error encountered when using the $.post function

$(".eventer button[name=unique]").click(function() { console.log('button clicked'); thisBtn = $(this); parent = $(this).parent(); num = parent.data('num'); id = parent.data('id'); if(typeof num ! ...

What is the best way to insert a Button within a Tab while ensuring that the indicator remains in the appropriate tab?

Is it possible to include a button inside a Tab? When I click on "Homepage", the tab switches correctly with the indicator showing on the right tab. However, when I click on "Profile", the indicator moves to the logout button instead. How can I fix this ...

Oops! You're trying to perform actions that must be plain objects. If you need to handle async actions

I have been struggling to implement Redux and pass an object into the store. Although I am able to fetch the correct object when I call the action, the store remains unchanged when I use store.dispatch(). It still only reflects the initial state. I've ...

Using Javascript's Speech Recognition to activate a button

I am new to using JavaScript Speech Recognition and decided to work with the Annyang library. My goal is to automatically trigger the "show date" button when the user says 'hello', without actually clicking the button. However, I've been fac ...

Utilize fetch API in React to streamline API responses by filtering out specific fields

I have received an API response with various fields, but I only need to extract the description and placeLocation. results: [{placeId: "BHLLC", placeLocation: "BUFR", locationType: "BUFR",…},…] 0: {placeId: "BHLL ...

Client-side image upload problem in Next.js API routes

I've been banging my head against this bug for a couple of hours now and I just can't seem to figure out the reason behind it. The issue is with an API route I'm trying to set up in next.js where I need to modify an image and then upload it ...

Bootstrap 4 modal experiencing issues with the form end tag functionality

Currently, I am facing an issue while attempting to incorporate a confirmation delete feature using a Bootstrap 4 modal in my Laravel project. The problem arises when the modal is opened, and the submit button fails to function. Upon inspecting the browser ...

What is the best way to retrieve classes from arrays and apply styling to them using javascript?

Imagine having 3 unique classes: alpha, beta, and gamma. Each class contains 3 individual div elements like so: <div class="alpha"></div> <div class="alpha"></div> <div class="alpha"></div> <div class="beta">< ...

What could be causing the issue with the .toLocaleTimeString method not properly converting time zones?

I have been attempting to convert timezones based on the current time, but I haven't had success. I tried switching from using date.toLocaleTimeString to date.toLocaleString, but it didn't work. I also tried changing the timezone from America/Den ...