Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding click event handler to iframe

I want to handle click event on an iframe with a handler that gets the iframe’s id as parameter.

I’m able to add an onClick event handler via JavaScript as follows and it works fine:

iframe.document.addEventListener('click', clic, false);

But in this case I’m unable to pass a parameter to clic(). I tried to print this.id in clic() but no result.

onClick HTML attribute does not work at all, the handler is not called.

<html>
<head>
<script type="text/javascript">
function def() {
    myFrame.document.designMode = 'on';
}
function clic(id) {
    alert(id);
}
</script>
</head>
<body onLoad="def()">
<iframe id="myFrame" border="0" onClick="clic(this.id)"></iframe>
</body></html>
like image 805
samach Avatar asked Jun 23 '11 10:06

samach


2 Answers

iframe doesn't have onclick event but we can implement this by using iframe's onload event and javascript like this...

function iframeclick() {
document.getElementById("theiframe").contentWindow.document.body.onclick = function() {
        document.getElementById("theiframe").contentWindow.location.reload();
    }
}


<iframe id="theiframe" src="youriframe.html" style="width: 100px; height: 100px;" onload="iframeclick()"></iframe>

I hope it will helpful to you....

like image 105
Gaurav Agrawal Avatar answered Oct 12 '22 00:10

Gaurav Agrawal


You can use closures to pass parameters:

iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);

However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):

document.getElementById("myFrame").contentDocument.addEventListener(...);
like image 42
Wladimir Palant Avatar answered Oct 11 '22 23:10

Wladimir Palant