How to add click event to a iframe with JQuery

JqueryIframeOnclick

Jquery Problem Overview


I have an iframe on a page, coming from a 3rd party (an ad). I'd like to fire a click event when that iframe is clicked in (to record some in-house stats). Something like:

$('#iframe_id').click(function() {
    //run function that records clicks
});

..based on HTML of:

<iframe id="iframe_id" src="http://something.com"></iframe>

I can't seem to get any variation of this to work. Thoughts?

Jquery Solutions


Solution 1 - Jquery

There's no 'onclick' event for an iframe, but you can try to catch the click event of the document in the iframe:

document.getElementById("iframe_id").contentWindow.document.body.onclick = 
function() {
  alert("iframe clicked");
}

EDIT Though this doesn't solve your cross site problem, FYI jQuery has been updated to play well with iFrames:

$('#iframe_id').on('click', function(event) { });

Update 1/2015 The link to the iframe explanation has been removed as it's no longer available.

Note The code above will not work if the iframe is from different domain than the host page. You can still try to use hacks mentioned in comments.

Solution 2 - Jquery

I was trying to find a better answer that was more standalone, so I started to think about how JQuery does events and custom events. Since click (from JQuery) is just any event, I thought that all I had to do was trigger the event given that the iframe's content has been clicked on. Thus, this was my solution

$(document).ready(function () {
	$("iframe").each(function () {
		//Using closures to capture each one
		var iframe = $(this);
		iframe.on("load", function () { //Make sure it is fully loaded
			iframe.contents().click(function (event) {
				iframe.trigger("click");
			});
		});

		iframe.click(function () {
			//Handle what you need it to do
		});
	});
});

Solution 3 - Jquery

Try using this : iframeTracker jQuery Plugin, like that :

jQuery(document).ready(function($){
	$('.iframe_wrap iframe').iframeTracker({
		blurCallback: function(){
			// Do something when iframe is clicked (like firing an XHR request)
		}
	});
});

Solution 4 - Jquery

> It works only if the frame contains page from the same domain (does > not violate same-origin policy)

See this:

var iframe = $('#your_iframe').contents();

iframe.find('your_clicable_item').click(function(event){
   console.log('work fine');
});

Solution 5 - Jquery

You could simulate a focus/click event by having something like the following. (adapted from https://stackoverflow.com/questions/16037671/window-blur-event-affecting-iframe)

$(window).blur(function () {
  // check focus
  if ($('iframe').is(':focus')) {
    console.log("iframe focused");
    $(document.activeElement).trigger("focus");// Could trigger click event instead
  }
  else {
    console.log("iframe unfocused");
  }                
});

//Test
$('#iframe_id').on('focus', function(e){
  console.log(e);
  console.log("hello im focused");
})

Solution 6 - Jquery

None of the suggested answers worked for me. I solved a similar case the following way:

<a href="http://my-target-url.com" id="iframe-wrapper"></a>
<iframe id="iframe_id" src="http://something.com" allowtrancparency="yes" frameborder="o"></iframe>

The css (of course exact positioning should change according to the app requirements):

#iframe-wrapper, iframe#iframe_id {
  width: 162px;
  border: none;
  height: 21px;
  position: absolute;
  top: 3px;
  left: 398px;
}
#alerts-wrapper {
  z-index: 1000;
}

Of course now you can catch any event on the iframe-wrapper.

Solution 7 - Jquery

You can use this code to bind click an element which is in iframe.

jQuery('.class_in_iframe',jQuery('[id="id_of_iframe"]')[0].contentWindow.document.body).on('click',function(){	
	console.log("triggered !!")
});

Solution 8 - Jquery

Maybe somewhat old but this could probably be useful for people trying to deal with same-domain-policy.

let isOverIframe = null;
$('iframe').hover(function() {
        isOverIframe = true;
    }, function() {
        isOverIframe = false;
    });

$(window).on('blur', function() {
    if(!isOverIframe)
        return;

    // ...
});

Based on https://gist.github.com/jaydson/1780598

Solution 9 - Jquery

You may run into some timing issues depending on when you bind the click event but it will bind the event to the correct window/document. You would probably get better results actually binding to the iframe window though. You could do that like this:

    var iframeWin = $('iframe')[0].contentWindow;
    iframeWin.name = 'iframe';
    $(iframeWin).bind('click', function(event) {
        //Do something
        alert( this.name + ' is now loaded' );
    });

Solution 10 - Jquery

This may be interesting for ppl using Primefaces (which uses CLEditor):

document.getElementById('form:somecontainer:editor')
.getElementsByTagName('iframe')[0].contentWindow
.document.onclick = function(){//do something}

I basically just took the answer from Travelling Tech Guy and changed the selection a bit .. ;)

Solution 11 - Jquery

Solution that work for me :

var editorInstance = CKEDITOR.instances[this.editorId];

			editorInstance.on('focus', function(e) {

				console.log("tadaaa");

			});

Solution 12 - Jquery

You can solve it very easily, just wrap that iframe in wrapper, and track clicks on it.

Like this:

<div id="iframe_id_wrapper"> <iframe id="iframe_id" src="http://something.com"></iframe> </div>

And disable pointer events on iframe itself.

#iframe_id { pointer-events: none; }

After this changes your code will work like expected.

$('#iframe_id_wrapper').click(function() { //run function that records clicks });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJustin LucenteView Question on Stackoverflow
Solution 1 - JqueryTraveling Tech GuyView Answer on Stackoverflow
Solution 2 - JqueryKevinView Answer on Stackoverflow
Solution 3 - JqueryVinceView Answer on Stackoverflow
Solution 4 - JqueryJhonatan S. SouzaView Answer on Stackoverflow
Solution 5 - JqueryJustin FennView Answer on Stackoverflow
Solution 6 - JqueryramiggView Answer on Stackoverflow
Solution 7 - JquerymstView Answer on Stackoverflow
Solution 8 - JqueryMoldevortView Answer on Stackoverflow
Solution 9 - JquerySantosh DangareView Answer on Stackoverflow
Solution 10 - JquerysalgmachineView Answer on Stackoverflow
Solution 11 - JquerymaxiplayView Answer on Stackoverflow
Solution 12 - JqueryVasylChepilView Answer on Stackoverflow