How to scroll an overflowed div to a specific hashtag (anchor)?

On my webpage, I have a crowded div (i.e. with a vertical scrollbar). Inside the div, I have bindings with identifiers. When I put one of these identifiers in the URL (mypage.html # id), I want the div, not the page, to scroll through this anchor.

How to do this, preferably using regular JavaScript? If it's too complicated, I will go with jQuery, but I will not use it in this project for anything else.

+8
source share
3 answers
$('.overflow').scrollTop($('#anchor').offset().top); 

There is no reason you cannot convert this to standard javascript.

Note that scrolling will be disabled if there is a margin on the anchor element.

+8
source

Have you tried to set focus() to an anchor?

Any DOM element with tabindex can be customized, and any element with focus will be viewed by the browser.

+5
source

This is a pure Javascript solution (ECMA 6), similar to Ariel's answer.

 const overflow = document.querySelector('.overflow'); const anchor = document.getElementById('anchor'); // Get the bounding client rectangles for both // the overflow container and the target anchor const rectOverflow = overflow.getBoundingClientRect(); const rectAnchor = anchor.getBoundingClientRect(); // Set the scroll position of the overflow container overflow.scrollTop = rectAnchor.top - rectOverflow.top; 
+1
source

Source: https://habr.com/ru/post/897810/


All Articles