views:

302

answers:

4

how can i prevent a html page from scrolling when arrow keys are pressed if a iframe inside it is focused?

im gettting this error in chrome

The iframe is focused, i know its focused. the parent scrolls anyway.

+3  A: 

The following code inside the iframe document will prevent it from scrolling:

document.onkeydown = function(evt) {
    evt = evt || window.event;
    var keyCode = evt.keyCode;
    if (keyCode >= 37 && keyCode <= 40) {
        return false;
    }
};
Tim Down
that will prevent the iframe from scrolling, but i want to prevent the page from scrolling.
Jcubed
But if the iframe is focussed, how can arrow keys be affecting the parent document?
Tim Down
@Tim Down - It's because the way he focus it doesn't work as it should. My answer provide him with the code to fix that issue.
Gert G
A: 

This works except IE:

window.top.document.onkeydown = function(evt) {
    evt = evt || window.event;
    var keyCode = evt.keyCode;
    if (keyCode >= 37 && keyCode <= 40) {
        return false;
    }
};
galambalazs
A: 

This code does the trick:

JavaScript

<script type="text/javascript">
  function focusOnIframe(iFrameID) {
    if (frames[iFrameID]!=undefined)
      frames[iFrameID].focus(); // Works in all browser, except Firefox
    else
      document.getElementById(iFrameID).focus();  // Works in Firefox
  }
</script>

HTML (example)

<input type="button" id="setfocus" value="Set focus" onclick="focusOnIframe('myiframe')" />

<p>Bla<br />Bla<br />Bla<br />Bla<br />Bla<br /></p>  <!-- Just some filler -->

<iframe id="myiframe" src="yourpage.html"></iframe>

<p>Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br />Bla<br /></p>  <!-- Just some filler -->

I've tested it in Firefox 3.6.6, Iron 5.0.380, Opera 10.60, IE 6 and IE 8.

Gert G
you understand that the question involves scrolling, right? not focusing?
Jcubed
The problem is that your focus isn't working, correct? I.e. when the iframe is focused and you use the arrow keys, it scrolls the parent. The above code sets the focus and the parent doesn't scroll.
Gert G
no, it focuses on the frame
Jcubed
And when you use up and down key, the parent scrolls, correct?
Gert G
A: 

I have the same issue both frames scroll with the arrow keys when focused on the iframe

Ben