Reputation: 9053
I want to click this button, which is a section head of an accordion and have it move to the top of page (based on window)
I feel like this is simple --- but it was a long day. Any ideas?
Some background is that this is an accordion like thing - and the buttons are headers. Because the accordion is long - and the phone screen is small --- when you fold and open... you can end up in some random middle area of a section and I'm trying to get that section to move to the top instead of a hash... I've tried a few hash ideas, but I'll also need an if statement to avoid this happening on larger screens. I hope that is clear. Thanks. OH and HERE is a fiddle
HTML
<div class="some-div"></div>
<div class="some-div"></div>
<button>button to endup up at top</button>
<div class="some-div"></div>
<div class="some-div"></div>
<div class="some-div"></div>
<div class="some-div"></div>
<div class="some-div"></div>
<div class="some-div"></div>
<div class="some-div"></div>
<button>button to endup up at top</button>
javascript
$('button').on('click', function() {
$(this). go-to-the-top-with-an-offset-of-10px();
});
Upvotes: 2
Views: 4180
Reputation: 6781
With this, you can move at the top of the page ("based on window"):
$('button').click(function() { // on button click
$("html, body").animate({ // catch the `html, body`
scrollTop:0 // make their `scrollTop` property 0, to go at the top
}, 1000); // in 1000 ms (1 second)
});
Or if you want to move up by an offset of 10px, use:
$('button').click(function () { // on button click
$("html, body").animate({ // catch the `html, body`
scrollTop: $(this).offset().top - 10 // button's offset - 10
}, 1000); // in 1000 ms (1 second)
});
Or let's say you want to bring the 8th div to the top on click, use:
$('button').click(function () { // on button click
$("html, body").animate({ // catch the `html, body`
scrollTop: $("div:nth-of-type(8)").offset().top // 8th div's top offset
}, 1000); // in 1000 ms (1 second)
});
Upvotes: 5