If the body's height is adjusted, the page will automatically scroll to the top

I'm facing an issue where a button on my HTML page triggers a popup box to open (which covers the background). To prevent the background from scrolling, I am using the following CSS:

windowHeight = $(window).height();
$("body").css({
    "height": windowHeight,
    "overflow": "hidden", 
    "overflow-y": "hidden"
});

While everything is functioning correctly, the page automatically scrolls to the top when the button is clicked. How can I avoid this from happening?

Answer №1

The reason for this behavior is when you modify the height property. It's unnecessary to explicitly set the height; simply applying overflow: hidden to the body should suffice.

CSS:

.locked {
  overflow-x: hidden; 
  overflow-y: hidden;
}

Javascript:

$("body").addClass("locked");

Give it a try: http://jsbin.com/tapagexope/1/edit?html,css,js,output (Click on the body)

Tested on FF 34 and Chrome 38 browsers.


Remember to place your overlay within a container that has position: fixed with all sides (left, top, bottom, right) set as 0, covering the entire viewport. Then you can center your overlay element inside that box.

Answer №2

Fortunately, I have already developed a custom jQuery solution for this specific issue: jquery-preventscroll

To implement the plugin, simply include the script and then utilize the following code when the modal is displayed:

$(window).preventscroll();

Once the modal is closed, you can re-enable scrolling functionality by executing:

$(window).preventscroll("undo");

If you'd like to see a demonstration, check out this example.

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

Utilizing AngularJS HTML5 mode with UI Router on an Apache server

A few days ago, I enabled html 5 mode on my Angular (1.5.8) app using the following code: $locationProvider.html5Mode({enabled:true,requireBase:true}).hashPrefix('!'); Later, I came across a guide on configuring an Apache server for html5 mode ...

Using Wordpress's built-in feature for displaying images in the admin panel can enhance the user experience and make

I'm currently in the process of developing a unique Wordpress plugin for one of my customers and I really want to incorporate a modal popup feature on the admin page. After experimenting with ThickBox, LightBox, and Fancybox, none of them seem to do t ...

React Native - Caution: It is important for every child in a list to have a distinct "key" prop assigned to it

In my app, I am using FlatList to display a list of products with the help of Products.js and ProductCard.js. Products.js: const Products = ({navigation}) => { const renderItem = ({item}) => ( <ProductCard item={item} onClickHa ...

Retrieve an item from the Ionic Firebase database

My current challenge is retrieving data from the Firebase database. user-service.ts getProfile(){ try {; return this.afDatabse.object(`profile/${this.afAuth.auth.currentUser.uid}`); } catch (e) { console.log(e); } } c ...

Animation using CSS keyframes for simultaneous manipulation of various properties

I am facing a challenge with animating both the bottom and left properties of an object inside a container div simultaneously. How can I make it move diagonally? Despite using keyframes, the following code does not seem to achieve this effect: #containe ...

Executing npm commands programmatically from a node.js script

Currently, I am developing a specialized command line interface (CLI) for managing various packages to be installed or uninstalled using npm. Should I execute npm through spawn('npm') or require('npm')? require('child_process&apos ...

The function res.sendFile() does not display files on the browser

For the past few days, I've been facing a challenge. Does anyone have any suggestions? When I click on a login button, I authenticate the user, generate a token, store it in cookies, and then use it in the headers of a request to display the homepage. ...

What causes the div to shift while performing the FadeIn-FadeOut effect?

It seems like there might be something that I'm overlooking, as I am encountering a minor issue with this. I am aiming to align the "submenu div" on the right side of the Show/hide links. Initially, when I load the div, it is correctly positioned. H ...

steps for making a specific cell editable in tabulatorI'm happy to help

click here for image description required initializeTabulatortableBng() { let thisClass = this; let bngTableData = thisClass.tableDataWorm; function formatDecimal(cell) { var value = cell.getValue(); if (value !== null && value !== undefine ...

Is there a reason the hr tag elements aren't extending to the full width within the list?

I am having trouble with my hr tag elements in the table I created - they are not spanning the full width like the line above them. I have tried adjusting the width property but it doesn't seem to be working. Can anyone offer advice or guidance on how ...

Is there a messaging app that provides real-time updates for when messages are posted?

I am in the process of developing a messaging application. User1 sends out a message, and I want to display how long ago this message was posted to other users - for example, "Posted 9 min. ago", similar to what we see on sites like SO or Facebook. To ach ...

The Canvas renderer in Three.js is struggling to properly utilize the map and color properties

While attempting to utilize both the map and color properties at the same time with the canvas renderer, I have encountered a problem where only one of them will work properly. Additionally, when the cube to which the image is applied rotates, the image ...

Breaking up phrases into separate lines (Bootstrap 4 + Mobile)

On my website, I currently have a sentence that is fully displayed on the Desktop version. However, I am looking to modify it so that it breaks into 2-3 lines when viewed on Mobile using Bootstrap-4. For example, here is the text in question: Our large, ...

Navigate to the top of each element, unfortunately, the scrolling feature is malfunctioning

jQuery(".event_item .event_title").each(function(){ jQuery(this).click(function(){ var checkElement = $(this).next(); if(checkElement.is(':visible')) { checkElement.parent().find(".event_content").slideDown().slideUp('norm ...

Display solely the error message contained within the error object when utilizing the fetch API in JavaScript

I am facing an issue in logging the error message to the console while everything else seems to be working fine. Specifically, I am unable to log only the message such as "email exists" when the email already exists in the system. const submitHandler = a ...

Image gradually disappears after being loaded via ajax request

I am trying to achieve a fade-in effect for images after they have been loaded following an ajax call. The goal is to make the fade-in occur smoothly, rather than having the user observe the image loading process. Is there anyone who can assist me with ...

PHP implementation for a static header layout

I am interested in learning how to update content without refreshing the header. I have created a simple example below. Header.php <html> <head> </head> <body> <ul> <li><a href="index.php" ...

What is the best way to showcase the properties of multiple files with the help of

I have been attempting to utilize jQuery to exhibit the specifics of several uploaded files. Below is my code: <!DOCTYPE html> <html> <head> <title>jQuery Multi File Upload</title> </head> <body> <f ...

How to shift an image to the right side of the navbar

Is it possible to change the position of an image within a navbar from left to right? I have tried using the float property but it doesn't seem to work. .logo-img{ float: right; margin: 0px 15px 15px 0px; } <a class="navbar-brand logo-img" ...

Checkbox click registers two instances

I made sure to cover all the details in the demo video. Check out the sandbox here: https://codesandbox.io/s/github/b1gun0v/reactjs-typescript-vladilen-minin Watch the demo video here: https://www.youtube.com/watch?v=xt032rjyXsU ...