Reputation: 429
I am targeting multiple similar child divs inside multiple container divs. Subsequently the page scrolls towards the first targeted child div.
Unfortunately, the page doesn't scroll towards the first child div and then stop scrolling. The page keeps scrolling towards all of the child divs one-by-one-by-one.
Without luck I am trying to change this behaviour. I wish the page would just stop scrolling at the first child div.
To see my problem in action please click on any year in the header: http://paintings.directory
Current jQuery code:
var $sections = $('section');
$('#index_year p, section p').on('click', function(e) {
let year = $(this).data('y');
$sections.each(function() {
let $section = $(this);
let $target = $('.' + year, $section);
if ($target.length) {
$('html, body').animate({
scrollTop: $target.offset().top - 128
}, 2000);
$section.removeClass('yearNotFound');
$section.animate({
scrollLeft: $section.scrollLeft() + $target.position().left
}, 2000);
} else {
$section.addClass('yearNotFound');
};
});
});
So far I have unsuccessfully tried to:
$('html, body').animate({
scrollTop: $('.class:visible:first').offset().top
}, 1000);
return, false;
after the current scrolling code as follows:$('html, body').animate({
scrollTop: $target.offset().top - 128
}, 2000); return, false;
$( "$target:first" )`
$('#index_year p, section p').on('click', function() {
$('html, body').animate({
scrollTop: $target.offset().top - 128
}, 2000);
});
scrollIntoView
, I just couldn't phantom where and how to use this.So far it's not working out for me and I am therefor looking for help.
Upvotes: 1
Views: 962
Reputation: 33933
I would store the first painting having the "year" class in another variable to procede to the scroll after the loop.
But the animation of each section having a matched date has to be in the loop...
$('#index_year p, section p').on('click', function(e) {
let year = $(this).data('y');
var $storedTarget;
$sections.each(function() {
let $section = $(this);
let $target = $('.' + year, $section);
if ($target.length) {
// Store the target here.
if(typeof($storedTarget) == "undefined"){
$storedTarget = $target.first(); // The first one!
}
// Animate sections left/right if there's a match
$section.animate({
scrollLeft: $section.scrollLeft() + $target.position().left
}, 1500);
$section.removeClass('yearNotFound');
} else {
$section.addClass('yearNotFound');
}
});
// Make sure there is at least a result..
if($storedTarget.length>0){
// Scrolling to the first section that has a match
$('html, body').animate({
scrollTop: $storedTarget.offset().top - 128
}, 1500);
}
});
Upvotes: 1