when i click a particular section’s link in link_div then i want to make scroll into the content_div’s section.
i try with javascript, but i cannot properly handle this. this scroll with whole body element.
my page is like this
<body>
<div>header/navbar</div>
<div>hero section</div>
<div class="container position-relative">
<div class="row d-flex">
<div class="col-3 link_div position-sticky">
<ul>
<li><span onclick="showSection(section1)">Section 1</span></li>
<li><span onclick="showSection(section2)">Section 2</span></li>
<li><span onclick="showSection(section3)">Section 3</span></li>
<li><span onclick="showSection(section4)">Section 4</span></li>
<li><span onclick="showSection(section5)">Section 5</span></li>
</ul>
</div>
<div class="col-9 content_div">
<div id="section1" class="height-300"></div>
<div id="section2" class="height-300"></div>
<div id="section3" class="height-300"></div>
<div id="section4" class="height-300"></div>
<div id="section5" class="height-300"></div>
</div>
</div>
</div>
</body>
i use javascript’s method like – scrollTo, scrollBy, scrollIntoView but anyone cannot work properly
function showSection(sectionId) {
var targetSection = document.getElementById(sectionId);
var contentDiv = document.getElementById('content_div');
if (targetSection && contentDiv) {
var contentDivRect = contentDiv.getBoundingClientRect();
var sectionRect = targetSection.getBoundingClientRect();
var scrollPosition = sectionRect.top - contentDivRect.top + contentDiv.scrollTop;
window.scrollTo(0, scrollPosition);
}
}
i also try this-
function showSection(sectionId) {
var selectedSection = document.getElementById(sectionId);
if (selectedSection) {
const scrollOffset = targetElement.offsetTop - scrollableDiv.offsetTop;
scrollableDiv.scrollTop = scrollOffset;
selectedSection.scrollIntoView({ behavior: 'smooth' });
}
}
2
Answers
There is no need to use JS for this. HTML has a default "jump to element" tool. You simply just need to use an
<a>
nchor where you use a hash (#
) to reference an ID. This either works within the same page or even on external pages.Your code was very close to the solution. You did not wrap quotes around the section id, you searched for a class as if it was an id and did not do the scroll and you overcomplicated incorrectly the scroll computation. Fixing these issues also fixed your code, here’s the snippet: