Home > Article > Web Front-end > 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:
<code class="javascript">var myElement = document.getElementById('element_within_div'); var topPos = myElement.offsetTop;</code>
<code class="javascript">document.getElementById('scrolling_div').scrollTop = topPos;</code>
Alternatively, for a prototype JS implementation:
<code class="javascript">var posArray = $('element_within_div').positionedOffset(); $('scrolling_div').scrollTop = posArray[1];</code>
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!