How do you scroll an iframe from within using jquery?

11,830

Solution 1

This ended up working:

$('html,body').animate({ scrollTop: x }, t);

Solution 2

Like this: (Tested)

$("iframe").contents().children().animate({ scrollTop: x }, t);

Solution 3

Create a function in the parent javascript like this:

function scrollToPoint(top) {
    $("html, body").animate({ scrollTop: top }, "slow")
}

and call that function within the iframe like this:

window.parent.scrollToPoint(top);

It should work in chrome, not tested in firefox yet

Solution 4

In Chrome I had to specifically select the body element:

$('#my-iframe').contents().find('body').animate({scrollTop:90},500);

Share:
11,830
Chris Stahl
Author by

Chris Stahl

Updated on June 04, 2022

Comments

  • Chris Stahl
    Chris Stahl almost 2 years

    I'm using a shadowbox which generates an iframe to display product details on a page. Because the details page can be pretty long, the client would like a "More" button that scrolls the page down (apparently the scrollbar on the right of the iframe isn't enough).

    Here's the code that I've tried in order to get the iframe to scroll:

    $(document).ready(function()
    {
    $(".moreButton img").click(function() {
        scrollbottom();
    });
    });
    
    function scrollbottom() {
    var x = 250; // this number is a temporary placeholder
    var t = 500;
    $("iframe").animate({ scrollTop: x }, t);
    }
    

    I've also tried using body instead of iframe but to no avail. Any ideas? Thanks!

  • Chris Stahl
    Chris Stahl almost 14 years
    $('iframe').contents().animate({ scrollTop: x }, t); That doesn't seem to be working either.
  • mack
    mack over 11 years
    does above line solved your problem? i'm getting same issue but not able to resolve by above line
  • Chris Stahl
    Chris Stahl over 11 years
    Yes, that ended up working for me. The only advice I would give you is to make sure that the scope of your function is correct. If your code is in the iframe itself, remember that it won't automatically run like it would on a freshly loaded page. You'll have to invoke it from the parent frame.
  • SLaks
    SLaks over 8 years
    @DavidReynolds: You're probably fighting SOP. What error do you get?