Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll an iframe to the bottom when page loads?

Tags:

jquery

iframe

I was like on every question about this on the net, tried like 50 diff methods, first i tried to scroll the div - then when its not worked i've tried to iframe the file with the div and scroll the iframe.. nothing just works!

Look on the last script i have set up:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var t = 100; //arbitrary time in ms
$("#frame").animate({ scrollTop: $("#frame").height()}, t);
});
</script>

<center><iframe id="frame" src="xxx.php" frameborder="0" width="630px" height="500px"></iframe></center>

I tried both #frame and frame without the (#), both with (document).ready and without it. Nothing seems to work on the page and its driving me nutz.

Thanks. :)

like image 522
Ricardo Avatar asked Jun 11 '11 13:06

Ricardo


1 Answers

With jQuery you need to use .contents() to access whatever's inside the iframe. You also need to use either the window load event, or the iframe's document ready event.

$(window).load(function ()
{
    var $contents = $('#frame').contents();
    $contents.scrollTop($contents.height());
});

Demo: http://jsbin.com/ujuci5/2


I would recommend going back to the div structure you mentioned, since it sounds like what you're trying to do doesn't require an iframe. You'll find that it's a lot less headache to work with a div than an iframe.

$(function ()
{
  var $mydiv = $('#mydiv');
  $mydiv.scrollTop($mydiv.height());
});

Demo: http://jsbin.com/ujusa4/2


how can i launch the scroll function like 3 seconds after the page loads?

Use setTimeout.

$(window).load(function ()
{
    setTimeout(function ()
    {
        var $contents = $('#frame').contents();
        $contents.scrollTop($contents.height());
    }, 3000); // ms = 3 sec
});
like image 121
Matt Ball Avatar answered Sep 23 '22 00:09

Matt Ball