The window fails to retain the scroll position when overflow is enabled

Whenever I click on a specific div, I use jQuery to dynamically apply overflow: hidden to the html and body.

$(".mydiv").on("click", function() {
   $("html, body").css("overflow", "hidden");
});

However, this action causes the window to scroll to the top of the page and lose its current scroll position. To regain the scroll position, I simply remove the overflow property like this:

$("html, body").css("overflow", "");

This issue occurs when the user clicks outside the previously opened div. Any suggestions on how to prevent this?

Answer №1

My assumption is that you are utilizing an <a href="#"> to toggle your CSS properties.

If not prevented with JavaScript, this will result in the page jumping to the top.

For example:

$('.overflow-toggle').on('click', function(e) {
  e.preventDefault() // prevent '#' navigation
  $("body").toggleClass('overflow-hidden');
});
.overflow-hidden {
  overflow: hidden;
}
.overflow-toggle {
  position: fixed;
  top: 0;
  right: 0;
  background: #FFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#" class="overflow-toggle">Toggle overflow</a>
<p>
  [Lorem Ipsum text here]
</p>
[Repeated Lorem Ipsum paragraphs]

The same example without preventing scroll:

$('.overflow-toggle').on('click', function(e) {
  $("body").toggleClass('overflow-hidden');
});
.overflow-hidden {
  overflow: hidden;
}
.overflow-toggle {
  position: fixed;
  top: 0;
  right: 0;
  background: #FFF;
}
[Same script as above without 'e.preventDefault()' included]

Applying overflow: hidden to either html or body should suffice, no need for both.

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

Why does my contact form display PHP code unexpectedly?

I've been following a YouTube tutorial to create a responsive single-page website using Bootstrap. The tutorial covered the front-end, but now I'm stuck on integrating a contact form. I added some PHP code I found online, but there seems to be an ...

Tips to enhance web page loading speed when parsing JSON data from a URL

While extracting data from a JSON file accessed via URL, I am experiencing long loading times. Surprisingly, the website manages to display the same data only when it's ready, and I aspire to achieve a similar functionality. I have yet to discover a ...

Can users arrange a lineup of choices?

As a beginner, I have a task that seems pretty simple to others but not so much for me. I need to create a feature where a client can order 10 different services in the order they prefer. The idea is to use a dropdown menu or checkboxes to allow the user ...

Issue encountered while attempting to send an HTML file using express.js

I have been trying to display an HTML file using Express.js with a static __dirname, but the HTML content does not show up after calling localhost/ var express = require('express'); var web = express(); ...

React Native: A guide to triggering a modal or action sheet when a button tab is clicked using Wix React Native navigation

Is it possible to trigger a modal or actionsheet by clicking on a specific bottom tab in a tab-based application using wix react native v2 navigation? These are the current packages and versions I am working with: react-native : "0.59.8" react : "16.8. ...

Export jqgrid information into Excel and PDF while preserving the currency format

I am looking for a way to export jqgrid data in currency format, such as $4,355. Here is my colmodel. I am using the function exportGrid('griddtable',[1,2,3,4,5]) name : 'totalSpend', index : 'tota ...

"Learn how to easily send media files stored on your local server via WhatsApp using Twilio with Node.js and Express

Whenever I attempt to send the PDF file created through WhatsApp, an error pops up preventing me from viewing it. easyinvoice.createInvoice(data, function(result) { //The response will contain a base64 encoded PDF file ...

Using JQuery's getJSON() method causes the URL in the request header to be duplicated

I have encountered an issue with a duplicated value in the request URL while attempting to execute the following AJAX function: var url = "localhost/travel/home/getPrevApplicantData"; $.getJSON(url, {group_id : "1"}) .done(function(data) { console.log ...

issue encountered during resource provider setup

Below is my code snippet where I'm attempting to populate a table using ngResource in a RESTful manner. However, when I include configuration directives, I encounter an uncaught object MINERR ASST:22 error. var app = angular.module('infra&apo ...

PugJS is failing to properly interpolate numbers from the JSON file

My goal is to display a list of interfaces retrieved from my router API, which is in JSON format. However, when using Pug, only the strings are being rendered and not the numbers. Here is the output (it displays correctly in HTML): em1 192.168.0.0/24 Addr ...

Make IE10 HTML page use IE Quirks mode

Assist me, I'm battling with Internet Explorer. We have a series of pages that function well in IE8 (on our intranet). The company has made the decision to upgrade directly to IE10. What is the HTML code needed to force a page to use IE5 Quirks Mode ...

Django Dynamic Field Error: Please choose a valid option from the available choices

My modeling dilemma revolves around the following structures. class Category(MPTTModel): name=models.CharField(max_length=75,null=False,blank=False, unique=True) parent=TreeForeignKey('self', null=True, blank=True, related_name='chi ...

Alignment issue with Ul dropdown menus and shadow

After stumbling upon a fascinating menu design at this link, I decided to tweak it for center alignment by following the advice on this forum thread. Unfortunately, my efforts have hit a roadblock - the drop down menus aren't aligning as intended and ...

Getting the dimensions of an image using a path in JavaScript

I am trying to display a div with an image, its name, size, and download link using jQuery. Here is the code I have created: var image = 'image/example.png' $('#download').attr("href", result2); $('.image').attr("src", re ...

Breaking apart a pipe-separated text and sending it through a JavaScript function

CSS: <div class="pageEdit" value="Update|1234567|CLOTHES=5678~-9876543?|5678"> <a href="https://host:controller">Update</a> </div> Trying to retrieve the data within the div and pass it into a JavaScr ...

Issue encountered while transferring data for populating table content with Material-ui

Could you assist me with a problem I'm encountering? I have created a component to display the information from an array, consisting of both index.js and TableData.js files. However, when attempting to transfer the array data from index.js to TableDat ...

Ways to adjust the width of the Dialog box in Jquery UI to 60% of the window size

Currently, I am utilizing Jquery UI for a pop-up feature that displays a table populated through an Ajax call. The script implementation is as follows: <script> $(function() { $( "#dialog" ).dialog({ autoOpen: false, show: { ...

Leveraging Object.assign for updating fields in Firebase documents

Currently, I am working on a website that allows users to create new projects by filling out a form with all the necessary project information. Within this form, there is a file input field where users can upload images and documents. I have successfully i ...

Tips for dynamically retrieving a CSS file for an HTML page

With multiple html pages containing the same navbar, I made the decision to place the navbar in its own file called navbar.html and use ajax with jquery.get() to dynamically load it onto each page. This prevents redundant code across all pages. Currently, ...

Having trouble with Node.js GET request functionality not functioning properly

I've been encountering difficulties with loading a page using Node.js. While my Node.js Application code functions properly when attempting to load other resources such as www.google.com, it seems to encounter issues specific to the domain name www.eg ...