I have a list of items. When I click on one item (project) it opens (this is ok) and it scrolls to the top of the page (the wrong top!). The problem occurs when I have an opened item and I decide to open the one below: the top position is increased by the opened project height and the second project I click goes too far over the top.
Following the FIDDLE below: if I open project1 and then I click on project2, this goes on the wrong top. Same if I try to open any project below another opened one.
JS
$('.accordion-section-title').on('click', function () {
var idName = $(this).attr('id');
$('html, body').animate({
scrollTop: $("#" + idName).offset().top
}, 500);
});
Here's the FIDDLE
The problem seems to be the .slideUp()
and .slideDown()
methods are animated at the same time the window is scrolling. By the time the window has scrolled to the right Y coordinate, the accordion sections' heights have been altered, thus causing the window to end up in the wrong position.
I'm sure there are other ways to accomplish correct scroll positions, but my first thought was to store the initial Y positions once the page is loaded. This can be done this way:
$('.accordion-section-title').each(function() {
$(this).data('ypos', $(this).offset().top)
})
Each .accordion-section-title
element will have its Y position stored in a data attribute called ypos
. Later when you scroll the window, don't scroll to the elements position, but rather to its stored initial position. In other words, change scrollTop: $("#" + idName).offset().top
to scrollTop: $("#" + idName).data('ypos')
. Put together with your code it will look like the following:
$('.accordion-section-title').on('click', function(e) {
var idName = $(this).attr('id');
$('html, body').animate({
scrollTop: $("#" + idName).data('ypos') - 10
}, 500);
});
You can see how it plays out in this fiddle