// scroll an element
element.scrollBy(300, 300);Element: scrollBy() method / notebook
Element: scrollBy() method
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
element.scrollBy({
top: 100,
left: 100,
behavior: "smooth",
});<div>
<button class="scroll">scroll() to 1000</button>
<button class="scroll-to">scrollTo() top</button>
<button class="scroll-by">scrollBy() 200</button>
<button class="scroll-into-view">Scroll last <p> into view</button>
</div>
<section>...</section>section {
border: 1px solid black;
padding: 20px;
margin-top: 60px;
height: 500px;
overflow-y: scroll;
scroll-behavior: smooth;
}.fade-out {
animation: fade-out 0.3s linear both;
}
.fade-in {
animation: fade-in 0.3s linear both;
}
@keyframes fade-out {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
@keyframes fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}const scrollByBtn = document.querySelector(".scroll-by");
const toolbar = document.querySelector("div");
const section = document.querySelector("section");function isInterrupted(interrupted) {
console.log(`Scroll finished;${interrupted ? " " : " not "}interrupted`);
if (interrupted) {
alert("Scroll interrupted!");
}
}scrollByBtn.addEventListener("click", async () => {
toolbar.className = "fade-out";
const result = await section.scrollBy(0, 200);
isInterrupted(result.interrupted);
toolbar.className = "fade-in";
});function supportsScrollPromises() {
const test = section.scroll(0, 0);
return test instanceof Promise;
}