Q:

How to detect click inside iframe using JavaScript

0

How to detect click inside iframe using JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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.

The following example will display an alert message whenever you click inside the iframe.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Detect Click into iFrame</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<style>
    body{
        padding: 30px;
    }
    iframe{
        width: 100%;
        height: 200px;
        border: 2px solid #ccc;
    }
</style>
<script>
$(document).ready(function(){
    $("iframe").on("load", function(){
        $(this).contents().on("mousedown, mouseup, click", function(){
            alert("Click detected inside iframe.");
        });
    });
});
</script>
</head>
<body>
    <iframe src="/examples/html/div-layout.php"></iframe>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to determine if variable is undefined or null ... >>
<< How to replace multiple spaces with single space i...