Categories
JavaScript Answers

How to scroll an iframe with JavaScript?

Spread the love

Sometimes, we want to scroll an iframe with JavaScript.

In this article, we’ll look at how to scroll an iframe with JavaScript.

How to scroll an iframe with JavaScript?

To scroll an iframe with JavaScript, we call the scrollTo method.

For instance, we write

const myIframe = document.getElementById("iframe");
myIframe.onload = () => {
  myIframe.contentWindow.scrollTo(xCoord, yCoord);
};

to select the iframe with getElementById.

Then we call myIframe.contentWindow.scrollTo to scroll the iframe to xCoord, yCoord x-y coordinates in the iframe’s onload callback.

We call scrollTo there to scroll only when the iframe is loaded.

Conclusion

To scroll an iframe with JavaScript, we call the scrollTo method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *