Reputation: 9
I am trying to get my JavaScript to scroll something into view upon me clicking a div
. When I click it nothing happens.
I've done a few things to troubleshoot: console.log in the scrollToAbout
section works fine and I can run other functions like changing innerHTML
just fine. ScrollIntoView just doesn't appear to do anything. No errors in the dev console.
HTML for the div
I'm clicking
<div class="lander">
<div class="intro"></div>
<div id="navbar">
<a href="#" class="navlist hyperlink" id="aboutButton">about</a>
<a href="#" class="navlist hyperlink" id="contactButton">contact</a>
<a href="#" class="navlist hyperlink" id="funButton">fun</a>
</div>
</div>
HTML for the div
I want to scroll to:
<div class="row hello col-12 p-0 m-0" id="aboutSection">
<img class="xyz col-12 col-md-6" src="xyz" alt="">
<p class="aboutme col-12 col-md-6"> THIS SECTION </p>
</div>
then here is the JS I've written:
let aboutButton = document.querySelector('#aboutButton');
let aboutSection = document.querySelector('#aboutSection');
aboutButton.onclick = function(){
scrollToAbout()
};
function scrollToAbout(){
aboutSection.scrollIntoView({ behavior: 'smooth'});
};
Upvotes: 1
Views: 87
Reputation: 31992
The href
attribute on the anchor (href="#"
) is causing the page to scroll to the top.
As per MDN:
You can use
href="#top"
or the empty fragment (href="#"
) to link to the top of the current page...
You should instead remove it altogether, or, if you want to preserve the anchor styling, set the href to javascript:void(0)
.
Also,
aboutButton.onclick = function(){
scrollToAbout()
};
is redundant. Simply aboutButton.onclick = scrollToAbout
does the trick.
let aboutButton = document.querySelector('#aboutButton');
let aboutSection = document.querySelector('#aboutSection');
function scrollToAbout() {
aboutSection.scrollIntoView({
behavior: 'smooth'
});
};
aboutButton.onclick = scrollToAbout;
#navbar {
margin-bottom: 500px;
}
<div class="lander">
<div class="intro"></div>
<div id="navbar">
<a class="navlist hyperlink" id="aboutButton">about</a>
<a href="#" class="navlist hyperlink" id="contactButton">contact</a>
<a href="#" class="navlist hyperlink" id="funButton">fun</a>
</div>
</div>
<div class="row hello col-12 p-0 m-0" id="aboutSection">
<img class="xyz col-12 col-md-6" src="xyz" alt="">
<p class="aboutme col-12 col-md-6"> THIS SECTION </p>
</div>
Upvotes: 0