views:

273

answers:

1

On the webpage I have iframe, in which I display some content.
I want to run a function if any key is pressed inside iframe (iframe is editable).

I can do it using ajax (with scriptmanager on page):

Sys.UI.DomEvent.addHandler(document.getElementById('iframe1').contentWindow.document, 'keyup', iframeKeyHandler);

But I want to do it without ajax!

Updated Code:

function Init() {
    document.getElementById('iView').contentWindow.document.designMode = "on";       

     document.getElementById('iView').contentWindow.document.onkeyup = function(event) {
       alert(event);
     }    
 }

<body onload="Init()" >   
<iframe id="iView" style="width: 434px; height:371px" ></iframe>
</body>
A: 

I guess you meant "do it without using the script manager"?

You can do it this way (use attactEvent/addEventListener):

<html>
<head>
<script type="text/javascript">
function Init() {
    var _win = document.getElementById("iView").contentWindow;
    var _doc = _win.document;
    _doc.designMode = "on";
    if(_doc.addEventListener) {// if support addEventListener
     _doc.addEventListener("keyup", frameKeyUp, true)
    }
    else { //For IE
     _doc.attachEvent("onkeyup", frameKeyUp);
    }
}
function frameKeyUp(e){
    alert(e.keyCode);
}
</script>
</head>
<body onload="Init()" >   
<iframe id="iView" style="width: 434px; height:371px"></iframe>
</body>
</html>

Or using jQuery's event handler for "keyup":

$('#iframe1').keyup(function(event){
  //... do your stuff here ..
  //use event.keyCode to get the asscoiated key
});

More info on keyboard event arg can be found here and here.

o.k.w
and how can I found out what key was pressed?
kenny
"event.keyCode". Check the example at http://docs.jquery.com/Events/keyup
o.k.w
without using jQuery
kenny
"event.keyCode" as well, see my updated post :)
o.k.w
There must be something that I am doing wrong I get: 'event.keyCode' is null or not an object
kenny
Works for me though. Care to update your post with the updated codes?
o.k.w
done, also note that I need key event for iframe's contentWindow.document
kenny
@kenny: I've overhauled my codes to fit yours. The `keyup` method do not have a consistent behaviour across browsers and I think using the `attachEvent` (IE) and `addEventListener` (others) will be cleaner. I really recommend using jQuery, here's a related post: http://stackoverflow.com/questions/549488/adding-event-handler-to-an-iframe-using-jquery
o.k.w
This is great! thanks!
kenny
You are welcomed :P
o.k.w