I'm writing a modal popup and I need the browser to jump to the top of the screen when the open modal button is pressed. Is there a way to scroll the browser to the top using jQuery?
This question is related to
javascript
jquery
css
modal-dialog
// When the user scrolls down 20px from the top of the document, show the button_x000D_
window.onscroll = function() {scrollFunction()};_x000D_
_x000D_
function scrollFunction() {_x000D_
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {_x000D_
document.getElementById("myBtn").style.display = "block";_x000D_
} else {_x000D_
document.getElementById("myBtn").style.display = "none";_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
// When the user clicks on the button, scroll to the top of the document_x000D_
function topFunction() {_x000D_
_x000D_
$('html, body').animate({scrollTop:0}, 'slow');_x000D_
}
_x000D_
body {_x000D_
font-family: Arial, Helvetica, sans-serif;_x000D_
font-size: 20px;_x000D_
}_x000D_
_x000D_
#myBtn {_x000D_
display: none;_x000D_
position: fixed;_x000D_
bottom: 20px;_x000D_
right: 30px;_x000D_
z-index: 99;_x000D_
font-size: 18px;_x000D_
border: none;_x000D_
outline: none;_x000D_
background-color: red;_x000D_
color: white;_x000D_
cursor: pointer;_x000D_
padding: 15px;_x000D_
border-radius: 4px;_x000D_
}_x000D_
_x000D_
#myBtn:hover {_x000D_
background-color: #555;_x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
_x000D_
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>_x000D_
_x000D_
<div style="background-color:black;color:white;padding:30px">Scroll Down</div>_x000D_
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>
_x000D_
Pure Javascript solution
theId.onclick = () => window.scrollTo({top: 0})
If you want smooth scrolling
theId.onclick = () => window.scrollTo({ top: 0, behavior: `smooth` })
If you're using jQuery UI dialog, you could just style the modal to appear with the position fixed in the window so it doesn't pop-up out of view, negating the need to scroll. Otherwise,
var scrollTop = function() {
window.scrollTo(0, 0);
};
should do the trick.
you're using jQuery UI dialog, you could just style the modal to appear with the position fixed in the window so it doesn't pop-up out of view, negating the need to scroll. Other
You could do it without javascript and simply use anchor tags? Then it would be accessible to those js free.
although as you are using modals, I assume you don't care about being js free. ;)
I know this is old, but for those having problems in Edge:
Plain JS: window.scrollTop=0;
Unfortunately, scroll()
and scrollTo()
throw errors in Edge.
Source: Stackoverflow.com