Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

I need help with the DOM. These are only five line of JS code and very simple to read.

<style>
*{margin:0;}
</style>
<div style="height:100vh;width:100vw;background-color:#000;">
<button class="btnScrollBottom">Scroll to second div</button>

</div>
 <div style="height:100vh;width:100vw;background-color:violet;"></div> 
<div style="height:100vh;width:100vw;"></div>
<script>
const home = document.querySelector('div')
const div2  = document.querySelectorAll('div')[1]
/* 
I wan to scroll to div with class name div 2 when I clicked the button.
I do not think  scrollTo is a better choice because I think it will causes issue on mobile. Is there any better way to scroll to div with class name div2.
*/
const btnScrollBottom = home.children[0]

btnScrollBottom.addEventListener('click',function(){
window.scrollTo(0,522)
})
</script>

1 Answer

Gergely Bocz
Gergely Bocz
14,244 Points

Hi there!

I think this is what you are looking for:

<style>
*{margin:0;}
</style>
<div style="height:100vh;width:100vw;background-color:#000;">
<button class="btnScrollBottom">Scroll to second div</button>

</div>
 <div style="height:100vh;width:100vw;background-color:violet;"></div>
<div style="height:100vh;width:100vw;"></div>
<script>
const home = document.querySelector('div')
const div2  = document.querySelectorAll('div')[1]
/*
I wan to scroll to div with class name div 2 when I clicked the button.
I do not think  scrollTo is a better choice because I think it will causes issue on mobile. Is there any better way to scroll to div with class name div2.
*/
const btnScrollBottom = home.children[0]

btnScrollBottom.addEventListener('click',function(){
div2.scrollIntoView({behavior: 'smooth'});
})
</script>

In short i replaced window.scrollTo(0,522) with scrollintoView. I have also added smooth scrolling as a behaviour option, because it looks nicer that way, but it's purely optional. If you don't want to enable smooth scrolling, replace "smooth" with "auto" or just leave out everything inside and including {} altogether; in other words write div.scrollIntoView().

If you want to read more about scrollIntoView, i suggest checking out the MDN page.

I hope this answer helps and if you have any question left, feel free to ask!

GergΕ‘