Glen Davidson
Glen Davidson

Reputation: 123

How to add click event to the dynamic element of an iframe?

I'm adding some html element to the iframe by using innerHTML like below

var iframe = document.getElementById('composer_frame'), iframedoc = iframe.contentDocument || iframe.contentWindow.document;

iframedoc.body.innerHTML = "<a id='myAnch'>Click</a>";

and i want to write a function which should be exicute by clicking anchor "#myAnch"

Upvotes: 1

Views: 1293

Answers (3)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

Explanation:- Since you are trying to add a event on dynamically created element inside an iframe, so you have to bind it through parent reference.

That means based on parent element try to find-out the dynamically added element and then add event on it.(as jQuery din't recognise dynamically added element directly)

So do it like below:-

$("#composer_frame").contents().find('#myAnch').on("click", function (e) {
    e.preventDefault();
    alert('clicked');
});

Working snippet:-https://jsfiddle.net/sycf9nz6/

This is called event-delegation

Upvotes: 0

qu.xj
qu.xj

Reputation: 9

you can write function for element like this

$('#myAnch', iframedoc).click(function() {console.log("a");})

but you should put this code on parent html page.

Upvotes: 1

Jeffrey Ram
Jeffrey Ram

Reputation: 1168

Try this:

$("#composer_frame").contents().find("#myAnch").on('click',function(){
    //do stuff
});

Upvotes: 1

Related Questions