I am curious how I can scroll the target id element of an anchor tag's href to the center of the page using the scrollIntoView method.
Here is my code so far:
$("a").click(function () {
var target = $($(this).attr("href"));
target[0].scrollIntoView({
behavior: "smooth",
block: "center"
})
});
I am able to log the targeted element to the console and use other methods to change the targeted element but can't figure out how to center it when scrolling.
Here is a Codepen with an example of what I'd like to do but instead uses scroll-margin-top: 50vh.
Anything is appreciated, Thx.
Your code seems to be working for me. The issue may be with the href not being a valid css selector or the element not being available in the scope of your code.
Try adding console.log(target) to the callback function, or even logging target[0] and seeing if it is the desired target.
here is a working snippet of .scrollIntoView
(async () => {
const $ = str => document.querySelector(str);
const wait = t => new Promise(r => setTimeout(r, t));
const section1 = $("section");
const section2 = $("section:nth-of-type(3)");
const options = {
behavior: "smooth",
block: "center"
}
while (true) {
await wait(3000);
section2.scrollIntoView(options);
await wait(3000);
section1.scrollIntoView(options);
}
})();
body {
margin: 0;
height: 300vh;
background: linear-gradient(black, lightgray);
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
}
section {
height: 20px;
width: 100%;
background-color: rgba(30, 30, 255, 0.8);
}
<section></section>
<section></section>
<section></section>
<section></section>
<section></section>