How can I scroll the iFrame to the top when the content changes?
When embedding PollUnit on your website, it may be useful to change the scroll position of your webpage when the content of PollUnit changes. For example, when switching from an overview to a detailed view in a photo contest and the height of the iFrame changes significantly. Unfortunately, PollUnit cannot remotely control your website and scroll to a different position. This needs to happen on your website.
To make this work, you can listen for the load
event of the iFrame using JavaScript and then trigger a function. In our example, we call the function »customScrollFunction«, and the iFrame is assigned the ID »pollUnitIframe«.
The JavaScript that triggers the function could look like this:
document.getElementByClassName('pollUnitIframe')[0].onload = function() {
customScrollFunction();
};
The actual function that scrolls the iFrame could look like this:
customScrollFunction = function() {
const element = document.querySelector('#pollUnitIframe');
if (element) {
element.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
};
Please note that we are selecting the iFrame again based on our example ID. In some cases, it may be necessary to scroll a parent element of the iFrame or consider an offset. This could be the case, for example, if your website has a fixed header. Then you would need to adjust our example code accordingly.