The values returned by screen.height and screen.width are not accurate

When a user clicks on a button, I want to enable an overlay. However, when the user minimizes the screen, the overlay does not cover the full page and buttons remain clickable. I have tried setting the screen.height and screen.width for the overlay div using the id1, but once the screen is minimized to a certain level, the buttons are visible again.

document.getElementById("id1").style.height=screen.height;
document.getElementById("id1").style.width=screen.width;

My goal is to have the overlay display over the entire web page without any buttons being accessible.

Answer №1

Alright, let me walk you through the process of creating Overlays. Firstly, make sure you have a parent div set up like this:

<div class="container">
  <div class="overlay-div"></div>
  <div class="content">
      <!-- Your Content Here -->
  </div>
</div>

Within your HTML code, you will find a container with an overlay-div and content. Now in your CSS file:

.container {
   position: relative;
}
.overlay-div {
   position: absolute;
   right: 0;
   top: 0;
   left: 0;
   bottom: 0;
   background: rgba(0,0,0,0.5);
}

Answer №2

If you're encountering issues with the accuracy of screen.height, make sure to consult this resource for clarification.

Combining CSS with a touch of JavaScript can help accomplish your task effectively.

Pay close attention to two key units in CSS: vw and vh. For an in-depth understanding, refer to this MDN article.

The following demonstration showcases how CSS and JavaScript work together for event handling.

let trigger = document.getElementById('trigger'),
  triggersClose = document.querySelectorAll('.trigger-close'),
  fullScreen = document.getElementById('fullscreen');

/** Click event listener to display the overlay when button is clicked **/
trigger.addEventListener('click', e => {
  e.preventDefault();
  fullScreen.classList.add('visible'); /** Adding .visible class shows the overlay **/
});

/** Setting click events to hide the overlay for all corresponding buttons **/
triggersClose.forEach(el => {
  el.addEventListener('click', e => {
    e.preventDefault();
    fullScreen.classList.remove('visible'); /** Removing .visible class hides the overlay **/
  });
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.overlay {
  display: none; /** Initially hiding the overlay **/
  position: fixed; /** Positioned fixed regardless of scrolling **/
  width: 100vw; /** Viewport width unit responsive to zooming changes **/
  height: 100vh; /** Viewport height unit responsive to zooming changes **/
  top: 0;
  left: 0;
  justify-content: center; /** Center content horizontally **/
  align-items: center; /** Center content vertically **/
  padding: 15px;
  background: rgba(24, 24, 24, .6);
  z-index: 999; /** Topmost layer on screen **/
}

.overlay.visible {
  /** JavaScript-triggered class to show the overlay **/
  display: flex; /** Simplifying layout with flex **/
}

.overlay .overlay-wrapper {
  display: flex;
  flex-direction: column;
  width: 65%;
  max-height: 100%;
  overflow-y: auto; /** Adding scrollbars for excess content **/
  background-color: #fff;
}

.overlay .overlay-wrapper .overlay-header {
  position: relative;
  background-color: #1548a6;
}

.overlay .overlay-wrapper .overlay-header>.text,
.overlay .overlay-wrapper .overlay-body {
  padding: 15px 5px;
}

.overlay .overlay-wrapper .overlay-header>.trigger-close {
  position: absolute;
  width: 45px;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  font-size: 1.1rem;
  font-weight: bold;
  border: 0;
  color: #fff;
  background-color: #dc3545;
  cursor: pointer;
  border-top-right-radius: 4px
}

.overlay .overlay-wrapper .overlay-footer>.trigger-close {
  float: right;
  margin-bottom: 5px;
  margin-right: 5px;
  padding: 8px 15px;
  color: #fff;
  background-color: #007bff;
  border: 0;
  border-radius: 4px;
}
<button id="trigger">Click me!</button>

<div id="fullscreen" class="overlay">
  <div class="overlay-wrapper">
    <div class="overlay-header">
      <h3 class="text">Message heading</h3>
      <button class="trigger-close">&times;</button>
    </div>
    <div class="overlay-body">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. In facere fugiat aperiam officiis debitis voluptas soluta assumenda cumque reiciendis blanditiis nostrum, consequuntur vero corporis doloribus! Expedita voluptatem illum maiores culpa.</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae ex temporibus, possimus commodi, obcaecati nostrum maiores cupiditate voluptas voluptate unde qui quasi accusantium earum dolores pariatur fuga. Optio, officia praesentium.</p>
    </div>
    <div class="overlay-footer"><button class="trigger-close">Close</button></div>
  </div>
</div>

Read up more on flexbox (display: flex) for better insights into layout design.

Hopefully, this information will assist you further in your development journey.

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

What is the best way to retrieve all information from GitLab API using Axios?

I am looking to retrieve data from all the projects stored on my GitLab server. As I understand, GitLab usually displays a default of 20 projects per page, so I need to adjust the setting to show more projects at once: https://gitlab-repo.com/api/v4/proje ...

The virtual method 'android.location.Location' was called in error

I'm using WL.Device.Geo.acquirePosition(onGeoLocationSuccess, onGeoLocationFailure, options) from MobileFirst to retrieve a device's location. Initially, everything works smoothly as I successfully obtain the location. However, after clearing t ...

Using Node.js setTimeout method

I'm struggling with understanding how to utilize the setTimeOut function in NodeJS. Let's say I need: function A() to be executed every 10 seconds. If function A returns 'true' from its callback, it should trigger a call to a specific ...

What is the most effective way to exchange data among multiple React applications?

I am looking for a solution to securely share data among multiple applications, with some parts of the data being secure and others not. I have explored options like IndexedDB and localStorage, but they don't work in all browsers, especially in incogn ...

Chrome debug function named "Backbone" triggered

Backbone provides the capability to activate functions in other classes by utilizing Backbone.Events effectively. a.js MyApp.vent.on("some:trigger", function(){ // ... }); b.js function test(){ doSomething(); MyApp.vent.trigger("some:trig ...

Using a number input with step increments of 0.01 in AngularJS can result in undefined values for specific inputs

An issue arises when using a specific type of input in angularjs (1.6.1) where the values between 9.03 to 9.05 inclusively return undefined. This problem also occurs with other values like 9.62, 9.63, and 17.31. <input type="number" step="0.01" data-ng ...

Safari-exclusive: Google Maps API dynamically altering page aesthetics post-loading

Recently, I encountered a peculiar problem. Upon loading a page, the text displayed with full opacity. However, upon the Google Maps API loading after 2 seconds, the entire page's styling suddenly changed. It was as if the text on the page became less ...

How can an array of objects be sent as a query string to the endpoint URL in React?

I'm currently developing a react application and facing the challenge of dynamically constructing and appending query strings to URLs. This is necessary because I have a shared base endpoint for all links, but each link may require different parameter ...

Having trouble with the rendering of the Stripe Element Quickstart example

Currently, I am diving into the world of Stripe's Element Quickstart. Take a look at this fiddle that I have been working on. It seems to be quite different from the example provided. Although I have included the file, I can't seem to figure out ...

The initial rendering of the NextJs 13 application is experiencing significant sluggishness when deployed on an EC2

After deploying my NextJS 13.4 app on an AWS EC2 instance with 2 GB of RAM, I noticed that the initial load time is quite slow, taking around 20 seconds to load for the first time. The development mode in NextJS builds and displays the result, which may co ...

Does Typescript not provide typecasting for webviews?

Typescript in my project does not recognize webviews. An example is: const webview = <webview> document.getElementById("foo"); An error is thrown saying "cannot find name 'webview'". How can I fix this issue? It works fine with just javas ...

What is the best way to resize an element such as an image?

When an image is resized using a percentage, it preserves its aspect ratio properly. I am looking for a way to replicate this behavior with a div. My current challenge involves precisely positioning an element relative to an image. The image fills 100% of ...

Employ material-ui default prop conditionally

I am implementing a StepLabel component in material ui. Depending on the props passed to the parent, I may need to make changes to the icon property of the StepLabel: interface Props { customClasses?: ClassNameMap; customIcon?: ReactNode; } const MySt ...

Using Redux to Implement Conditional Headers in ReactJS

I am planning to develop a custom component named HeaderControl that can dynamically display different types of headers based on whether the user is logged in or not. This is my Header.jsx : import React from 'react'; import { connect } from &a ...

Customizing Images using a JSON array of images

Looking to implement a feature that displays images fetched from a CMS via a JSON file. The JSON data structure is as follows: { "images": [ {"title": "Image One", "url": "image1.jpg"}, {"title": "Image Two", "url": "image2.jpg"}, {"title": "Ima ...

What steps should be taken to resolve the error message "TypeError: Cannot read properties of undefined (reading 'toLowerCase')?"

After creating a basic search bar, I encountered an issue when typing in it for the first time: TypeError: Cannot read properties of undefined (reading 'toLowerCase') However, when I closed the pop-up and tried again, the search bar worked prope ...

Creating a Kendo Grid that mimics the appearance and functionality of an

Can someone help me with styling my Kendo grid to match the look of a basic HTML table? I want to use the table style I already have set up instead of the default Kendo style. Is there a way to achieve this? #resultTable th { cursor:pointer; } #result ...

Adjust the background shade of specific characters within an input text field

When a user inputs a string into a standard HTML input field (type="text"), such as "2013/13/29", and validation reveals that the number 13 is invalid in this context, I would like to visually highlight it by changing its background color to red while tu ...

Can you identify the issue within this code that combines HTML5, CSS, and JavaScript?

I'm attempting to create a feature where, upon clicking a button, a hidden div will be revealed. However, my current implementation doesn't seem to be working. function reload(){ window.reload(); } function vis(x,z,a){ var xpar = docu ...

The external javascript file is unable to recognize the HTML table rows that are dynamically inserted through an AJAX request

I have a situation where I'm pulling data from an SQL database and integrating it into my existing HTML table row. Here's the code snippet: Using Ajax to fetch data upon clicking analyze_submit: $(document).ready(function(e) { $('#anal ...