If I have the following JS code:
$(document).ready(function() {
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
This is the HTML:
<a href="#about">
<div class="containerScroll">
<div class="first-scroll"></div>
<div class="second-scroll"></div>
</div>
</a>
Right now the scrolling effect is working for all links with the tag a; however, can I change the $("a").on('click', function(event) { to something like $("scroll").on('click', function(event) {? Now, I'm hoping it will work for all the tags with scroll so now my HTML would look like:
<scroll href="#about">
<div class="containerScroll">
<div class="first-scroll"></div>
<div class="second-scroll"></div>
</div>
</scroll>
Would this work? Essentially, I want to add another tag instead of a because I do not want the scrolling effect to take place on all the links and only the ones I choose. This is why I tried changing the tag to scroll but it still did not work? Am I supposed to define a scroll css property for it to work?
Using jQuery for smooth scrolling is pointless nowadays
There are two methods (#2 is better IMO)
const element = document.querySelector('#something')
// element is the target you're trying to scroll to
element.scrollIntoView({ behavior: "smooth" })
/* in CSS */
html {
scroll-behavior: smooth;
}
//in JS
element.scrollIntoView()