I have a set of buttons on a page and when someone’s clicks I want the button to expand and scroll to the top of the page (viewport height, not the actual top). This is my code –
<div class="team-header" id="brian"> <div class="teamlogo"> <img src="images/logos/wolves.png" /> <h1>Brian</h1> </div> </div> <div class="brian-roster team-rosters"> <?php include ('brian.php'); ?> </div> <div class="team-header" id="carlos"> <div class="teamlogo"> <img src="images/logos/leverkusen.png" /> <h1>Carlos</h1> </div> </div> <div class="carlos-roster team-rosters"> <?php include ('carlos.php'); ?> </div>
There are 14 of those divs in total, that’s just an example of two.
I have this jQuery code for each one –
const brianRoster = $(".brian-roster"); const brianID = $("#brian"); brianID.on("click", function () { $("html, body").animate( { scrollTop: $("#brian").offset().top - 60, }, 100 ); $(brianRoster).slideToggle(700); });
(the -60 is to compensate for a sticky header)
Right now if you click the button it expands but does not scroll to the top. If you click the button again it collapses (as it should), and then scrolls to the top.
How can I get it to scroll to the top?
Advertisement
Answer
try this :
$(window).scrollTop(0);
instead of
scrollTop: $("#brian").offset().top - 60,
or try
$("html, body").animate( { scrollTop: $("#brian").offset().top, }, slow );