Prevent horizontal HTML scrolling while displaying a layer

I am currently working with a .layer div element that darkens the page to highlight a modal. However, I have encountered an issue where upon triggering the event, the div does not occupy 100% of the screen and the original browser scroll bar disappears.

Is there a more elegant solution to ensure that the .layer div maintains the original page's scroll bar when visible?

While testing on smartphones/tablets, I have not experienced any issues when using the event .layer").show();. However, on desktop screens, the disappearance of the original browser scroll bar causes the entire HTML document to shift to the right.

What would be the proper approach to prevent the HTML from shifting to the right in this scenario?

Thank you in advance!

HTML:

<div class="layer"></div>
<div class="open-modal">Open</div>

<div class="modal">
  <div class="close-modal">Close</div>
</div>

CSS:

html {width:100%;min-height:100%;margin:0 auto;top:0;left:0;padding:0}
body {top:0;left:0;margin:0;padding:0;min-height:100%}

.layer {
display:none;
position:fixed;
top:0;
left:0;
width:100%;
min-height:100vh;
background:rgba(0,0,0,.9);
z-index:2
}

.modal {display:none;z-index:1}

SCRIPT:

$(document).ready(function(){
  $(".open-modal").click(function(){
    $(".modal,.layer").show();
    $("body").css("overflow","hidden");
  });
    $(".close-modal,.layer").click(function(){
      $(".close-modal,.layer").hide();
      $("body").css("overflow","");
  });
});

Answer №1

Remove the use of "overflow" from your code. Check out the link to Mozilla Developer Network docs for more information, but here's a quick summary:

"hidden Content is clipped to fit the padding box. No scrollbars are provided, and user scrolling is not supported (no dragging or scroll wheel). The content can be scrolled programmatically (e.g., by setting offsetLeft), making it a scroll container."

https://developer.mozilla.org/en-US/docs/Web/CSS/overflow

If you click Open and Close once, then try clicking Open again, the word Close won't appear. This happens because you're not using the .show() method to display the text when clicking Open. Here's an updated JavaScript snippet:

JavaScript:

$(document).ready(function(){
  $(".open-modal").click(function(){
    $(".modal,.layer,.close-modal").show();
  });
    $(".close-modal,.layer").click(function(){
      $(".close-modal,.layer").hide();
  });
});

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

Text input setting for jQuery UI Slider

Currently, I am utilizing jQuery UI sliders to input values in text boxes. However, I would like this functionality to be bidirectional; meaning if a value is entered into the text box, I want the slider to move to the corresponding position. I am unsure ...

Once you have successfully navigated past Div2, smoothly transition downwards to Div1 and transform it into a sticky

I wish to scroll down, and view #div1... also see #div2... When #div2 disappears from sight, I want #div1 to slide down and stay fixed at the top of the window. If I reach the footer div, I no longer want #div1 to remain sticky. If it's po ...

Checking the response from an AJAX call with an if/else statement

Is there a way to create a counter for unread messages using PHP and jQuery? Below is the PHP code in BubbleStat.php: $totalMsg = $mysql->totalRows("SELECT msg_id from messages WHERE msg_opened = 0 AND msg_receiver = '".$_SESSION["ActiveUserSessio ...

Guarantee: exclude all successful and unsuccessful responses and only carry out the .finally method

I have a function named request: function request (endpoint) { return axios.request(endpoint).then(api.onSuccess).catch(api.onError) } api.onSuccess: onSuccess (response) { let breakChain = false ... adding some logic here ... return break ...

Passing props in VueJS is a common task, especially while redirecting to another

I am working with two separate single-file components, each equipped with its own named route. In the Setup.vue component, there is a basic form that gathers and sends data to the Timer.vue component which expects certain props. Is there a way to navigate ...

The PHP script failed to display accurate information on the server terminal

I am looking to execute the following script: <?php $file = file_get_contents('data.json'); echo ($file); unset($file); exit(0); ?> When I access this script via ajax in JavaScript, everything works fine. However, when I ...

Rails Navigation Issue: JQuery Confirmation Not Functioning Properly

Having a Rails app, I wanted to replicate the onunload effect to prompt before leaving changes. During my search, I came across Are You Sure?. After implementing it on a form, I noticed that it only works on page refreshes and not on links that take you a ...

Is there a way for me to confirm that I am receiving the 401 error when fetching data?

When using an async function to fetch data, how can one determine if a 401 error occurred during the data retrieval process? The code example is as follows: async function getBilling(url, id, date) { let header = { method: 'GE ...

Instructions for adding a name to a string based on certain conditions

I am attempting to prepend a company name to a card number using the code provided. The challenge I am facing is incorporating the specific rules for each company as conditions for an if statement. Although I acknowledge that my current approach with the ...

Error in Java script due to the combination of Jmeter and Selenium APIs

While using Jmeter in conjunction with Selenium WebDriver, I encountered an unhandled error "016/02/17 16:51:47 ERROR - com.googlecode.jmeter.plugins.webdriver.sampler.WebDriverSampler: :14:94 Expected , but found ; WDS.browser.findElement(pkg.By.cssSele ...

Leveraging Handlebars for templating in Node.js to incorporate a customized layout

app.js const exphbs = require('express-handlebars'); app.engine('handlebars', exphbs({defaultLayout: 'layout'})); app.set('view engine', 'handlebars'); app.use('/catalog', require('./routes/ ...

When transferring files using formData via axios, the server is unable to interpret the data

`` In my quest to figure out how to send a file from a client using an input type=file to an API, I came across the suggestion to use formData. Following some examples I found, I implemented this approach, but upon checking the data on the server side, it ...

Exploring the possibilities of combining Selenium Code and F# with Canopy

Currently, I am facing the challenge of incorporating Selenium code into my F# project while utilizing the canopy wrapper. Canopy relies on Selenium for certain functions. My main struggle lies in converting Selenium code from Java or C# to fit within an ...

Ways to use jQuery to disable row form elements in the second and third columns

I need a way to deactivate form elements in the second and third columns, starting from the second row until the nth row using a jQuery selector. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> ...

Keep your data safe and protected within a Node CLI application

Currently developing a NodeJS command-line application that interacts with an API to provide data to users. To access the public API, users need an API token. The CLI will be globally installed on users' machines using npm i -g super-cool-api-cli. Up ...

How can I call the telerik radgrid.databind() function using a JavaScript function?

Currently, I am coding in ASP .NET and have an ASPX page featuring a Telerik RadGrid. I am curious to know if it is feasible to call the RadGrid.DataBind() method from within a JavaScript function? ...

Discovering latitude and longitude coordinates from a map URL, then enhancing dynamism by utilizing the coordinates as parameters

Hello, I am currently learning Vue.js and have encountered a challenge with embedding Google Maps URLs. Despite my extensive research on Google, I have not been able to find the solution I need. Here is an example of the URL I am working with: "https: ...

Adjust the size of an iFrame's content according to the dimensions of the iFrame

I am looking to use an iFrame for embedding a map, and my goal is to resize the map according to the values in the iFrame tag. Most tutorials I have found focus on auto-sizing the iFrame based on content, which is not what I need. Just to make it clear, I ...

Customize the Gap Between Inline Radio Buttons in MaterializeCSS

Help needed to align MaterializeCSS's radio buttons inline without gaps. Thank you in advance for any assistance! Below is a snippet of the code: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize ...

Unable to successfully link filter outcomes with input in AngularJS

Here is the code snippet I am working with: <body ng-app=""> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {nam ...