Thursday 19 June 2014

Add javascript event handlers to frames and iframes of web page

Hi All,

Those who are familiar with javascript would know, how powerful are javascript event handlers and how it makes their life easier in web applications.

Javascript event handlers are inserted at document or at individual element level in web sites and they listen for the specific events and perform the required actions as defined by the developer.

You can find the definition about events and its various types here: http://www.w3schools.com/js/js_events.asp

Events can be inserted into web pages with help of below mentioned methods:

i) addEventListener (for firefox, chrome and IE 9+ browsers)
ii) attachEvent (for IE 5-8)

But, when we need to attach event handlers to elements present inside frames and iframes of web pages - we need to do some additional work. In this blog, I am going to explain how to achieve it.

Event handlers can be added into iframes as below:

var iframes = document.getElementsByTagName('iframe');
alert(iframes.length);

document.iframes[0].contentDocument.addEventListener('click',callback,false);
function callback(e){
alert(123);
}
For adding into Frames, you can use the below statement:

var frames = document.getElementsByTagName('frame');
alert(frames.length);

parent.frames[0].document.addEventListener('click',callback,false);
function callback(e){
alert(123);
}



No comments:

Post a Comment