Archive for the ‘Javascript’ Category

Adding an event listener to iframe which has designMode “on” (firefox)

May 11, 2009

In firefox when designMode is set to “on”, all the events for that iframe are disabled. You cannot add events to that iframe using the convensional way. Actually this makes sense since you wouldn’t want to have mouse hover events or click events triggered when you set the designMode of an iframe to “on”. But not been able to re-enable it while the designMode is still on is really inconvinient. I wanted to add a new feature for the sinhala transliteration for html WYSIWYG editors/RTE (Rich Text Editors). Since the transliteration happens detecting the keypress events in the control i needed to have a number of listeners on an iframe (normally all RTEs use iframe for its designMode functionality). After much searching on the net i found how to do it.

document.getElementById("my_iframe").contentWindow.addEventListener('focus', onFocussed, true)

where ‘focus’ is the event name and  onFocussed is a event handler of the type

function onFocussed(e){
     //Do something
}

Anyones interested my ff addon is here.

Adding events to iframe which has designMode set to ‘on’ (firefox)

May 8, 2009

Being looking for this for a while, then I found that firefox disables the events for a iframe when the designMode is set to “on”. But I kept on searching for a hack for this, which eventually brought me to the following code which works perfectly.

document.getElementById('iView').contentWindow.addEventListener('keypress',keypress, true);
function keypress(e){
   //Do something
}

How to get the caret position (cursor position) of a iframe which has designMode ‘on’ in firefox

May 8, 2009

Took me a couple of hours to find this out. Couldn’t find it on the internet. With a little bit of improvising finally found out the way.

var range = document.getElementById('iframe_id').contentWindow.getSelection().getRangeAt(0);
alert(range.startOffset);
alert(range.endOffset);

thats it.

Note:

Since this is an iframe we are talking about you should know the startOffset and endOffset is wrt to the container of the start pos and end pos text. In here what I meant by the container is that iframe may contain html tags.

For eg:

...my name is <b>saminda</b>. I like js.....

if you had selected the text “is samin” from the iframe the endOffset would be 5, not startOffset+3+5. Hope you understood