user3507859 user3507859 - 5 months ago 134
Javascript Question

stop parent page from scrolling down to iframe

I have embedded a website using iframe.
Whenever the parent page loads, the embedded page makes the parent page scroll down to the iframe. I cannot change any code in the embedded page, only the parent page.
Here's the [fiddle of the issue][1]:


<iframe src="!/~/cart" width="100%" height="100%" id="Container"></iframe>


body { margin-top: 100px; height: 1000px; }

How can I prevent the parent page from scrolling down to the iframe?


So we've added the following javascript to force the page to scroll bacl to the top:

window.addEventListener("scroll", runOnScroll);

function runOnScroll(){
window.scrollTo(0, 0);
window.removeEventListener("scroll", runOnScroll);

It does work as you can see [in this fiddle][2]. However, on the iPad and iPhone, you can clearly see the page scolling back then up again. On the PC, you can't see the transition.
Please visit [this website][3] so you can check both transitions (pc and mobile).
I'd like to know if there is anything we can add to the code so:

  1. the transition in mobile is not noticed like in the pc (preferred choice)


  1. the transition is smoother (slower scrolling or something like that)


Ok, I added a bit of JavaScript that listens to the first time the document is scrolled down. When the document is scrolled down for the first time, it'll force itself back to the top, then it'll remove the listener so that the user may scroll as desired afterward.


<!DOCTYPE html>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css"></link>
<script src=""></script>

<iframe src="!/~/cart" width="100%" height="100%" id="Container"></iframe>
<script src="scripts.js"></script>

JAVASCRIPT (In a file named scripts.js)

window.addEventListener("scroll", runOnScroll);

function runOnScroll(){
    $('html,body').animate({scrollTop: 0},1000);
    window.removeEventListener("scroll", runOnScroll);

Give it a shot, and let me know if it works!