Nytrix Nytrix - 11 months ago 44
CSS Question

Event within Iframe

I have been having some issues figuring this out.

Page 1

<iframe id="block" src="page2.html" tag> </iframe>

I want to hover in the Iframe and trigger an event if the element that I am hovering has a certain tag.

var attr = $(this).attr('name');
if (typeof attr !== typeof undefined && attr !== false) {
return; //do something

I have tried multiple things but they all seem to want something just a bit different, I understand the firing of a event from a parent class. I don't seem to get how to do this though. The result that I want:

  • I hover in the Iframe over an element that has

  • I get a response on the end of the Iframe that I can work with further

I feel like I got very close but I just need a little piece of connecting code, hopefully someone can explain what I need.

Answer Source

As long as you're on the same domain (you are) there is an easy way:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<iframe id="block" src="page.html" onload="test()"></iframe>
function test() {
    var iframe = document.getElementById('block');
    var doc = iframe.contentDocument || iframe.contentWindow.document;
    var element = doc.getElementById('hover');
    $(element).hover(function() {
        element.append("It's working!\n");

Live example: http://tras.pw/beta/SOverflowJS/