0

Hey guys, i'm not much of a hardcore coder and so I don't get this basics here.

Imagine I have multiple 's on my page (that contain Youtube Videos via swfobject). All those object's have a unique ID like ytplayer_12, ytplayer_2, ytplayer_56, etc.

I need to run through all of this ytplayer_'s with jquery and add an EventListener to them.

It works just fine! I just wonder if I'm declaring the variables ($ytid, ytid) in the right place - outside of the onYouTubePlayerReady() function? Or should I declare the vars inside of the function? Or even inside of the each-loop?

var $ytid = '',
    ytid = '';

function onYouTubePlayerReady() {

    $('object[id^="ytplayer_"]').each(function() {

        $ytid = $(this).attr('id');
        ytid = document.getElementById($ytid);

        ytid.addEventListener("onStateChange", "foo");

    });
};

I'm just curious what is better in this case and if I'm doing that correct right now? Thank you for your info and help?

2 Answers 2

1

Declaring variables at global scope is bad idea. Move them into function scope.

function onYouTubePlayerReady() {
    var $ytid = '', ytid = '';
    $('object[id^="ytplayer_"]').each(function() {
        $ytid = $(this).attr('id');
        ytid = document.getElementById($ytid);

        ytid.addEventListener("onStateChange", "foo");
    });
};

And you can get rid of them:

function onYouTubePlayerReady() {
    $('object[id^="ytplayer_"]').each(function() {
        this.addEventListener("onStateChange", "foo");
    });
};
Sign up to request clarification or add additional context in comments.

Comments

1

Since the variables' values are unique to each iteration, you definitely need to define them inside the loop. Although you can make life a little easier for yourself and leave out the document.getElementById() call, since this is already pointing to the object you're looking for:

var ytid = this;
var $ytid = $(this).attr('id'); // only if you need the id for something other than instantiating the ytid variable

I used var as per gor's suggestion not to make the variables global

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.