31

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>
Palec
  • 12,743
  • 8
  • 69
  • 138
samach
  • 3,244
  • 10
  • 42
  • 54
  • 1
    as commented by [deepi](http://stackoverflow.com/users/787076/deepi) in an answer: `your code (what you gave on top) is working fine. But it's working when you click exactly on the border not in side box` – Félix Adriyel Gagnon-Grenier May 20 '15 at 01:22

2 Answers2

30

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....

Gaurav Agrawal
  • 4,355
  • 10
  • 42
  • 61
19

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(...);
Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
  • thanks wladimir....u solved half of my prblm...but still this.id is nt working. if i pass "hello world" then it gets printed but for this.id it says "undefinied" in the alert box:S – samach Jun 23 '11 at 11:11
  • Right, that's because you added the listener to the document - and the document doesn't have an ID. You probably want to add it to the ` – Wladimir Palant Jun 23 '11 at 11:17
  • Can you assign that event even when iframe is from different scope? – Flash Thunder Oct 12 '14 at 15:34
  • 1
    @FlashThunder: No, you generally cannot intercept clicks on frames from a different security context (if you could that would be a security issue). – Wladimir Palant Oct 12 '14 at 17:46
  • there is no `.contentDocument` method for me. What am I missing? – A. Savva Mar 07 '17 at 15:11
  • @A.Savva: Could be a lot - like accessing something that isn't an ` – Wladimir Palant Mar 07 '17 at 16:56