I have plans section on the homepage and I have other pages when I click on plans (in the top nav-bar) it smooth scrolls perfectly on the homepage, but it doesn't work in the other separate pages!
for that, I've tried several solutions and it didn't go the way it should.
My HTML code:
<ul class="navbar-nav">
<li class="nav-item"><a class="nav-link" data-value="home">home</a></li>
<li class="nav-item"><a class="nav-link" data-value="services">services</a>
</li>
<li class="nav-item"><a class="nav-link" data-value="recent-posts">posts</a>
</li>
<li class="nav-item"><a class="nav-link" data-value="plans">plans</a></li>
<li class="nav-item"><a class="nav-link" data-value="more">more..</a></li>
</ul>
My js code:
$('header .navbar-nav > li > a, .services .arrow > .arrowDown').click(function () {
$('html').animate({
scrollTop: $('#' + $(this).data('value')).offset().top
}, 500);
});
I'm expecting that when I press on link and I'm on a different page it should load the homepage, and scroll down to section on my homepage.
I'm basically a beginner and I don't know much, I'm sorry if I can't explain my problem any better.
Edit: I've tried another method to solve my problem, however, I'm facing a new one. What I did was check if the current page has an id with the specific value? if yes then I smooth scroll to that section, else I have to redirect to the home page and then scroll that specific section.
My new code is :
$('header .navbar-nav > li > a, .services .arrow > .arrowDown').click(function () {
// check if $(this).data('value') exist in the current page
if ($('#' + $(this).data('value')).length) {
// smooth scroll to that element
$('html').animate({
scrollTop: $('#' + $(this).data('value')).offset().top
}, 500);
}
// else load the homepage, then scroll to that element
else {
document.location.href = "/";
$('html').animate({
scrollTop: $('#' + $(this).data('value')).offset().top
}, 500);
// console.log('this item doesn\'t exist in the current page')
}
});
what I'm expecting is that if the current page isn't the homepage && and data-value doesn't exist in the current page, then I must redirect to (homepage) and smooth scroll to that specific section.
Many Thanks.