1

How can I make my jQuery script run once when an iframe is loading? Here is my code.

My code

$(document).ready(function(){

    //setup a counter to keep our place and cache a selection to the letter wrappers
    var counter = 0,
        $chars  = $(".test").children();

    //setup an interval to animate a letter every so often
    setInterval(function () {

        //select the current letter wrapper and animate it
        $chars.eq(counter).effect( "bounce", {times:1}, 500 );

        //increment the counter so we animate the next letter next time around
        counter++;

        //check if the counter still relates to an index of the $chars collection
        if (counter >= $chars.length) {
            counter = 0;
        }
    }, 250);

});

See my fiddle

I need it to run the script once when my iframe with the id playing_song is loading. Which it can at any point.

What I've tried.

I have tried using .ready but obviously it will only show it when it's ready, not when it's loading.

What I was thinking of doing is making a div with the animation that goes over the static div. But it can't change dynamically, as the iframe can load at any point. This method only works if it's the parent that has been refreshed.

What I'm after

All I want the code to do is run once when the iframe playing_song is loading, which can happen any time, and more than once.

Any suggestions as to how this can be achieved?

2 Answers 2

1

You should be able to do this with plain javascript. Consider this html:

<div class="test">
    <span>M</span>
    <span>u</span>
    <span>s</span>
    <span>i</span>
    <span>f</span>
    <span>y</span>
</div>

<iframe id="foo" href="https://youtube.com" width="300" height="250"></iframe>

Then you could use this javascript to do something when '#foo' starts loading:

var frame_to_load = document.getElementById("foo");
frame_to_load.onload = function() {
    // your js here
}

or with jquery:

$('#foo').on('load', function() {
    // your js here
});

If you have access to your iframe you could also run the js inside a $(document).load(function(){...}); from your iframe.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

0

Use $(document).load to access the load event, in the iframe of course

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.