`The universal functionality of body background blur is inconsistent and needs improvement.`

I've developed a modal that blurs the background when the modal window is opened. It's functioning flawlessly with one set of HTML codes, but encountering issues with another set of HTML codes (which seems odd considering the identical CSS and JavaScript being used).

The issue is that in the non-working HTML code, when the modal window is opened, both the modal window and the background become blurred and remain that way indefinitely... while in the other HTML code, it works perfectly fine. Only the background gets blurred when the modal is open and returns to normal when the window is closed - everything works as expected there.

Firstly, I'll provide the codes that are working well together - HTML, CSS, and JavaScript

At the end of this post, I will include a link to a different HTML code where this functionality doesn't seem to work properly for some unknown reason (so anyone can easily compare and debug the issue).

JavaScript

// JavaScript code here
// ...

CSS

Working HTML Code

Hopefully someone can pinpoint the cause of this issue

JSBIN with the working HTML code here

JSBIN with the non-working HTML code here

Note: The JavaScript and CSS codes are exactly the same; the only difference lies in the HTML.

Answer №1

Your code utilizes the blur effect on all immediate children of elements with the class .open (.open > *).

However, there is a special rule for the .modal class that resets the blur to blur(0px), overriding the earlier rule.

To ensure it works correctly, the .modal element must be a direct child of the element receiving the .open class. This is as you have in your first code snippet, but not in the second.

In the second example, since the .modal is not a direct child of this element, the parent of .modal will receive the filter. By that time, it's too late to remove it from your .modal element.

.open > * {
  filter: blur(5px);
}
.modal {
  filter: none;
}
<div class="open">
  <div>
    A direct Child, not .modal (and thus blurred).
    <p> Some inner content, still not .modal </p>
   </div>
  <div>
    A direct Child, not .modal (and thus blurred).
    <p class="modal"> Some inner content. This time .modal but blurred by its parent anyway...</p>
  </div>
  <div class="modal">
    A direct Child, .modal (and thus not blurred).
    <p class="modal"> Some inner content. not blurred either</p>
  </div>

</div>

Ensure that the document structure maintains the relationship where .modal elements are direct children of the .open element and apply the .open class to a common parent (e.g., <body>). Another update required is on the line

this.parentElement.nodeName == 'BODY'
because this refers to the <a> which is now a child of <section>. You need to adjust it to either
this.parentElement.nodeName == 'SECTION'
or
this.parentElement.nodeName == 'BODY'
:

let open_modals = [];

$(function() {

  var btn = document.querySelectorAll(".modal-button");
  var modals = document.querySelectorAll('.modal');
  var spans = document.getElementsByClassName("close");

  for (var i = 0; i < btn.length; i++) {
    btn[i].onclick = function(e) {
      e.preventDefault();
      modal = document.querySelector(e.target.getAttribute("href"));
      modal.style.display = "block";
      open_modals.push(modal.id);
      document.body.style.overflow = "hidden";

      if (this.parentElement.parentElement.nodeName == 'BODY') {
        document.body.classList.add("open");
      } else {
        this.parentElement.parentElement.parentElement.classList.add("open");
      }
    }
  }

  function checkRenableScroll() {
    if (!open_modals.length) {
      document.body.style.overflow = "scroll";
    }
  }

  for (var i = 0; i < spans.length; i++) {
    spans[i].onclick = function() {
      // close modal logic
    };
  }

  window.onclick = function(event) {
    // close modal logic when clicking outside
  }
})
@import url('https://fonts.googleapis.com/css?family=Quicksand&display=swap');

/* The Modal (background) */
// CSS styles here

.modal {
  // more CSS styles
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
// HTML code snippets here

I also simplified some parts using jQuery functions for easier handling. Additionally, I made changes to streamline the process based on your existing setup. Feel free to adapt and modify further for your specific needs.

Answer №2

Resolved this issue by updating the code snippet. Visit the link here

Make the following replacement:

document.body.classList.add("open");

Replace with:

document.getElementById("product").classList.add("open");

Also, replace

document.body.classList.remove("open");

with:

document.getElementById("product").classList.remove("open");

Update in IF function as follows:

Initially,

if (this.parentElement.nodeName == 'BODY') {
        document.body.classList.add("open");
      } else {
        this.parentElement.parentElement.parentElement.classList.add("open");
      }

Change it to:

if(this.parentElement.matches('#product')){
           document.getElementById("product").classList.add("open");
         } else{
           this.parentElement.parentElement.parentElement.classList.add("open");
         } 

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

Crafting dynamic parameters in the Express router - A step-by-step guide!

Original Code Example: const express = require('express'); const router = express.Router(); router.get('/data/:d1/:d2/:d3', require('../apifoo').foo); Route: /data/:d1/:d2/:d3 Path: /data/1/2/3 req.params : 'd1' : ...

Stop YouTube Video in SlickJS Carousel, Remove Placeholder Image Forever

Feel free to check out the CodePen example: http://codepen.io/frankDraws/pen/RWgBBw Overview: This CodePen features an ad with a video carousel that utilizes SlickJS. There are a total of 3 YouTube videos included in the carousel, with the SlickJS ' ...

Nuxt and Webpack error: Failed to parse module - Unexpected character (1:0)

https://i.sstatic.net/ope8z.png I am working on a Vue carousel component and my goal is to dynamically generate a list of .png files from the static folder. I have followed instructions from here and also from here. Below is an excerpt from my component: ...

Unexpected error in boot.ts file in Angular 2

I am currently experimenting with various folder arrangements for Angular 2. When attempting to launch a local server, I encounter the following error: Uncaught SyntaxError: Unexpected token < Evaluating http://localhost:3000/prod/app/TypeScript/bo ...

Display a new div with its content every 5th item

I am currently working with a Smarty template that contains the following code output: Check out my other question on Stackoverflow My problem lies in the fact that the provided code does not repeat the inserted HTML after every 5 elements... Could some ...

What is the best way to determine which id has been clicked using jQuery?

Can someone help me figure out how to determine which button has been clicked using jQuery? Here is the HTML code I am working with: <div class="row"> <div class="col-md-6"> <div class="well " id="option_a"> </div& ...

Utilizing a Clear Button to Reset Specific Fields in a Form Without Clearing the Entire Form

I am currently working on a multipart form that includes 'Name', 'Email', and 'Phone Number' fields. It's important to note that the phone number field is actually composed of 10 individual single-digit fields. To enhan ...

Guide: Displaying components within a Vue2 string

Within my Vue2 component, I am working with a string that looks something like this: <template> <div><h1>Hello World</h1> <div v-html="testString"></div> </div> </template> <script> exp ...

I'm curious about how I can determine the reason why my badge is not accepting HTML tags in its tooltip

My goal is to integrate a bootstrap badge-alert with an HTML tooltip. I am following the example provided at https://getbootstrap.com/docs/4.3/components/tooltips/ Despite my efforts, when using the code snippet below, the tooltip appears but the HTML tag ...

Using jQuery's append function, you can dynamically generate a dropdown list in PHP code

One of the challenges I'm facing is related to a button that, when clicked by a user, should append a dropdown list to the HTML. I am using PHP to retrieve data from a database and fill the dropdown list with it. However, upon trying out this code, it ...

Is it accurate to consider all JavaScript code and variables as inherent properties of an execution context?

It's worth considering that everything in JS code can be viewed as a property of an execution context, whether it's a global, function, or eval() execution context. Why is this the case? Each execution context has its own unique lexical and v ...

The Ajax call is failing to trigger the success function

Can anyone assist me? My success function isn't working properly. The beforesend is functioning correctly and I've verified the variable s. It has a true value before the ajax call, so all validations are correct. Please take a look... function ...

Each time I refresh the page, the user data disappears and I have to login

Hello there, I am currently utilizing Express for backend authentication and these are the sign in functions/controllers implemented on the front end. export const signInUser = async credentials => { console.log('this is for the signInUser&apos ...

Unable to define a range for the hr element using the nth-of-type selector

Why isn't the hr element from the 1st to the 3rd hour red as specified in the CSS code below? hr:nth-of-type(n+1):nth-of-type(-n+3){ background:red; } <!DOCTYPE html> <html> <head> </head> <body> <hr /> <p>T ...

"Everything is running smoothly on one REST endpoint, but the other one is throwing a CORS error

I am currently working on a project that involves a React client app and a Django server app. The React app is running on port 9997 and the server API is on port 9763. While the frontend is able to access some APIs successfully, there are some APIs that ar ...

Using TypeScript with React: Initializing State in the Constructor

Within my TypeScript React App, I have a long form that needs to dynamically hide/show or enable/disable elements based on the value of the status. export interface IState { Status: string; DisableBasicForm: boolean; DisableFeedbackCtrl: boolean; ...

Steps to keep the gridlines in the chart from moving

Take a look at the example provided in the following link: Labeling the axis with alphanumeric characters. In this particular instance, the gridlines adjust dynamically based on the coordinate values. How can we modify this so that the chart remains static ...

I am facing an issue in my Vue Project where the CSS does not recognize URLs enclosed in quotes

When attempting to pass over a quoted URL to background-image or cursor, I'm facing an issue where the file simply doesn't load. I am currently working with Vue and have installed the following libraries: Vuetify, SASS, SASS-Loader, and Node-S ...

Discover the nearest locations along your route using Google Maps API V3's boundary feature

I am trying to find locations that fall within a specific boundary along a route. I need the results to be ordered by distance from the route. I attempted to use rankby=distance in my Nearby Search request, but it didn't work because it requires a lo ...

Maximizing the power of Webpack alongside Google Maps API

I have been using Webpack along with the html-webpack-plugin to compile all my static files. However, I am facing an issue when integrating it with the Google Maps API. Here is the code snippet: var map; function initMap() { map = new google.maps.Map(d ...