friendlyfire friendlyfire - 6 months ago 18
Javascript Question

when hovering on iframe, how do I trigger a class on element outside of iframe?

I have this page with an iframe. I want to trigger a hover class on an element outside of the iframe. It's not a parent wrapper, it's just a totally different div in the DOM outside of the iframe.

The html:

<body>

<div class="a6-expander-wrapper"></div>
<div class="some-other-div"></div>
<iframe title="My-Iframe" src="//example.com"></iframe>

</body>


The CSS:

.a6-expander-wrapper-hover {
opacity: 1 !important;
}

.a6-expander-wrapper {
height: 44px;
width: 44px;
background-color:red;
opacity: 0;
}


The jquery I'm currently using:

var $iframe = $('iframe[title="My-Iframe"]').contents();
var hoverItem = $('.a6-expander-wrapper');

$iframe.find('*').mouseover(function () {
hoverItem.addClass('a6-expander-wrapper-hover');
}).mouseout(function () {
hoverItem.removeClass('a6-expander-wrapper-hover');
});


Here's a plnkr: http://plnkr.co/edit/2WONkAijTzF2BBsh3p9H?p=preview

None of this is working as you can tell from the plnkr. I'm not sure what to do. Let me know how you'd solve this.

Answer

This should be what you need. No need to target the iFrame contents then select everything inside. You can just put the mouseover on the iFrame itself.

$(function () {
    var iframe = $('iframe[title="My-Iframe"]'); 
    var hoverItem = $('.a6-expander-wrapper');
    $(iframe).mouseover(function () {
        hoverItem.addClass('a6-expander-wrapper-hover');
    }).mouseout(function () {
      hoverItem.removeClass('a6-expander-wrapper-hover');
    });
});

Working example: http://plnkr.co/edit/pJdtn9fX8HT9KWSvrOcW?p=preview

Comments