jQuery HTML Element How to - Scroll within an iFrame on click








Question

We would like to know how to scroll within an iFrame on click.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.8.3.js'></script>
<style type='text/css'>
#wrap {<!--from  w  ww. j  av  a  2s  .  c o m-->
  width: 400px;
  height: 200px;
  overflow: hidden;
  position: relative;
}

#frame {
  position: absolute;
  top: 0;
  left: 0;
  width: 500px;
  height: 1000px;
}
</style>
<script type='text/javascript'>
$(window).load(function(){
    $(document).ready(function() {
        $wrap = $('#wrap');
        // Simulate scrolling
        $wrap.prop('scrollTop', 500);
        $('#btnOk').bind('click', function(e) {
            $wrap.prop('scrollTop', 0);
        });
    });
});
</script>
</head>
<body>
  <button type="button" id="btnOk">Click Me!</button>
  <div id="wrap">
    <iframe id="frame" src="http://www.java2s.com" scrolling="no"> </iframe>
  </div>
</body>
</html>

The code above is rendered as follows: