Reputation: 25
I have a button which when clicked should scroll the page down to meet a div. I created a scrollIntoView function in JavaScript and linked it to the button (a tag) with an onClick. The onClick is working because it triggers the console.log, but it doesn't trigger the scroll event.
Here is the code, HTML and JavaScript.
HTML
<div class="arrowContainer">
<a type="button" onClick="move();" id="arrowBtn" data-scroll href="#">
<div class="arrow"></div>
</a>
</div>
JavaScript
function move() {
document.querySelector('.experience').scrollIntoView({
behavior: 'smooth'
});
console.log('Is it working?')
};
So since I noticed the onClick was not triggering the scrolling, I added move() underneath the function, and as the page was reloaded the scroll function + console.log worked properly. I have no idea what I have done to stop it from working properly.
Any help would be really appreciated. Also its probably something really obvious as I'm new to JavaScript.
Upvotes: 0
Views: 1898
Reputation: 451
Normally, use of href="#exampleid"
should do the trick and teleport to element with id="exampleid"
, so you could use id instead of class.
Here is your code based on class
function move(e) {
e.preventDefault();
document.querySelector('.experience').scrollIntoView({
behavior: 'smooth'
});
};
<html>
<head></head>
<body>
<a href="#" onClick="move(event);" id="arrowBtn">
<div class="arrow">arrow</div>
</a>
<div style="height:1000px;"></div>
<div class="experience">experience</div>
</body>
</html>
And here is simplest and without js:
html{
scroll-behavior: smooth;
}
<html>
<head></head>
<body>
<a href="#experience" id="arrowBtn">
<div class="arrow">arrow</div>
</a>
<div style="height:1000px;"></div>
<div id="experience">experience</div>
</body>
</html>
Your anchor tag (<a></a>
) have type
attribute, but it's not like <input>
type. It stands for
media type of the linked document a type
and you could use it like this:
<a href="example.com/img.png" type="image/png">image link</a>
Upvotes: 0