Buzz: Questions & Answers

Scroll up on button click

Follow
Answered
UpCode
I have a couple courses that have interior pages managed by javascript and button clicks. It looks like the activity page is a couple levels of nested iframes. Because of this I cannot do something like window.scrollTo(0,0) to scroll up. Is there any function to use that will scroll the screen to the top on an event?

Comments (1)

Sort by
Brian Williams
  • Agilix team member

When dealing with nested iframes, directly using `window.scrollTo(0, 0)` within one of the nested iframes might not work as expected because it affects the scroll position of the iframe's own content, not the parent document or other iframes.

However, might be able to trigger the scrolling of the parent window or any other iframe from within a nested iframe using the following approaches:

1. Scrolling the Parent Window
If you want to scroll the main (parent) window from within a nested iframe:

window.parent.scrollTo(0, 0);

2. Scrolling a Specific Ancestor Frame
If you know the frame hierarchy and want to scroll a specific ancestor, you can use `parent.parent`, `window.top`, or any combination based on the level of nesting:

window.top.scrollTo(0, 0); // Scrolls the top-most window
// or
window.parent.parent.scrollTo(0, 0); // Scrolls the grandparent window

3. Using `postMessage` for Cross-Origin Frames
If the iframes are cross-origin (i.e., they are served from different domains), directly accessing the parent or other iframes is not possible due to the Same-Origin Policy. In this case, you can use `postMessage` to send a message from the iframe to the parent window, which then handles the scrolling:

In the iframe:
window.parent.postMessage({ action: 'scrollToTop' }, '*');

In the parent window (include this script on the parent page):
window.addEventListener('message', function(event) {
    if (event.data.action === 'scrollToTop') {
        window.scrollTo(0, 0);
    }
});

4. Scroll within a Specific Iframe
If you want to scroll a specific iframe from another iframe or the parent window, you would need to first access that iframe and then scroll its content:

var iframe = document.getElementById('yourIframeId');
iframe.contentWindow.scrollTo(0, 0);

By implementing one of these methods based on your setup, it may may be possible to scroll the desired content to the top.
If additional assistance is needed, I recommend reaching out to your organization's authorized support representative to have a ticket submitted to Agilix Support. 

0 Comment actions Permalink
Please sign in to leave a comment.