Question

I am having some problems with addEventListener in Firefox. I have an iframe on my site for a WYSIWYG area I built myself.

I want the iframe to look more like a normal textarea so I want a border around the iframe on focus. First tp (textpreview) is found like this (and works well):

var tp = document.getElementById('iframe-textpreview');
var iframe = tp;    

if(tp.contentDocument){ // normal
    tp = tp.contentDocument;
}
else if(tp.contentWindow){ // old IE
    tp = tp.contentWindow.document; 
}
//Open and close for Firefox
tp.open();
tp.close();
tp.designMode = 'on';

Then I try to attach an eventlistener and log when the event fires. This works in Chrome, Opera and the most recent IE but not in Firefox:

//Doesn't work in Firefox
tp.body.addEventListener('focus', function(){ console.log('focus...')});
tp.body.addEventListener('blur', function(){ console.log('blur...')});

This does work however:

//Firefox
tp.body.onfocus = function(){ console.log('focus...')};
tp.body.onblur = function(){ console.log('blur...')};

I have cleared the cache on Firefox and tried with another computer, still no luck to get the first option working.

Was it helpful?

Solution

Firefox doesn't fire the event handler on the body element for some reason, instead you have to attach the event handler to the iframe itself or an actual element inside the iframe.

Focusing on the iframe itself, and not the body, seems to work in all browsers

tp.addEventListener('focus', function(){ console.log('focus...')});
tp.addEventListener('blur', function(){ console.log('blur...')});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top