Home > Web Front-end > JS Tutorial > body text

How to Prevent Scrolling the Entire Page When Clicking an Element Inside a Scrollable Div?

Susan Sarandon
Release: 2024-10-26 15:41:30
Original
854 people have browsed it

How to Prevent Scrolling the Entire Page When Clicking an Element Inside a Scrollable Div?

How to Scroll Within a Scrollable Div

When clicking on an element within a scrolled div, you may encounter an issue where the entire page scrolls instead of just the div. To resolve this, leverage the following steps:

  1. Calculate the vertical offset of the desired element relative to its parent div:
<code class="javascript">var myElement = document.getElementById('element_within_div');
var topPos = myElement.offsetTop;</code>
Copy after login
  1. Utilize scrollTop to scroll the div to the specified position:
<code class="javascript">document.getElementById('scrolling_div').scrollTop = topPos;</code>
Copy after login

Alternatively, for a prototype JS implementation:

<code class="javascript">var posArray = $('element_within_div').positionedOffset();
$('scrolling_div').scrollTop = posArray[1];</code>
Copy after login

This approach ensures that the div scrolls to display the desired element at the top or as far down as possible if it's not visible by default.

The above is the detailed content of How to Prevent Scrolling the Entire Page When Clicking an Element Inside a Scrollable Div?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!