alias51
alias51

Reputation: 8638

How to apply a jQuery function to a child page in an iframe?

Here's a brainteaser:

I have an iframe in a window, and a navbar that links to it:

<div class="nav">
<a href="link.html" target="iframe-content" id='debug">#Debug<a>
</div>

<iframe name="iframe-content" src="page.html"></iframe>

I've then got a simple jQuery function to inset a class when a link in the nav is clicked.

$(window).load(function() {
    $("#debug").click(function() {
        $('body').toggleClass("debug");
    });
});

Now my question is how do I get the toggleclass to apply to the inline frame (page.html) and not the parent page?

Upvotes: 1

Views: 78

Answers (2)

Brad Christie
Brad Christie

Reputation: 101614

var $iframe = $('iframe[name="iframe-content"]').contents();
$iframe.find('#debug').click(function(){
    $iframe.find('body').toggleClass('debug');
});

Use .contents()

From the docs:

The .contents() method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.

Upvotes: 1

tomaroo
tomaroo

Reputation: 2534

Change

$('body').toggleClass("debug");

To

$('#debug').contents().find('body').toggleClass("debug");

Check out the jQuery documentation for .contents()

Upvotes: 1

Related Questions