Reputation: 123
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
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
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
Reputation: 1168
Try this:
$("#composer_frame").contents().find("#myAnch").on('click',function(){
//do stuff
});
Upvotes: 1