Before the:
window.location.href = target_id;
It will lead directly to the element, without the scroll, but I believe that already imagined
Second, with all due respect and forgive me beforehand, but Eliseub’s answer is wrong, has no sense passing the value of the ID to the scrollTop
:
let target_id = $(this).find('a').attr('id_ou_name');
$('html, body').animate({scrollTop: target_id}, 300);
scrollTop expects a number and not an ID reference of an HTML element, so it does not work, the correct would be to take the offset().top
of the element you want the scroll to reach, follow the documentation:
Here on the site itself already has a very intuitive example of how is the correct minimum:
Although it has how to improve, as for example the selector could be something like:
a[href^="#"]
To affect only links that start with HASH, to summarize your code could look like this:
$("#pages .page:not('.hide')").stop().fadeOut('fast', function() {
$(this).addClass('hide');
var currentPage = $('#pages .page[data-page="' + page + '"]');
currentPage.fadeIn('slow', function() {
$(this).removeClass('hide');
$('html,body').animate({ scrollTop: currentPage.offset().top });
});
});
See example working:
$(document).ready(function() {
//Função que mostra o conteúdo de acordo com o botão clicado (menu)
$("#menu li a[href^='#']").on('click', function(e) {
e.preventDefault();
var target_id = $(this).attr('href');
var page = $(this).data('page');
$("#pages .page:not('.hide')").stop().fadeOut('fast', function() {
$(this).addClass('hide');
var currentPage = $('#pages .page[data-page="' + page + '"]');
currentPage.fadeIn('slow', function() {
$(this).removeClass('hide');
$('html,body').animate({ scrollTop: currentPage.offset().top });
});
});
});
//Função que insere a classe Active no botão que foi clicado (menu)
$("#menu li").on('click', function() {
$(this).siblings().removeClass('actives');
$(this).addClass('actives');
});
});
#pages .page {
min-height: 900px;
}
#pages #sobre {
background: #fc0;
}
#pages #teste {
background: #cfcfcf;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="store container">
<ul id="menu">
<li>
<a data-page="sobre" href="#sobre">
<h2> Sobre </h2>
</a>
</li>
<li>
<a data-page="teste" href="#teste">
<h2> Teste </h2>
</a>
</li>
</ul>
</div>
<div id="pages">
<section id="sobre" class="page style" data-page="sobre">
<header>
<h2> aaaa </h2>
</header>
<p class="text">aaaaaaaaaaaaaaaa.</p>
</section>
<section id="teste" class="page style" data-page="teste">
<header>
<h2> bbbb </h2>
</header>
<p class="text">bbbbbbbbbbbbbbbb.</p>
</section>
</div>
If you’re interested in a CSS-only option check this https://answall.com/questions/306228/layout-onepage-apenas-com-html-e-css-com-transition/306238#306238
– hugocsl