I am trying to create a list of videos to be fetched via YouTube. Here is my HTML:
<ul class="videos-list">
<li>
<a href="#" class="vid_thumb">
<img src="http://placehold.it/120x90&text=Loading+.+.+." class="yt_thumb" data-url="http://gdata.youtube.com/feeds/api/videos/f_JRZI9o49w?v=2&alt=jsonc" alt="" />
<span class="duration">Loading...</span></a>
<h5><a href="#"></a></h5>
</li>
<li>
<a href="#" class="vid_thumb">
<img src="http://placehold.it/120x90&text=Loading+.+.+." class="yt_thumb" data-url=
"http://gdata.youtube.com/feeds/api/videos/uHUHFthr2QA?v=2&alt=jsonc" alt="" />
<span class="duration">Loading...</span></a>
<h5><a href="#"></a></h5>
</li>
And here is the javascript:
$(function() {
/**
* Set up JSON parsing for video pages
*/
$("a.vid_thumb").each(function(i) {
$this = $(this);
feed_url = $this.children(".yt_thumb").attr("data-url");
$.getJSON(feed_url, function(json) {
$title = json.data.title;
$url = json.data.player.
default;
$thumb = json.data.thumbnail.sqDefault;
$duration = json.data.duration;
$likes = json.data.likeCount;
$views = json.data.viewCount;
$this.next("h5").html("<a href=" + $url + ">" + $title + "</a>");
$this.children(".duration").html($duration);
$this.children(".yt_thumb").attr("src", $thumb);
$this.next("span.view_count").html($views + " Views");
$this.next("span.upload_date").html($likes + " Likes");
});
});
});
The script is supposed to work on all anchors with class name "vid_thumb". But it works only on the last element.
You can see it in action here: http://jsfiddle.net/ZJNAa/ Am I missing something?
Yes, this is a classic Javascript mistake.
If you omit the var
keyword when declaring a variable, it will be created as a global variable.
What you want are variables local to each function, so make sure to prefix them all with var
.
See here for an updated and working jsFiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With