First, check out the following code:
$(document).ready(function(){
for (var i = 1; i <= 6; i++) {
var coinId = "#btn_tag_" + i;
$(coinId).click(function(){
var targetId = $(this).attr("id");
var navMainOffset = $("#main_box").offset().top;
var scrollDistance = navMainOffset - $(window).scrollTop();
$("html, body").animate({
scrollTop: scrollDistance
}, 1000);
});
}
});
.up-page {
display: block;
width: 100%;
height: 100vh;
}
#main_box {
display: block;
width: 60%;
height: auto;
margin: 2rem auto 3rem;
padding: 10px;
box-shadow: 0 0 5px #000;
}
.content-up {
display: block;
width: 99%;
height: 100vh;
padding: 5px;
box-shadow: 0 0 3px #f00;
text-align: center;
}
.main-btn {
display: block;
width: 100px;
height: 35px;
margin: 15px auto;
box-shadow: 0 0 4px #f00, inset 0 0 200px #0028ff;
cursor: pointer;
border-radius: 10px;
color: #fff;
}
.main-btn p {
text-align: center;
font-weight: bold;
font-size: 20px;
padding: 5px 0 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="btn_tag_6" class="main-btn">
<p>6</p>
</div>
<div class="up-page"></div>
<div id="main_box">
<h1>main box</h1>
<div class="content-up">
<h2>content-up</h2>
</div>
<div id="btn_tag_1" class="main-btn">
<p>1</p>
</div>
<div id="btn_tag_2" class="main-btn">
<p>2</p>
</div>
<div id="btn_tag_3" class="main-btn">
<p>3</p>
</div>
<div id="btn_tag_4" class="main-btn">
<p>4</p>
</div>
<div id="btn_tag_5" class="main-btn">
<p>5</p>
</div>
</div>
As you can see in the code above, clicking on button number 6 correctly scrolls the page to the #main_box
ID, which is exactly what I want.
However, when I click on buttons 1 to 5, instead of scrolling to the #main_box
ID, it scrolls to the top of the page!!!
Please help me solve this problem as I can’t seem to find a solution.