How to detect user's click on the link inside the iframe using JavaScript?
Answer: Use the jQuery contents() method If you try to detect or capture a click event inside an iframe simply using jQuery click() method it will not work, because iframe embed a web page within another web page. However, you can still do it on the same domain utilizing the jQuery contents() and load() method.
you can always detect the click on a div using the onclick event without caring what is inside the div . but you can check if the div innerHTML to see if the ad is loaded or it's empty and if the ad was loaded then run your script.
Getting the element in IframegetElementById() method by passing iframe id as an argument. const iframe = document. getElementById("myIframe"); Now, it has and contentWindow property which returns the document object by using that we can access the elements from an Iframe.
yes. getElementsByTagName('iframe') to refer to a nodeList and access elements inside with [0], assuming you're dealing with one. or you can do a loop.
Assuming you have an iframe with ID "myIframe", and the iframe comes from the same domain as the main document, the following will detect a click anywhere in the document. This will also work when the document is editable, which using the document's onclick
property would not:
function iframeClickHandler() {
alert("Iframe clicked");
}
var iframe = document.getElementById("myIframe");
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
if (typeof iframeDoc.addEventListener != "undefined") {
iframeDoc.addEventListener("click", iframeClickHandler, false);
} else if (typeof iframeDoc.attachEvent != "undefined") {
iframeDoc.attachEvent ("onclick", iframeClickHandler);
}
You are able to check iframe load event
onLoad="alert(this.contentWindow.location);"
or on jquery:
$('iframe#yourId').load(function() {
alert("the iframe has been loaded");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With