Reputation: 299
Is there anyway to automatically scroll to the first visible element with a certain div class using javascript?
thanks!
Upvotes: 14
Views: 21899
Reputation: 1264
Can be easily done with plain JS:
const items = container.getElementsByClassName('active');
const visible = [...items].filter((el) => {
// jQuery-like :visible selector
return !!( el.offsetWidth || el.offsetHeight || el.getClientRects().length );
});
if (visible.length > 0) {
container.scrollTo({
top: items[0].offsetTop,
behavior: 'smooth'
});
}
This assumes:
container
is your scrollable container, you can replace with document
& window
if you're trying to scroll the whole page.active
class name.behavior: 'smooth'
config if you want the scroll to happen instantly in a single jump.https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo
Upvotes: 2
Reputation: 298246
You should be able to use something like this:
$('html, body').animate({
scrollTop: $('.class:visible:first').offset().top
}, 1000);
Demo: http://jsfiddle.net/Blender/xUw54/2/
Upvotes: 39