Unlock the power of overlay masks with just CSS and JavaScript on any webpage

After experimenting with different types of masks, I wanted to be able to dynamically create a CSS class and apply it after the DOM had loaded in order to achieve an overlay mask effect. However, my initial attempt was unsuccessful:

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.overlay-loader-mobile-edition { height: 100%; width: 100%; position: fixed !important; z-index: 5000000 !important;left: 0!important;background-color: rgb(0,0,0);background-color: rgba(0,0,0,0.9);overflow-x:hidden;transition: 0.5s;}';
document.getElementsByTagName('head')[0].appendChild(style);
document.body.className = 'overlay-loader-mobile-edition';

I found no success using this method. When testing on Google and running the same command in console, the results were not as expected:

https://i.sstatic.net/iGRSj.jpg

In my research, I came across a similar example on W3Schools website: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_overlay

Answer №1

The problem arises when you assign the class directly to the body element, turning it into the overlay itself which is not the correct approach. Instead, utilize a pseudo-element as your overlay element to cover the contents within the body:

var styling = document.createElement('style');
styling.type = 'text/css';
styling.innerHTML = '.overlay-loader-mobile-style:before {content:"";height: 100%; width: 100%; position: fixed !important; z-index: 5000000 !important;left: 0 !important;background-color: rgb(0,0,0);background-color: rgba(0,0,0,0.9);overflow-x:hidden;transition: 0.5s;}';
document.getElementsByTagName('head')[0].appendChild(styling);
document.body.className = 'overlay-loader-mobile-style';

Answer №2

Discovered a solution that is effective on all websites, unless a specific element has a higher z-index.

const customStyle = document.createElement('style');
customStyle.type = 'text/css';
customStyle.innerHTML = '.overlay-loader-mobile-edition:before {content:"";height: 100%; 
width: 100%; position: fixed !important; z-index: 5000000 !important;left: 0 
!important; top:0 !important;background-color: rgb(0,0,0);background-color: 
rgba(0,0,0,0.3);overflow-x:hidden;transition: 0.5s;}';
document.getElementsByTagName('head')[0].appendChild(customStyle);
const newDivElement = document.createElement("div");
newDivElement.setAttribute("id", "overlay-mobile-mask-div");
newDivElement.className = "overlay-loader-mobile-edition";
document.body.appendChild(newDivElement)

Grateful to Temani for highlighting the necessity of creating a new element.

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

Is there a way to align the content in my Flexbox rows to the top of each cell, resembling a table layout?

I am currently facing challenges in aligning my layout correctly, especially on resolving the final adjustments. In the scenario described below, everything seems to work fine when the message_data <span> elements contain a single line of data. Howe ...

Tips for ensuring that the dynamic view updates correctly when the scope variable is modified

I am currently working on an Angular SPA where a $scope variable plays a crucial role in determining the content of a specific page. When a user clicks on a different link in the menu, parameters are passed through the URL, updating the scope variable. How ...

``ScrollTop does not function properly in Safari when trying to reach the scroll

When implementing divRef.current.scrollTop = divRef.current.scrollHeight in my React project, I encountered an issue where it properly scrolled to the end in Chrome but not in Safari. divRef.current.scrollTop = divRef.current.scrollHeight ...

Determine the originating component in React by identifying the caller

Can you explain how to access the calling component in a React application? function MyCallingComponent() { return <MyReadingComponent/> } function MyReadingComponent() { console.log(callingComponent.state) } ...

Is there a way to retrieve and store a JSON object from a URL using JavaScript and jQuery?

I have a PHP page that is returning a JSON object in the correct format, like this: [ { "name":"Users", "parent":"null", "children":[ { "name": "adsd", "parent": "Users", "children": [] } , { "name": "ca", "p ...

What methods can be used to prevent words from breaking inside a label?

I'm having trouble styling a label with CSS properties because every word inside the label is breaking to a new line. For example, "Withdraw money" is displaying like this: Withdraw money I've tried various properties like white-space:nowrap,f ...

Troubleshooting: Unable to modify value with function in AngularJS

Why can't I change a value using a function in AngularJS? html: <div ng-controler='TestCtrl' id='TestCtrl'> <h1>Test: {{test.name}}</h1> <div ng-hide='showTest'> <div class=&a ...

Guide to prompting a browser to download a file using an XHR request

When it comes to downloading files from a server using an XHR request, how can I ensure that the browser initiates the download once the response is received? Additionally, which headers should be included by the server for this process to work seamlessl ...

Using JSTL within JavaScript

Can JavaScript be used with JSTL? I am attempting to set <c:set var="abc" value="yes"/> and then later retrieve this value in HTML and execute some code. The issue I'm facing is that the c:set always executes even when the JavaScript condition ...

Executing a particular function on multiple buttons that have not been initialized yet

I am struggling to make this code work for every button and I haven't been able to find an explanation for the issue. I believe it may be a small detail that I am overlooking. $(document).ready(function() { // delete the selected row from the datab ...

Get the results of a MongoDB projection query in Javascript/Node.js by converting the output to

When using a query with projection to retrieve specific fields from a MongoDB collection, do I need to output the results of the query to an array? I haven't come across any examples that don't involve converting the results to an array. db.coll ...

Organize information before making a choice in the dropdown menu

Currently, I have a dropdown menu in HTML that allows you to order the data by different options: <select ng-model="sortOrder" ng-options="option.value as option.name for item in options"></select> In addition, I have implemented code using n ...

"The powerful trio of Moongose, expressjs, and node-webkit combine forces

I'm currently in the process of developing an app using node-webkit, with expressjs and mongoose as the foundation. As a newcomer to this technology stack, I've encountered some challenges. One specific issue involves my attempt to integrate a m ...

Ensuring maximum length validation on input

I am having an issue with the function "checkNumbers()". I am attempting to validate if my input does not exceed 10 numbers; while "isAllowedSymbol()" is functioning correctly, the other one is not. What could be causing this problem? function isAllowe ...

What are the steps to approve an Amazon Pay request for retrieving a "get checkout session"?

Exploring the integration of Amazon pay as a payment option for customers on my website has led me to encounter some challenges with understanding the request headers required for calling the Amazon Pay API. Attempting a request to 'https://pay-api.a ...

Place the sorting image on the left side of the DataTable header

I am currently using DataTable in my code. The sorting images in the header of the table are on the right side while the labels are on the left, as shown below: https://i.sstatic.net/Bz6EO.jpg However, I would like to switch this arrangement and have the ...

Selecting middleware to be executed based on Express JS request parameters

Can someone please advise me on how to select between two distinct middleware functions, based on the request for a specific endpoint? It may involve something along these lines: router.post("/findAvailableAgents", chooseMiddleware(middleware1, ...

How can I adjust the scale and position of my image textures in Three.js?

Is there a way to adjust the scale and position of my image textures? The dimensions of my image are 1024px x 1024px. let textureMap = THREE.ImageUtils.loadTexture( 'texture.png' ); https://i.sstatic.net/wKd6f.jpg ...

Utilize Angular's $location to add or update the current URL parameter

I'm working on a function for handling multiple parameters in the URL when clicking an element. Specifically, I need to check if parameter pthree exists, update it to a new value without duplicating, and if it doesn't exist, append it to the curr ...

Need help tackling this issue: getting the error message "Route.post() is asking for a callback function, but received [object Undefined]

I am currently working on implementing a new contactUs page in my project that includes a form to store data in a mongoDB collection. However, after setting up all the controller and route files and launching the app, I encountered an error that I'm u ...