I am trying to develope a slider, which change every 5 seconds if the user doens´t hit the back- or forward-button.
But if he (the user) does, the interval fires multiple times... why?
I save the Interval in a variable and clear this variable so i don´t know why this dont work... but see yourself:
jQuery.fn.extend({
wrGallery: function() {
return this.each(function() {
// config
var wrClassActive = 'galerie_active';
var wrTime = 5000;
// wrAutomaticDirection gibt an, in welche Richtung
// die Gallerie bei automatischem Wechsel wechseln soll (True = vorwärts/rechts)
var wrAutomaticDirection = true;
var wr = jQuery(this);
var wrGalleryContents = wr.find('.galerie_content');
var wrGalleryContentsFirst = wr.find('.galerie_content:first-child');
var wrBtnBack = wr.find('#galerie_backward');
var wrBtnFor = wr.find('#galerie_forward');
var wrTimer = 0;
var wrI = 0;
var wrOldActiveID = 0;
var wrInit = function() {
wrGalleryContents.each(function() {
wrI++;
jQuery(this).attr('id', wrI);
jQuery(this).css({
display: 'none',
opacity: 0
})
})
wrGalleryContentsFirst.css({
display: 'block',
opacity: 1
})
wrGalleryContentsFirst.addClass('galerie_active')
wrStartTimer();
}
var wrStartTimer = function() {
wrTimer = setInterval(function() {
wrChange(wrAutomaticDirection);
}, wrTime)
}
var wrStoppTimer = function() {
clearInterval(wrTimer);
wrTimer = 0;
}
var wrBackground = function(wrDirection) {
wrOldActiveID = wr.find('.' + wrClassActive).attr('id');
wr.find('.' + wrClassActive).removeClass(wrClassActive);
if (wrDirection) {
wrOldActiveID++;
if (wrOldActiveID <= wrI) {
wr.find('#' + wrOldActiveID).addClass(wrClassActive);
} else {
wr.find('#1').addClass(wrClassActive);
}
} else {
wrOldActiveID--;
if (wrOldActiveID <= wrI) {
wr.find('#' + wrOldActiveID).addClass(wrClassActive);
} else {
wr.find('#3').addClass(wrClassActive);
}
}
}
var wrAnimate = function(wrDirection) {
wrGalleryContents.stop().animate({
opacity: 0
}, 500);
wr.find('.' + wrClassActive).css({
display: 'block'
})
wr.find('.' + wrClassActive).stop().animate({
opacity: 1
}, 500);
}
var wrChange = function(wrDirection) {
wrBackground(wrDirection);
wrAnimate(wrDirection);
}
wr.on('mouseenter', function() {
wrStoppTimer();
});
wr.on('mouseleave', function() {
wrStartTimer();
});
wrBtnBack.on('click', function() {
wrStoppTimer();
wrStartTimer();
wrChange(false);
});
wrBtnFor.on('click', function() {
wrStoppTimer();
wrStartTimer();
wrChange(true);
});
wrInit();
});
}
});
Thanks for reading ;-)
Add a wrStoppTimer() call at the beginning of wrStartTimer:
var wrStartTimer = function() {
wrStoppTimer();
wrTimer = setInterval(function() {
wrChange(wrAutomaticDirection);
}, wrTime)
};
Also in the two click functions you have:
wrStoppTimer();
wrStartTimer();
you can remove that wrStoppTimer() call since wrStartTimer() will call it for you now.
One other thing: if you define functions the way you're doing with var name = function() { ... } you should put a semicolon after the closing } as in the updated code above.
Related
$.starRating = function(options) {
var defaults = {
onClickCallBack: null,
};
var settings = $.extend({}, defaults, options);
var onClickCallBack = settings.onClickCallBack;
$(".rating-star span").hover(function() {
var hoverValue = parseInt($(this).attr('data-val'));
highlightStars(hoverValue, 'hover');
});
$(".rating-star span").mouseout(function() {
$(".rating-star span").each(function() {
$(this).removeClass("hover");
});
});
$(".rating-star span").click(function() {
if (onClickCallBack != null) {
var rate = parseInt($(this).attr('data-val'));
var id = parseInt($(this).attr('data-id'));
highlightStars(rate, 'clicked');
onClickCallBack(rate, id);
}
});
function highlightStars(count, cssClass) {
var itemValue = 0;
$(".rating-star span").each(function() {
itemValue = parseInt($(this).attr('data-val'));
if (itemValue <= count) {
$(this).addClass(cssClass);
} else {
$(this).removeClass(cssClass);
}
});
}
function highlightRating(rate) {
var roundedRate = Math.round(rate);
highlightStars(roundedRate, 'clicked');
}
return {
highlightRatingStars: function(rate) {
highlightRating(rate);
}
}
}
$(function() {
var starRatingFunction = $.starRating({
onClickCallBack: onRatingStar
});
function onRatingStar(rate, id) {
$("#1_star_input").val(rate);
$("#2_star_input").val(rate);
$("#3_star_input").val(rate);
loadData();
}
});
Hi guys, I have some star rating jquery code, right now I can use one set of stars and retrieve the values but, I want to be able to get values for three different sets of stars. i'm only getting values for #1_star_input and it does the same for the other two.
I have this code and not everything working as expected:
ORYGINAL CODE - START
function reminder_set_now$id(this_val,this_change) {
$( '#set_reminder' ).on({
mousedown: function() {
$(this).data('timer', setTimeout(function() {
if (this_change = 1) {
alert('1!');
sr_change_click_e1();
}
else if (this_change = 2) {
alert('2!');
sr_change_click_e2();
}
else {
alert('3!');
sr_change_click_e3();
}
}, 3000));
},
mouseup: function() {
clearTimeout( $(this).data('timer') );
}
});
}
function sr_change_click_e1() {
var clickfun = $("#set_reminder").attr("onClick");
var funname = clickfun.substring(0,clickfun.indexOf("("));
$("#set_reminder").attr("onclick",funname+"(\'2\',\'2\')");
}
function sr_change_click_e2() {
var clickfun = $("#set_reminder").attr("onClick");
var funname = clickfun.substring(0,clickfun.indexOf("("));
$("#set_reminder").attr("onclick",funname+"(\'3\',\'3\')");
}
function sr_change_click_e3() {
var clickfun = $("#set_reminder").attr("onClick");
var funname = clickfun.substring(0,clickfun.indexOf("("));
$("#set_reminder").attr("onclick",funname+"(\'1\',\'1\')");
}
Reminder
ORYGINAL CODE - END
And 2 issues with it:
Alert1 doesnt display after I hold for 3 seconds for the first time but if I click on it first and then hold it with the second click.
every other hold display always alert1 not 2 and then 3
UPDATED CODE - START
function reminder_set_now(this_val,this_change) {
var t_change = this_change;
$( '#set_reminder' ).on({
mousedown: function() {
$(this).data('timer', setTimeout(function() {
if(t_change == 1) {
sr_change_click_e1();
}
else if (t_change == 2) {
sr_change_click_e2();
}
else {
sr_change_click_e3();
}
}, 3000));
},
mouseup: function() {
clearTimeout( $(this).data('timer') );
}
});
}
function sr_change_click_e1() {
var clickfun = $("#set_reminder").attr("onmousedown");
var funname = clickfun.substring(0,clickfun.indexOf("("));
$("#set_reminder").attr("onmousedown",funname+"(\'2\',\'2\')");
}
function sr_change_click_e2() {
var clickfun = $("#set_reminder").attr("onmousedown");
var funname = clickfun.substring(0,clickfun.indexOf("("));
$("#set_reminder").attr("onmousedown",funname+"(\'3\',\'3\')");
}
function sr_change_click_e3() {
var clickfun = $("#set_reminder").attr("onmousedown");
var funname = clickfun.substring(0,clickfun.indexOf("("));
$("#set_reminder").attr("onmousedown",funname+"(\'1\',\'1\')");
}
Reminder
UPDATED CODE - END
Any suggestions where I am wrong please.
I have this code:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0;
var timer = setInterval(function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
clearInterval(timer);
}
});
$el.mouseout({
timer;
});
});
I want to suspend the function on mouseover and resume it on mouse out but I cant get the latter right. How can I resume it?
Thank you.
There are two ways:
Set a flag that the function being called by the interval checks, and have the function not do anything if it's "suspended."
Start the interval again via a new setInterval call. Note that the old timer value cannot be used for this, you need to pass in the code again.
Example of #1:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0,
suspend = false; // The flag
var timer = setInterval(function() {
if (!suspend) { // Check it
$el.removeClass("current").eq(++c % tot).addClass("current");
}
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
suspend = true; // Set it
},
mouseleave: function(e) {
suspend = false; // Clear it
}
});
});
Example of #2:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0,
timer = 0;
// Move this to a reusable function
var intervalHandler = function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
};
// Probably best to encapsulate the logic for starting it rather
// than repeating that logic
var startInterval = function() {
timer = setInterval(intervalHandler, 3000);
};
// Initial timer
startInterval();
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
clearInterval(timer); // Stop it
}
mouseleave: function(e) {
startInterval(); // Start it
}
});
});
Checkout these prototypes:
//Initializable
function Initializable(params) {
this.initialize = function(key, def, private) {
if (def !== undefined) {
(!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
}
};
}
function PeriodicJobHandler(params) {
Initializable.call(this, params);
this.initialize("timeout", 1000, true);
var getTimeout = function() {
return params.timeout;
};
var jobs = [];
function Job(params) {
//expects params.job() function
Initializable.call(this, params);
this.initialize("timeout", getTimeout(), true);
this.initialize("instant", false);
var intervalID = undefined;
this.start = function() {
if (intervalID !== undefined) {
return;
}
if (this.instant) {
params.job(true);
}
intervalID = setInterval(function() {
params.job(false);
}, params.timeout);
};
this.stop = function() {
clearInterval(intervalID);
intervalID = undefined;
};
}
this.addJob = function(params) {
jobs.push(new Job(params));
return jobs.length - 1;
};
this.removeJob = function(index) {
jobs[index].stop();
jobs.splice(index, 1);
};
this.startJob = function(index) {
jobs[index].start();
};
this.stopJob = function(index) {
jobs[index].stop();
};
}
Initializable simplifies member initialization, while PeriodicJobHandler is able to manage jobs in a periodic fashion. Now, let's use it practically:
var pjh = new PeriodicJobHandler({});
//It will run once/second. If you want to change the interval time, just define the timeout property in the object passed to addJob
var jobIndex = pjh.addJob({
instant: true,
job: function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}
});
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0;
var timer = setInterval(function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
jobIndex.stop();
}
});
$el.mouseout({
jobIndex.start();
});
});
With Javascript, it is much easy and efficient.
You can change the interval in setInterval function.
It is checking whether suspend variable is false or true, here suspend variable is setting to true, if mouseEnter function is called and set to false if mouseLeave function is called.
var displayMsg = document.getElementById('msg').innerHTML;
var i = 0;
var suspend = false;
var sequence = setInterval(update, 100);
function update() {
if (suspend == false) {
var dispalyedMsg = '';
dispalyedMsg = displayMsg.substring(i, displayMsg.length);
dispalyedMsg += ' ';
dispalyedMsg += displayMsg.substring(0, i);
document.getElementById('msg').innerHTML = dispalyedMsg;
i++;
if (i > displayMsg.length) {
i = 0;
}
}
}
document.getElementById('msg').addEventListener('mouseenter', mouseEnter);
document.getElementById('msg').addEventListener('mouseleave', mouseLeave);
function mouseEnter() {
suspend = true;
}
function mouseLeave() {
suspend = false;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#msg {
width: 680px;
height: 100px;
border: 1px solid #ccc;
padding-left: 15px;
}
</style>
</head>
<body>
<div id="msg">
Today is only 15% discount. Hurry up to grab. Sale will end sooooooooooooon!!!!
</div>
<div id="output"></div>
<script src="marquee.js"></script>
</body>
</html>
The question is very simple but also a bit theoretical.
Let's imagine you have a long JQuery script which modifies and animate the graphics of the web site. It's objective is to handle the UI. The UI has to be responsive so the real need for this JQuery is to mix some state of visualization (sportlist visible / not visible) with some need due to Responsive UI.
Thinking from an MVC / AngularJS point of view. How should a programmer handle that?
How to refactor JS / JQuery code to implement separation of concerns described by MVC / AngularJS?
I provide an example of JQuery code to speak over something concrete.
$.noConflict();
jQuery(document).ready(function ($) {
/*variables*/
var sliderMenuVisible = false;
/*dom object variables*/
var $document = $(document);
var $window = $(window);
var $pageHost = $(".page-host");
var $sportsList = $("#sports-list");
var $mainBody = $("#mainBody");
var $toTopButtonContainer = $('#to-top-button-container');
/*eventHandlers*/
var displayError = function (form, error) {
$("#error").html(error).removeClass("hidden");
};
var calculatePageLayout = function () {
$pageHost.height($(window).height());
if ($window.width() > 697) {
$sportsList.removeAttr("style");
$mainBody
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
if ($(".betslip-access-button")[0]) {
$(".betslip-access-button").fadeIn(500);
}
sliderMenuVisible = false;
} else {
$(".betslip-access-button").fadeOut(500);
}
};
var formSubmitHandler = function (e) {
var $form = $(this);
// We check if jQuery.validator exists on the form
if (!$form.valid || $form.valid()) {
$.post($form.attr("action"), $form.serializeArray())
.done(function (json) {
json = json || {};
// In case of success, we redirect to the provided URL or the same page.
if (json.success) {
window.location = json.redirect || location.href;
} else if (json.error) {
displayError($form, json.error);
}
})
.error(function () {
displayError($form, "Login service not available, please try again later.");
});
}
// Prevent the normal behavior since we opened the dialog
e.preventDefault();
};
//preliminary functions//
$window.on("load", calculatePageLayout);
$window.on("resize", calculatePageLayout);
//$(document).on("click","a",function (event) {
// event.preventDefault();
// window.location = $(this).attr("href");
//});
/*evet listeners*/
$("#login-form").submit(formSubmitHandler);
$("section.navigation").on("shown hidden", ".collapse", function (e) {
var $icon = $(this).parent().children("button").children("i").first();
if (!$icon.hasClass("icon-spin")) {
if (e.type === "shown") {
$icon.removeClass("icon-caret-right").addClass("icon-caret-down");
} else {
$icon.removeClass("icon-caret-down").addClass("icon-caret-right");
}
}
toggleBackToTopButton();
e.stopPropagation();
});
$(".collapse[data-src]").on("show", function () {
var $this = $(this);
if (!$this.data("loaded")) {
var $icon = $this.parent().children("button").children("i").first();
$icon.removeClass("icon-caret-right icon-caret-down").addClass("icon-refresh icon-spin");
console.log("added class - " + $icon.parent().html());
$this.load($this.data("src"), function () {
$this.data("loaded", true);
$icon.removeClass("icon-refresh icon-spin icon-caret-right").addClass("icon-caret-down");
console.log("removed class - " + $icon.parent().html());
});
}
toggleBackToTopButton();
});
$("#sports-list-button").on("click", function (e)
{
if (!sliderMenuVisible)
{
$sportsList.animate({ left: "0" }, 500);
$mainBody.animate({ left: "85%" }, 500)
.bind('touchmove', function (e2) { e2.preventDefault(); })
.addClass('stop-scroll');
$(".betslip-access-button").fadeOut(500);
sliderMenuVisible = true;
}
else
{
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500).removeAttr("style")
.unbind('touchmove').removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
}
e.preventDefault();
});
$mainBody.on("click", function (e) {
if (sliderMenuVisible) {
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500)
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
e.stopPropagation();
e.preventDefault();
}
});
$document.on("click", "div.event-info", function () {
if (!sliderMenuVisible) {
var url = $(this).data("url");
if (url) {
window.location = url;
}
}
});
function whatDecimalSeparator() {
var n = 1.1;
n = n.toLocaleString().substring(1, 2);
return n;
}
function getValue(textBox) {
var value = textBox.val();
var separator = whatDecimalSeparator();
var old = separator == "," ? "." : ",";
var converted = parseFloat(value.replace(old, separator));
return converted;
}
$(document).on("click", "a.selection", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/Add/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
var urlHoveringBtn = "/" + _language + '/BetSlip/AddHoveringButton/' + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(urlHoveringBtn).done(function (dataBtn) {
if ($(".betslip-access-button").length == 0 && dataBtn.length > 0) {
$("body").append(dataBtn);
}
});
$.ajax(url).done(function (data) {
if ($(".betslip-access").length == 0 && data.length > 0) {
$(".navbar").append(data);
$pageHost.addClass("betslipLinkInHeader");
var placeBetText = $("#live-betslip-popup").data("placebettext");
var continueText = $("#live-betslip-popup").data("continuetext");
var useQuickBetLive = $("#live-betslip-popup").data("usequickbetlive").toLowerCase() == "true";
var useQuickBetPrematch = $("#live-betslip-popup").data("usequickbetprematch").toLowerCase() == "true";
if ((isLive && useQuickBetLive) || (!isLive && useQuickBetPrematch)) {
var dialog = $("#live-betslip-popup").dialog({
modal: true,
dialogClass: "fixed-dialog"
});
dialog.dialog("option", "buttons", [
{
text: placeBetText,
click: function () {
var placeBetUrl = "/" + _language + "/BetSlip/QuickBet?amount=" + getValue($("#live-betslip-popup-amount")) + "&live=" + $this.data("live");
window.location = placeBetUrl;
}
},
{
text: continueText,
click: function () {
dialog.dialog("close");
}
}
]);
}
}
if (data.length > 0) {
$this.addClass("in-betslip");
}
});
e.preventDefault();
});
$(document).on("click", "a.selection.in-betslip", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/RemoveAjax/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(url).done(function (data) {
if (data.success) {
$this.removeClass("in-betslip");
if (data.selections == 0) {
$(".betslip-access").remove();
$(".betslip-access-button").remove();
$(".page-host").removeClass("betslipLinkInHeader");
}
}
});
e.preventDefault();
});
$("section.betslip .total-stake button.live-betslip-popup-plusminus").click(function (e) {
if (sliderMenuVisible) {
return;
}
e.preventDefault();
var action = $(this).data("action");
var amount = parseFloat($(this).data("amount"));
if (!isNumeric(amount)) amount = 1;
var totalStake = $("#live-betslip-popup-amount").val();
if (isNumeric(totalStake)) {
totalStake = parseFloat(totalStake);
} else {
totalStake = 0;
}
if (action == "decrease") {
if (totalStake < 1.21) {
totalStake = 1.21;
}
totalStake -= amount;
} else if (action == "increase") {
totalStake += amount;
}
$("#live-betslip-popup-amount").val(totalStake);
});
toggleBackToTopButton();
function toggleBackToTopButton() {
isScrollable() ? $toTopButtonContainer.show() : $toTopButtonContainer.hide();
}
$("#to-top-button").on("click", function () { $("#mainBody").animate({ scrollTop: 0 }); });
function isScrollable() {
return $("section.navigation").height() > $(window).height() + 93;
}
var isNumeric = function (string) {
return !isNaN(string) && isFinite(string) && string != "";
};
function enableQuickBet() {
}
});
My steps in such cases are:
First of all write (at least) one controller
Replace all eventhandler with ng-directives (ng-click most of all)
Pull the view state out of the controller with ng-style and ng-class. In most of all cases ng-show and ng-hide will be sufficed
If there is code that will be used more than once, consider writing a directive.
And code that has nothing todo with the view state - put the code in a service
write unit tests (i guess there is no one until now:) )
I am using the tubeplayer plugin to generate video playlists for my hot 100 music chart website http://beta.billboard.fm.
I pull playlist data and generate video playlists based on that data. The problem is that I currently am manually entering the youtube video ID for initial video load video on the home page, where I would like to create a variable that dynamically pulls the first youtube video id and inserts after initialVideo
So I am trying to create a variable that pulls track #1 from the hot 100 year playlist that I can place in the standard plugin parameters:
I will define it as var initialVideoID =
<script>
// IE workaround
function JSONQuery(url, callback) {
if ($.browser.msie && window.XDomainRequest) {
// alert('ie');
// var url = "http://gdata.youtube.com/feeds/api/videos?q=cher&category=Music&alt=json";
// Use Microsoft XDR
var xdr = new XDomainRequest();
xdr.open("get", url);
xdr.onerror = function () {
console.log('we have an error!');
}
xdr.onprogress = function () {
// console.log('this sucks!');
};
xdr.ontimeout = function () {
console.log('it timed out!');
};
xdr.onopen = function () {
console.log('we open the xdomainrequest');
};
xdr.onload = function () {
// XDomainRequest doesn't provide responseXml, so if you need it:
var dom = new ActiveXObject("Microsoft.XMLDOM");
dom.async = true;
dom.loadXML(xdr.responseText);
// alert(xdr.responseText);
callback(jQuery.parseJSON(xdr.responseText));
// alert(data.feed.entry[0].media$group.media$content[0].url);
// alert("ie");
};
xdr.send();
} else {
$.getJSON(url, callback);
}
};
var yearMap = [];
createYearMap();
function createYearMap() {
yearMap["1940"] = [1946, 1947, 1948, 1949];
yearMap["2010"] = [2010, 2011, 2012];
for (var i = 195; i < 201; i++) {
var curDecade = i * 10;
yearMap[curDecade.toString()] = [];
for (var j = 0; j < 10; j++) {
yearMap[curDecade][j] = curDecade + j;
}
}
}
// console.log(yearMap["2010"]);
(function ($) {
$(window).ready(function () {
// alert("before get");
// $.get("test.htm", function(data) {
// // var fileDom = $(data);
// // alert("get callback");
// $("#jqueryTest").html(data);
// });
// setInterval(function(){alert("Hello")},3000);
$(".song-description").mCustomScrollbar();
// var url = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=26178ccca6d355d31b413f3d54be5332&artist=" +"pink floyd" + "&track=" + "money" + "&format=json";
// JSONQuery(url, function(data) {
// if (data.track) {
// if (data.track.wiki) {
// $("#song-info").html(data.track.wiki.summary);
// } else {
// $("#song-info").html("No song info found");
// }
// } else {
// $("#song-info").html("No song info found");
// console.log("artist not found");
// }
// $(".song-description").mCustomScrollbar("update");
// });
// $("#example tbody tr").click(function() {
// selectPlaying(this, true);
// });
jQuery(".youtube-video").tubeplayer({
width: 300, // the width of the player
height: 225, // the height of the player
allowFullScreen: "true", // true by default, allow user to go full screen
initialVideo: var initialvideoID, // the video that is loaded into the player
preferredQuality: "default", // preferred quality: default, small, medium, large, hd720
showinfo: true, // if you want the player to include details about the video
modestbranding: true, // specify to include/exclude the YouTube watermark
wmode: "opaque", // note: transparent maintains z-index, but disables GPU acceleratio
theme: "dark", // possible options: "dark" or "light"
color: "red", // possible options: "red" or "white"
onPlayerEnded: function () {
videoEnded();
},
onPlayerPlaying: function (id) {
setIconToPause();
}, // after the play method is called
onPlayerPaused: function () {
setIconToPlay();
}, // after the pause method is called
onStop: function () {}, // after the player is stopped
onSeek: function (time) {}, // after the video has been seeked to a defined point
onMute: function () {}, // after the player is muted
onUnMute: function () {} // after the player is unmuted
});
setInterval(function () {
updateProgressBar()
}, 1000);
loadPlaylist("hot100", true);
});
})(jQuery);
var initialvideoID = "yyDUC1LUXSU"
function videoEnded() {
nextVideo();
}
var intervalTimer;
function startPlayer() {
jQuery(".youtube-video").tubeplayer("play");
playing = true;
clearInterval(intervalTimer);
intervalTimer = setInterval(function () {
updateProgressBar()
}, 1000);
setIconToPause();
}
function setIconToPause() {
var button = $(".icon-play");
if (button) {
button.removeClass("icon-play")
button.addClass("icon-pause");
}
}
function setIconToPlay() {
var button = $(".icon-pause");
if (button) {
button.removeClass("icon-pause")
button.addClass("icon-play");
}
}
function pausePlayer() {
jQuery(".youtube-video").tubeplayer("pause");
playing = false;
clearInterval(intervalTimer);
setIconToPlay();
}
function selectPlaying(item, autoStart) {
var nowPlayingItem = $(".nowPlaying");
if (nowPlayingItem) {
nowPlayingItem.removeClass("nowPlaying");
}
$(item).addClass("nowPlaying");
var aPos = $('#example').dataTable().fnGetPosition(item);
var aData = $('#example').dataTable().fnGetData(aPos);
if (aData[3]) {
// $("#song-info").html("Loading song info...");
$("#song-info").html("");
var url = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=26178ccca6d355d31b413f3d54be5332&artist=" + aData[1] + "&track=" + aData[2] + "&format=json";
JSONQuery(url, function (data) {
if (data.track) {
if (data.track.wiki) {
$("#song-info").html(data.track.wiki.summary);
} else {
$("#song-info").html("No song info found");
}
} else {
$("#song-info").html("No song info found");
console.log("artist not found");
}
// $(".song-description").mCustomScrollbar("update");
});
$(".info-rank").html("#" + aData[0]);
$(".info-artist").html(aData[1]);
$(".info-song").html(aData[2]);
$(".info-year").html($("#navYear").html());
var ytId = aData[3];
if (autoStart) {
jQuery(".youtube-video").tubeplayer("play", ytId);
setIconToPause();
} else {
jQuery(".youtube-video").tubeplayer("cue", ytId);
setIconToPlay();
}
clearInterval(intervalTimer);
intervalTimer = setInterval(function () {
updateProgressBar()
}, 1000);
playing = true;
// alert("youtube video id is: " + ytId);
} else {
alert("no youtube id");
}
}
function previousVideo() {
var curPlaying = $(".nowPlaying")[0];
var nextItem;
if (curPlaying) {
nextItem = $('#example').dataTable().fnGetAdjacentTr(curPlaying, false);
if (!nextItem) {
nextItem = $('#example').dataTable().fnGetNodes($('#example').dataTable().fnSettings().fnRecordsTotal() - 1);
}
} else {
nextItem = $('#example').dataTable().fnGetNodes(0);
}
selectPlaying(nextItem, true);
}
function nextVideo() {
var curPlaying = $(".nowPlaying")[0];
var nextItem;
if (curPlaying) {
nextItem = $('#example').dataTable().fnGetAdjacentTr(curPlaying, true);
if (!nextItem) {
nextItem = $('#example').dataTable().fnGetNodes(0);
}
} else {
nextItem = $('#example').dataTable().fnGetNodes(0);
}
selectPlaying(nextItem, true);
}
function updateProgressBar() {
// console.log("update bar");
myData = jQuery(".youtube-video").tubeplayer("data");
// console.log("update progress bar: " + (myData.currentTime / myData.duration * 100) + "%");
$(".bar").width((myData.currentTime / myData.duration * 100) + "%");
}
var playing = false;
function playPauseClick() {
if (playing) {
pausePlayer();
} else {
startPlayer();
}
}
function loadPlaylist(year) {
loadPlaylist(year, false);
}
function loadPlaylist(year, cueVideo) {
$.get("playlist/" + year + "playlist.txt", function (data) {
// var fileDom = $(data);
// alert("get callback");
// $("#playlistContents").html(data);
// $('#example').dataTable().fnAddData(data);
// var obj = eval("[[1,2,3],[1,2,3]]");
// obj = eval(data.toString());
obj = $.parseJSON(data);
// console.log(obj);
$('#example').dataTable().fnClearTable();
$('#example').dataTable().fnAddData(obj);
// $("#example tbody tr").click(function() {
// selectPlaying(this, true);
// });
if (year == "hot100") {
$("#navYear").html("Weekly Hot 100");
$("#navYearLabel").hide();
} else {
$("#navYear").html(year);
$("#navYearLabel").show();
}
if (cueVideo) {
selectPlaying($('#example').dataTable().fnGetNodes(0), false);
}
// $('#example').dataTable().fnAddData(data);
});
}
function modalDecadeClick(decade) {
var string = "";
if (decade == 'hot100') {
loadPlaylist("hot100");
$('#modal-example-decade').modal('hide');
$('#modal-year').modal('hide');
} else {
for (var i = 0; i < yearMap[decade].length; i++) {
string += '<li>' + yearMap[decade][i] + '</li>';
}
$('#modal-example-decade').modal('hide');
$('#specific-year-list').empty();
$('#specific-year-list').html(string).contents();
}
}
function modalYearClick(node) {
var year = parseInt($(node).children("li").html());
// console.log($(node).children("li").html());
$('#modal-year').modal('hide');
loadPlaylist(year);
}
function progressBarClick(e) {
var seekPercent = (e.pageX - $(".progress:first").offset().left) / $(".progress:first").width();
var seekTime = jQuery(".youtube-video").tubeplayer("data").duration * seekPercent;
jQuery(".youtube-video").tubeplayer("seek", seekTime);
}
var minYear = 1946;
var maxYear = 2012;
function nextYear() {
var year = $("#navYear").html();
if (year == "Weekly Hot 100") {
alert("Max year is " + maxYear);
return;
}
year = parseInt($("#navYear").html());
year++;
if (year > maxYear) {
loadPlaylist("hot100");
return;
}
loadPlaylist(year);
}
function prevYear() {
var year = $("#navYear").html();
if (year == "Weekly Hot 100") {
loadPlaylist(2012);
return;
}
year = parseInt($("#navYear").html());
year--;
if (year < minYear) {
alert("Min year is " + minYear);
return;
}
loadPlaylist(year);
}
function closeFilter() {
toggle_visibility('toggle-filter');
var oTable = $('#example').dataTable();
// Sometime later - filter...
oTable.fnFilter('');
}
</script>