Reputation: 35
I currently have a page with a CSS accordion here; as you can see, in order to have the page load with the accordion open instead of closed, i have the link point to one of the accordion sections, #acc3.
The problem with this is that the page automatically scolls down to center the accordion (on smaller viewports) I want the page to default to scroll top. I have tried using
$(document).ready(function(){
$('html').scrollTop(0);
});
but that does not seem to be helping. Any Idea? - Thanks
Upvotes: 0
Views: 749
Reputation: 9347
I don't think that the solution you're using is great to rely on anchor links alone. I understand that it acts as some kind of pagination, but as you said - the fact that on load it's jumping to the element is a bit crummy.
I also really don't like the fact that if no anchor is set, then none of them are open. I'd much prefer it if the first one was your "default". However, I can't think of a good way to achieve this using CSS off the top of my head, unless you were to explicitly mention #acc2:not(:target), #acc3:not(:target)
etc (maybe this would be easier in CSS4 if we get a parent selector - though I'm not sure how).
If you really want to achieve this with the existing solution, then using $("html,body").scrollTop(0)
should work, but I also remember having issues relating to trying to instantly set the scroll position using jQuery. Try adding a timeout (could be really minimal like 1ms) and see if that helps:
// Try de/increasing the 200 and see if that helps
setTimeout(function() {
$("html, body").scrollTop(0)
}, 200);
However, I'd still rather you recruited JavaScript a little more too, such as an initial check for a hash starting #acc
and if there's none then focus on one of the elements (a default).
Upvotes: 0
Reputation: 4648
Try this
<script type="text/javascript">
$(document).ready(function () {
window.scrollTo(0,0);
});
</script>
Upvotes: 1