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

Content in the Bootstrap carousel vanishes without warning after a period of time

I am facing an issue with a carousel I added to a section of my website using HTML, CSS, and Bootstrap 5. The problem is that after some time, the content and the carousel inside that section disappear. Reloading the page temporarily fixes this issue but ...

Fade-in a new, revised text after fading-out the original text in ReactJS

I have a bunch of p elements that I'd like to cycle through, fading in one at a time and then replacing it with the next. Here is the jQuery example on CodePen: https://codepen.io/motion333/pen/EBBGVM Now, I'm attempting to achieve the same effe ...

Mysterious error arises in Internet Explorer versions 7 and 8: An expected colon is missing

One of our websites is encountering a puzzling JS error in Internet Explorer. The console displays the following message: ':' expected javascript:false, Line 1 Character 24 When attempting to trace the source of the error, a notification appear ...

What are the implications of dynamically setting or changing event handlers in web development?

Looking to streamline the process of replacing standard confirm() boxes with Bootstrap modals for saving and deleting on a page. Each operation has its own button (referred to as the action button) which triggers the corresponding modal. Upon clicking the ...

A more intelligent approach for generating JSON responses using Mysql

Here is the code I have on my server side using Node.js: var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'SOMEUSER', password: 'SOMEPASSWD', database: 'SOMED ...

Manipulating JSON data in JavaScript

Currently delving into learning JSON as required for work purposes... I am attempting to dynamically add and delete records to a JSON object... Can anyone shed some light on why I keep receiving an UNDEFINED message? Here is the code... Appreciate any as ...

JavaScript loop to target a specific item

My goal is to animate the correct div under each navigation item, rather than all of them with the "navItemUnder" class. You can see exactly what I mean by hovering over a navigation item in this codePen. I am looking for a solution to target only one lin ...

Forecasting text input demands

Many websites display suggestions in a drop-down menu as you type, some even showing a preview of the most likely result in a lighter-gradient font next to the cursor. For example, Spotlight on my Mac does this: Spotlight text suggestion Is it possible ...

Tips for preventing harmful messages in a chat room app

As I am working on a chat room website, users are able to input any content they want into the entry field and then send it to all online users. However, I have concerns about security - what if malicious individuals try to inject harmful HTML or JavaScrip ...

Switching my Selenium code to HtmlUnit: A Step-by-Step Guide

Currently, my Selenium code is working perfectly fine. However, I am looking to convert this code into HtmlUnit. I know I can use the HtmlUnitDriver like WebDriver driver = new HtmlUnitDriver(); I want to make it purely HtmlUnit. Below is the code that I ...

Tips for customizing a button's font with CSS

Update: I have noticed that the issue mentioned in this question is specific to OS X browsers. I am looking to modify the font style of my input buttons using CSS, similar to the following: input[type="button"] { font: italic bold 3em fantasy; } How ...

Tips for selecting an element within a span by clicking on it?

Is there a way to click on an element that is contained within a span tag? I have attached a screenshot for reference. https://i.sstatic.net/FkhDB.jpg I would greatly appreciate any help on how to successfully click on that specific element. ...

How can a callback be properly passed in programming?

My coding approach is outlined below: var CustomLibrary = (function (window, $, undefined) { return { URI: 'http://testpage/API/', OnSuccess: function (data, status) { }, OnError: function (request, status, error) { } ...

Using Javascript, incorporate a string variable into the response

Currently, I'm working with a node.js program and I've come across this response: 'Content-Disposition': 'attachment; filename="tts.mp3"' Instead of using "tts.mp3," I have a variable named textToConvert. How can I modify it ...

The qTip comment box vanishes when focused on by IE/Edge browsers using touch devices

A unique JavaScript library called qTip is being utilized in my project. The application includes a StarRating and Comments feature, both of which are enabled by this plugin. After selecting a rating using the stars, users have the option to add comments, ...

How to use getBoundingClientRect in React Odometer with React Visibility Sensor?

I need help troubleshooting an error I'm encountering while trying to implement react-odometer js with react-visibility-sensor in next js. Can anyone provide guidance on how to resolve this issue? Here is the code snippet causing the problem: https:/ ...

Make sure to tick the checkbox by clicking on the <tr> element using jQuery

I have the following HTML code snippet: <table class="table table-striped"> <thead> <tr> <th></th> <th>Color</th> </tr> </thead> <tbody> ...

Press the LI element to toggle the visibility of the UL element

I'm attempting to create a toggle navigation menu, but I'm having trouble identifying the issue with my code. It's a bit messy because I'm using a CMS that automatically generates the IDs and classes for the list menu. Ideally, I would ...

Enhancing a Dropdown List with Jquery Using JSON Data

I am trying to populate a list using a JSON collection of objects. Here is the method that my action is returning: public ActionResult GetProductCategories() { var categories = _entities.ProductCategories.ToList(); var res ...

Guide on utilizing exported API endpoint in Node and Express

Seeking a deeper understanding of express and its utilization of various endpoints. Recently came across an example of an endpoint that reads in a json file, demonstrated as follows: const fs = require('fs'); const path = require('path&apos ...