Adding or Creating "forEach" to function in javascript / jquery - javascript

First and foremost I'd like to thank everyone who participates contributes and adds to the forums / community, you guys provide an extremely appreciated and valued resource to those that just need information and assistance when needed. Simple thing to do for some, but to many it means volumes. So thanks again.
I'm no coding or script expert but I definitely learn quick and know enough to get around and translate (especially if the language is explained) attempting to get a player on my site to populate and propagate a playlist based on an uploaded file string.
So far I have the player completely up and running, it properly parses the upload links to display the separate mp3 files to play as well as the separate description information per file.
The problem is when I click the play button all of the files mp3 play at once. I'm almost positive I need to add a forEach statement or something along those lines either here:
$(function(){
$('#player1').plp({
'volume': 80,
'playlist':[
{"title":"{$pic.video_descr }",
"author":"{.Me}",
"cover":"files/covers/fullfilename",
"mfile":"{.siteurl}{.fullfilename}",
"duration":"330"},
]
});
});
for each title, author, cover, duration and mfile,
or somewhere around here
function init_track(i){
cpl = i;
$this.find('.playlist span').removeClass('active');
$this.find('.playlist span:eq('+i+')').addClass('active');
$audio.src = options.playlist[i].mfile;
$this.find('.title').html(options.playlist[i].title);
$this.find('.author').html(options.playlist[i].author);
$this.find('.cover').attr('src', options.playlist[i].cover);
}
for(i=0; i < options.playlist.length; i++){
$this.find('.playlist').append('<span>'+options.playlist[i].author+' - '+options.playlist[i].title+'</span>');
}
init_track(cpl);
$this.find('.playlist span').click(function(){
init_track($(this).index());
});
here is the full .js
(function($) {
jQuery.fn.plp = function(options) {
var options = $.extend({
volume: 50,
playlist: [],
autostart: false
}, options);
var make = function() {
var $this = $(this);
var cpl = 0;
var $audio = new Audio();
var isrand = false;
$this.find('.volume').slider({
animate: true,
range: 'min',
value: options.volume,
min: 0,
max: 1,
step: 0.01,
slide: function(event, ui) {
$audio.volume = ui.value;
}
});
$this.find('.long').slider({
animate: true,
range: 'min',
value: 0,
min: 0,
max: 60,
step: 1,
slide: function(event, ui) {
$audio.currentTime = ui.value;
}
});
$audio.addEventListener('canplay', function(_event) {
if ($audio.duration) {
$this.find('.all').html(' / ' + toMinit($audio.duration));
$this.find('.long').slider({
'max': $audio.duration
});
} else {
this.find('.all').html(' / ' + toMinit(options.playlist[cpl].duration));
$this.find('.long').slider({
'max': options.playlist[cpl].duration
});
}
if (options.autostart) {
$audio.play();
$this.find('.tlb_stop').addClass('isplay');
} else {
options.autostart = true;
}
});
$audio.addEventListener('ended', function() {
if (isrand) {
var rand = cpl;
while (rand == cpl) {
rand = Math.floor(Math.random((options.playlist.length)));
}
init_track(rand);
} else {
if (cpl == options.playlist.length - 1) {
cpl = -1;
}
init_track(cpl + 1);
}
});
$audio.addEventListener('timeupdate', function() {
$this.find('.long').slider({
'value': $audio.currentTime
});
$this.find('.current').html(toMinit($audio.currentTime));
});
function toMinit(val) {
val = Number(val);
var ost = Math.floor(val % 60);
var tm = Math.floor(val / 60);
if (ost < 10) {
ost = '0' + ost;
}
if (tm < 10) {
tm = '0' + tm;
}
return tm + ':' + ost;
}
function init_track(i) {
cpl = i;
$this.find('.playlist span').removeClass('active');
$this.find('.playlist span:eq(' + i + ')').addClass('active');
$audio.src = options.playlist[i].mfile;
$this.find('.title').html(options.playlist[i].title);
$this.find('.author').html(options.playlist[i].author);
$this.find('.cover').attr('src', options.playlist[i].cover);
}
for (i = 0; i < options.playlist.length; i++) {
$this.find('.playlist').append('<span>' + options.playlist[i].author + ' - ' + options.playlist[i].title + ' < /span>');
}
init_track(cpl);
$this.find('.playlist span').click(function() {
init_track($(this).index());
});
$this.find('.tlb_prev').click(function() {
if (isrand) {
var rand = cpl;
while (rand == cpl) {
rand = Math.floor(Math.random() *
(options.playlist.length));
}
init_track(rand);
} else {
if (cpl === 0) {
cpl = options.playlist.length;
}
init_track(cpl - 1);
}
return false;
});
$this.find('.tlb_stop').click(function() {
if ($audio.paused) {
$audio.play();
$(this).addClass('isplay');
} else {
$audio.pause();
$(this).removeClass('isplay');
}
return false;
});
$this.find('.tlb_next').click(function() {
if (isrand) {
var rand = cpl;
while (rand == cpl) {
rand = Math.floor(Math.random() *
(options.playlist.length));
}
init_track(rand);
} else {
if (cpl == options.playlist.length - 1) {
cpl = -1;
}
init_track(cpl + 1);
}
return false;
});
$this.find('.vol_icon').click(function() {
$(this).toggleClass('active');
$this.find('.volume').fadeToggle(100);
return false;
});
$this.find('.pl_icon').click(function() {
$(this).toggleClass('active');
$this.find('.playlist').fadeToggle(100);
return false;
});
$this.find('.while_icon').click(function() {
if ($audio.loop) {
$(this).removeClass('active');
$audio.loop = false;
} else {
$(this).addClass('active');
$audio.loop = true;
}
return false;
});
$this.find('.rand').click(function() {
if (isrand) {
$(this).removeClass('active');
isrand = false;
} else {
$(this).addClass('active');
isrand = true;
}
return false;
});
};
return this.each(make);
};
})(jQuery);
Here is the PHP/HTML (smarty template):
<script type="text/javascript" src="/jquery.js">
</script>
<script type="text/javascript" src="/player.js">
</script>
{foreach item=pic from=$pics} {/foreach}
<table>
<tr>
<td valign="middle">
{if $pic.ext == 'yt'}
<div style=
"background-image:url('http://img.youtube.com/vi/{$pic.ytref}/0.jpg');">
<div style="height:120px; max-width:120px;">
<a alt="video no {$pic.videono}" href=
"http://www.youtube.com/v/{$pic.ytref}&fs=1&rel=0::"
title="Click to Play"><img height="120" onmouseout=
"this.src='playbtred.png'" onmouseover=
"this.src='playbty.png'" src="playbtred.png" width=
"120"></a>
</div>
</div>
<div style=
"width:60%;word-wrap: break-word;padding-bottom:20px;">
{$pic.video_descr }
</div>{elseif $pic.ext == 'mp3'}
<script type="text/javascript">
$(function(){
$('#player1').plp({
'volume': 80,
'playlist':[
{"title":"{$pic.video_descr }",
"author":"Test2",
"cover":"files/covers/1.jpg",
"mfile":"{$config.siteurl}{$pic.fullfilename}",
"duration":"330"},
]
});
});
</script><br>
<div style=
"width:60%;word-wrap: break-word;padding-bottom:20px;">
</div>{else} {include file='otheruploads.tpl'}<br>
{$pic.video_descr } {/if}
</td>
</tr>
</table>
<div class="player" id="player1">
<img alt="" class="cover" src=""><!--album cover-->
<span class="title"></span><!--song title-->
<span class="author"></span><!--artist-->
<div class="long"></div>
<div class="current">
00:00
</div>
<div class="all"></div>
<div class="volume"></div>
<div class="vol_icon"></div>
<div class="rand"></div>
<div class="while_icon"></div>
<div class="toolbar">
<div class="tlb_prev"></div>
<div class="tlb_stop"></div>
<div class="tlb_next"></div>
</div>
<div class="pl_icon active"></div>
<div class="playlist flexcroll"></div>
</div>{/if}
I'm just not sure where or how. I've literally spent the last two days searching and researching to figure it out. I'm so sure its simple, but I'm lost at the moment, and would GREATLY appreciate the help.

Related

Why can't I run my code in a browser or JS Fiddle?

With full disclosure, I am brand new to JS. I don't fully comprehend the nature of the language (e.g. is it written in html, what is the difference between JS and html?). So needless to say, I am a novice. That being said, I'm trying to build an experiment in jspsych and I went through the tutorials, tried to run the sample code, and got "Invalid JavaScript Code." I cannot find any answers to why this is. It neither works in a browser or on JS Fiddle's testing software. I would appreciate any help with this.
P.S. I'm a decent programmer in Python, and the JS syntax seems pretty straight forward, but I'm out to sea when it comes to formatting, etc.
<html>
<head>
<title>My experiment</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="jspsych-5.0.3/jspsych.js"></script>
<script src="jspsych-5.0.3/plugins/jspsych-text.js"></script>
<script src="jspsych-5.0.3/plugins/jspysch-single-stim.js"></script>
<link href="jspsych-5.0.3/css/jspsych.css" rel="stylesheet" type="text/css"></link>
</head>
<body>
</body>
<script>
/* define welcome message block */
var welcome_block = {
type: "text"
text: "Welcome to the experiment. Press any key to begin."
};
/*define instructions block*/
var instructions_block = {
type:"text",
text:"<p>In this experiment,a circle will appear in the center" +
"of the screen.</p><p>If the circle is <strong>blue</strong>," +
"press the letter F on the keyboard as fast as you can.</p>" +
"<p>If the circle is <strong>orange</strong>, do not press " +
"any key.</p>"+
"<div class ='left center-conten'><img src='img/blue.png'></img>" +
"<p class = 'small'><strong>Press the F key</strong></p></div>" +
"div class='right center-content'><img src='img/orang.png'></img>" +
"<p class='small'><strong>Do not press a key</strong></p></div>" +
"<p>Press any key to begin.</p>"
timing_post_trial: 2000
};
var test_stimuli = [
{
stimulus: 'img/blue.png',
data: { response: 'go'}
},
{
stimulus: 'img/orange.png',
data: { response: 'no-go'}
}
];
var all_trials = jsPsych.randomization.repeat(test_stimuli,10);
var post_trial_gap = function() {
return Math.floor( math.random() * 1500) + 750;
}
var test_block = {
type: 'single-stim',
choices: ['F'],
timing_response: 1500,
timing_post_trial: post_trial_gap,
on_finish: function(data){
var correct = false;
if(data.response == 'go' && data.rt > -1){
correct = true;
} else if(data.response == 'no-go' && data.rt == -1){
correct = true;
}
jsPsych.data.addDataToLastTrial({correct: correct});
},
timeline: all_trials
};
/*define debrief block*/
function getSubjectData() {
var trials = jsPsych.data.getTrialsofType('single-stim');
var sum_rt = 0;
var correct_trial_count = 0;
var correct_rt_count = 0;
for (var i = 0; i < trials.length; i++) {
if (trials[i].correct == true) {
correct_trial_count++;
if(trials[i].rt > -1){
sum_rt += trials[i].rt;
correct_rt_count++;
}
}
}
return {
rt: Math.floor(sum_rt/correct_rt_count),
accuracy: Math.floor(correct_trial_count / trials.length * 100)
}
}
var debrief_block = {
type: "text",
text: function() {
var subject_data = getSubjectData();
return"<p>You responded correctly on "+subject_data.accuracy+"% of "+
"the trials.</p><p>Your average response time was <strong>"+
subject_data.rt + "ms</strong>. Press any key to complete the "+
"experiment. Thank you!</p>";
}
};
/*create experiment timeline array*/
var timeline = [];
timeline.push(welcome_block);
timeline.push(instructions_block);
timeline.push(test_block);
timeline.pysh(debrief_block)
/*start the experiment*/
jsPsych.init({
experiment_structure: experiment,
on_finish: function() {
jsPsych.data.displayData();
}
});
</script>
</html>
Did you update the code posted here on SO? It looks like you still have some missing commas as I have indicated here with "//<-- YOU NEED A COMMA HERE". See below:
var welcome_block = {
type: "text", //<-- YOU NEED A COMMA HERE
text: "Welcome to the experiment. Press any key to begin."
};
/*define instructions block*/
var instructions_block = {
type:"text",
text:"<p>In this experiment,a circle will appear in the center" +
"of the screen.</p><p>If the circle is <strong>blue</strong>," +
"press the letter F on the keyboard as fast as you can.</p>" +
"<p>If the circle is <strong>orange</strong>, do not press " +
"any key.</p>"+
"<div class ='left center-conten'><img src='img/blue.png'></img>" +
"<p class = 'small'><strong>Press the F key</strong></p></div>" +
"div class='right center-content'><img src='img/orang.png'></img>" +
"<p class='small'><strong>Do not press a key</strong></p></div>" +
"<p>Press any key to begin.</p>", //<-- YOU NEED A COMMA HERE
timing_post_trial: 2000
};
EDIT: Another typo (math.random() should be Math.random());
var post_trial_gap = function() {
return Math.floor( Math.random() * 1500) + 750;
}
Here is the updated code:
/* define welcome message block */
var welcome_block = {
type: "text",
text: "Welcome to the experiment. Press any key to begin."
};
/* define instructions block */
var instructions_block = {
type: "text",
text: "<p>In this experiment, a circle will appear in the center " +
"of the screen.</p><p>If the circle is <strong>blue</strong>, " +
"press the letter F on the keyboard as fast as you can.</p>" +
"<p>If the circle is <strong>orange</strong>, do not press " +
"any key.</p>" +
"<div class='left center-content'><img src='img/blue.png'></img>" +
"<p class='small'><strong>Press the F key</strong></p></div>" +
"<div class='right center-content'><img src='img/orange.png'></img>" +
"<p class='small'><strong>Do not press a key</strong></p></div>" +
"<p>Press any key to begin.</p>",
timing_post_trial: 2000
};
/* define test block */
var test_stimuli = [
{
stimulus: "img/blue.png",
data: { response: 'go' }
},
{
stimulus: "img/orange.png",
data: { response: 'no-go' }
}
];
var all_trials = jsPsych.randomization.repeat(test_stimuli, 10);
var post_trial_gap = function() {
return Math.floor( Math.random() * 1500 ) + 750;
}
var test_block = {
type: "single-stim",
choices: ['F'],
timing_response: 1500,
timing_post_trial: post_trial_gap,
on_finish: function(data){
var correct = false;
if(data.response == 'go' && data.rt > -1){
correct = true;
} else if(data.response == 'no-go' && data.rt == -1){
correct = true;
}
jsPsych.data.addDataToLastTrial({correct: correct});
},
timeline: all_trials
};
/* define debrief block */
function getSubjectData() {
var trials = jsPsych.data.getTrialsOfType('single-stim');
var sum_rt = 0;
var correct_trial_count = 0;
var correct_rt_count = 0;
for (var i = 0; i < trials.length; i++) {
if (trials[i].correct == true) {
correct_trial_count++;
if(trials[i].rt > -1){
sum_rt += trials[i].rt;
correct_rt_count++;
}
}
}
return {
rt: Math.floor(sum_rt / correct_rt_count),
accuracy: Math.floor(correct_trial_count / trials.length * 100)
}
}
var debrief_block = {
type: "text",
text: function() {
var subject_data = getSubjectData();
return "<p>You responded correctly on "+subject_data.accuracy+"% of "+
"the trials.</p><p>Your average response time was <strong>" +
subject_data.rt + "ms</strong>. Press any key to complete the "+
"experiment. Thank you!</p>";
}
};
/* create experiment timeline array */
var timeline = [];
timeline.push(welcome_block);
timeline.push(instructions_block);
timeline.push(test_block);
timeline.push(debrief_block);
/* start the experiment */
jsPsych.init({
timeline: timeline,
on_finish: function() {
jsPsych.data.displayData();
}
});
After fetching the library and creating a blue and orange png I ran the experiment with the following correction to your last code post. The plugin name you have is incorrect. By the way, my time was 303ms.
<script src="jspsych-5.0.3/plugins/jspsych-single-stim.js"></script>

Replace random image on website

my goal is to replace one random image from open website with some random image from my list of images. I have this code, but It changes all the images on the website, I need just one random not all of them. Can you help me please with it?
//Handles all images on page with an interval of time
handleImages: function (lstImgs, time) {
$.each($('img'), function (i, item) {
//Skip if image is already replaced
if ($.inArray($(item).attr('src'), lstImgs) == -1) {
var h = $(item).height();
var w = $(item).width();
//If image loaded
if (h > 0 && w > 0) {
self.handleImg(item, lstImgs);
}
else {
//Replace when loaded
$(item).load(function () {
//Prevent 'infinite' loop
if ($.inArray($(item).attr('src'), lstImgs) == -1) {
self.handleImg(item, lstImgs);
}
});
}
}
});
//Keep replacing
if (time > 0) {
setTimeout(function () { self.handleImages(lstImgs, time); }, time);
}
},
//Replace one image
handleImg: function (item, lstImgs) {
$(item).error(function () {
//Handle broken imgs
self.handleBrokenImg(item, lstImgs);
});
self.setRandomImg(item, lstImgs);
},
//Set a random image from lstImgs to item
setRandomImg: function (item, lstImgs) {
var h = $(item).height();
var w = $(item).width();
$(item).css('width', w + 'px').css('height', h + 'px');
$(item).attr('src', lstImgs[Math.floor(Math.random() * lstImgs.length)]);
},
//Removed broken image from lstImgs, run handleImg on item
handleBrokenImg: function (item, lstImgs) {
var brokenImg = $(item).attr('src');
var index = lstImgs.indexOf(brokenImg);
if (index > -1) {
lstImgs.splice(index, 1);
}
self.setRandomImg(item, lstImgs);
},
};
//Run on jQuery ready
$(function () {
self.handleImages(self.gitmbImgs, 3000);
});
//Set global variable
$.gitmb = self;
$.each($('img') selects all images, all you need is one.
Update
<img src="https://thereisnocavalry.files.wordpress.com/2012/08/fractals-erucolindo3.jpg" alt="some image">
<img src="http://ionamiller.weebly.com/uploads/4/7/9/5/4795680/5133447.jpg?617" alt="some image">
<img src="http://wallpoper.com/images/00/17/31/50/abstract-fractal_00173150.jpg" alt="some image">
<img src="http://www.wussu.com/fractals/images/wd950112.gif" alt="some image">
<img src="http://naperdesign.com/wp-content/uploads/2010/09/fractals_generative.jpg" alt="some image">
$().ready(function() {
var imagesToReplace = $("img");
var imagesReplaced = [];
var imagesAvailable = [
"http://www.hdwallpapersn.com/wp-content/uploads/2015/04/Fractal-Pictures-3.jpg",
"http://fc02.deviantart.net/fs27/f/2008/073/c/e/Fractals_of_the_Ball_by_Hosse7.jpg",
"https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTQKqS8FDvMUcbsUTQj8TIbHg7JSIpvcQqWax9Pq5gZX2BcoVIm",
"http://www.sgeier.net/fractals/fractals/01/Fire%20and%20Water.jpg",
"http://www.fractalsciencekit.com/fractals/large/Fractal-Mobius-Dragon-IFS-10.jpg",
"https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQV44vnqHs24LfEEmMPKXojB4whOyBMnQbXghk2kJnkeP90bSR8"
];
var replaceImage = function() {
var repl_ind, with_ind, img;
if ( !imagesAvailable.length ) {
//loop once all images have been replaced
imagesAvailable = imagesReplaced.slice();
imagesReplaced = [];
}
repl_ind = Math.floor( Math.random() * imagesToReplace.length );
with_ind = Math.floor( Math.random() * imagesAvailable.length );
img = $(imagesToReplace.get(repl_ind));
console.log("replacing",img.attr("src"),"with",imagesAvailable[with_ind]);
imagesReplaced.push( img.attr("src") );
img.attr("src", imagesAvailable[with_ind] );
imagesAvailable.splice(with_ind, 1);
//start timer once image is ready, either instantly or after load
if ( img.get(0).complete ) {
setTimeout(replaceImage, 2000 );
console.log("complete");
img.get(0).onload=false;
} else {
console.log("onload");
img.get(0).onload = function() {setTimeout(replaceImage, 1000 );};
}
}
setTimeout(replaceImage, 4000 );
});
img {
width: 6em;
padding: 0.4em;
height: 5em;
}
This is fiddle link.

On Hover function is not showing in Chrome for my Jvectormap

Can't figure out why only chrome will not function, it is working fine in IE and Firefox.
$(function () {
$('#jvectormap-mill').vectorMap({
map: 'world_mill_en',
backgroundColor: 'white',
regionStyle: {
initial: {
fill: '#002d62'
},
hover: {
fill: '#FEC057',
"fill-opacity": 1
}
},
series: {
regions: [{
scale: ['#00B5E6'],
attribute: 'fill',
values: SavillePartnerArray()
}]
},
onRegionLabelShow: function (e, label, code) {
for (var partner in SavillePartners) {
if (partner == code) {
$("#jvectormap-label").position = e.position;
return false;
}
}
},
onRegionOver: function (e, code) {
var label = $("#jvectormap-label");
var region = $(".jvectormap-region[data-code='" + code + "']");
for (var partner in SavillePartners) {
if (partner == code) {
var Title = SavillePartners[code].name;
// Create HTML
var stringHtml = '<div class="jvectormap-label2"><div id="titleTextbox"><span id="titleSpan">' + Title + '</span></div><div class="globeLogoDiv"><img src="/images/international-partner-logos/saville-globe.jpg" alt="globe"/></div><div class="savilleLogoDiv"><img src="/images/international-partner-logos/saville-logo.jpg" alt="savilleconsulting" class="savilleLogoImg"/></div>';
if (SavillePartners[code].accreditedTrainer == 1) {
stringHtml = stringHtml + '<div class="internationalPartnersContainer"><div class="internationalContainer"><strong>INTERNATIONAL</strong></div><div class="partnersContainer">PARTNER</div></div><div class="accreditedTrainerContainer" ><div class="accreditedContainer"><strong>ACCREDITED</strong></div><div class="trainerContainer">TRAINER</div></div>';
}
else {
stringHtml = stringHtml + '<div class="internationPartnersSingle"><strong>INTERNATIONAL PARTNER</strong></div>';
}
stringHtml = stringHtml + '</div>';
label.html(stringHtml);
label = region.mousemove(function (t) {
var label = $("#jvectormap-label");
label.css({
left: t.pageX + 15,
top: t.pageY + 15
});
});
// Expand the title text to fit
var spanWidth = $("#titleSpan").width();
var newFontSize = (250 / spanWidth * 12);
$("#titleSpan").css({ "font-size": newFontSize, "line-height": newFontSize / 1.2 + "px" });
return;
}
}
e.preventDefault();
},
onRegionOut: function (e, code) {
var label = $("#jvectormap-label");
label.html('');
label.display = 'none';
},
onRegionClick: function (e, code) {
for (var partner in SavillePartners) {
if (partner == code) {
var link = SavillePartners[code].link;
document.location.href = '/International/' + link;
}
}
},
focusOn: {
x: mapXFocus,
y: mapYFocus,
scale: mapScale
}
});
});
Developer tools are not showing anything to point me in the direction of why...
If you want to see for yourself how its working in FF and IE but not Chrome please click here and hover on the lighter blue Countries. Any help will be greatly appreciated as I have been stuck on this for hours.
I'm using Chrome Version 25.0.1364.172 and it is working for me. Which version are you using, is there more data? The color changes, what exactly are you trying to solve?

JQuery Function not be invoked through Javascript in IE7

It works perfect in all major browsers, but not in IE7.
The Java script code is:
$(function() {
var $hdVid = jQuery.noConflict();
$hdVid(function() {
$hdVid('.hd-flv-player').hdVideo();
});
});
JQuery is:
(function($) {
// plugin definition
$.fn.hdVideo = function(options) {
// build main options before element iteration
var defaults = {
theme: 'simpledark',
childtheme: ''
};
var options = $.extend(defaults, options);
// iterate and reformat each matched element
return this.each(function() {
var $hdVideo = $(this);
$hdVideo.removeAttr('controls');
//create html structure
//main wrapper
var $video_wrap=$('<div id="hd-player"></div>');
var $video_hd_html_player = $('<div id="hd_html_player"></div>').addClass('hd-video-player').addClass(options.theme).addClass(options.childtheme);
//controls wraper
var $video_controls = $('<div class="hd-video-main-control"></div><div class="hd-video-controls"><div class="hd-video-seek-container"><div class="hd-video-seek"></div></div><div class="hd-video-buffer-container"><div class="hd-video-buffer"></div></div><div class="hd-video-options cf"><a class="hd-video-play" title="Play/Pause"></a><div class="hd-video-timer"><span class="hd-video-timer-curr">00:00</span><span class="hd-video-sep"> / </span><span class="hd-video-timer-tot-time">00:00</span></div><div class="hd-full-screen"><a class="hd-full-screen-button" title="Normal/FullScreen"></a></div><div class="hd-volume-box"><div class="hd-volume-slider-container"><div class="hd-volume-slider"></div></div><a class="hd-volume-button" title="Mute/Unmute"></a><div class="hd-volume-value-slider"></div></div><div class="hd-hd-swipe"><a class="hd-hd-swipe-button" title="High Definition / Low Definition"></a></div><div class="hd-flv-html5-switch"><a title="Switch to Flash"></a></div></div></div>');
$video_wrap.append($video_hd_html_player);
$hdVideo.wrap($video_wrap);
$hdVideo.after($video_controls);
var full_screen = 0;
//get new elements
var $video_container = $hdVideo.parent('.hd-video-player');
var $video_main_control = $('.hd-video-main-control', $video_container);
$video_controls = $('.hd-video-controls', $video_container);
var $hd_play_btn = $('.hd-video-play', $video_container);
var $hd_video_seek = $('.hd-video-seek', $video_container);
var $hd_video_buffer = $('.hd-video-buffer', $video_container);
var $hd_video_timer_curr = $('.hd-video-timer-curr', $video_container);
var $hd_video_timer_tot_time = $('.hd-video-timer-tot-time', $video_container);
var $hd_volume = $('.hd-volume-slider', $video_container);
var $hd_volume_value = $('.hd-volume-value-slider', $video_container);
var $hd_volume_btn = $('.hd-volume-button', $video_container);
var $hd_hd_swipe_btn = $('.hd-hd-swipe-button', $video_container);
var $hd_full_screen_btn = $('.hd-full-screen-button', $video_container);
var $player_change_btn = $('.hd-flv-html5-switch', $video_container);
$video_controls.hide(); // keep the controls hidden
var firstTime=1;
/* Video Elements Fetching */
var videoAttr = {};
videoAttr.poster = $("video").attr("poster");
videoAttr.src = $("source").map(function() {
return $(this).attr("src");
});
videoAttr.quality = $("source").map(function() {
return $(this).attr("data-quality");
});
videoAttr.type = $("source").map(function() {
return $(this).attr("type");
});
videoAttr.codecs = $("source").map(function() {
return $(this).attr("codecs");
});
/* Video Elements Fetching Ends */
/* Poster image into screen image */
var $video_bind_pst = $('<img class="hd-vid-poster-img" src="'+videoAttr.poster+'" data-width="544" data-height="306"><div class="hd-video-main-control"></div>');
//$hdVideo.before($video_bind_pst);
//var
//width: 630px !important; height: 354px !important; top: 0px !important; left: 0px !important; max-width: 630px !important;
/* Poster image into screen image ends*/
/* Play/Pause */
var gPlay = function() {
txt = navigator.platform ;
if(txt =='iPhone'|| txt =='Linux armv7l')
{
window.location.href = videoAttr.src[0];
}
else{
if($hdVideo.attr('paused') == false) {
$hdVideo[0].pause();
$video_main_control.removeClass("hd-video-main-control-none");
}
else {
if(firstTime)
{
$hdVideo.attr('src', vidStatistics.default_vid_src);
firstTime=0;
}
$hdVideo[0].play();
$hdVideo.attr('preload', 'auto');
$video_main_control.addClass("hd-video-main-control-none");
$hdVideo.addClass("video1-visible");
}
}
return false;
};
var hd_autoply =$("video").attr("play_auto");
if(hd_autoply=="autoplay"){
$hdVideo[0].play();
$video_main_control.addClass("hd-video-main-control-none");
$hd_play_btn.addClass('hd-paused-button');
}
$video_main_control.click(gPlay);
$hd_play_btn.click(gPlay);
$hdVideo.click(gPlay);
$hdVideo.bind('play', function() {
$hd_play_btn.addClass('hd-paused-button');
return false;
});
$hdVideo.bind('pause', function() {
$hd_play_btn.removeClass('hd-paused-button');
return false;
});
$hdVideo.bind('ended', function() {
$hd_play_btn.removeClass('hd-paused-button');
$(".hd-video-main-control").removeClass('hd-video-main-control-none');
return false;
});
var gTimeFormat=function(seconds){
var m=Math.floor(seconds/60)<10?"0"+Math.floor(seconds/60):Math.floor(seconds/60);
var s=Math.floor(seconds-(m*60))<10?"0"+Math.floor(seconds-(m*60)):Math.floor(seconds-(m*60));
return m+":"+s;
};
/* Play/Pause */
/* Progressbar Slider */
var seeksliding;
var createSeek = function() {
if($hdVideo.attr('readyState'))
{
$hd_video_timer_tot_time.text(gTimeFormat($hdVideo.attr('duration')));
var video_duration = $hdVideo.attr('duration');
$hd_video_seek.slider({
value: 0,
step: 0.01,
orientation: "horizontal",
range: "min",
max: video_duration,
animate: true,
slide: function(){
seeksliding = true;
},
stop:function(e,ui){
seeksliding = false;
$hdVideo.attr("currentTime",ui.value);
}
});
$video_controls.show();
}
else {
setTimeout(createSeek, 150);
}
return false;
};
createSeek();
var seekUpdate = function() {
var currenttime = $hdVideo.attr('currentTime');
if(!seeksliding)
{
$hd_video_seek.slider('value', currenttime);
$hd_video_timer_curr.text(gTimeFormat(currenttime));
}
return false;
};
$hdVideo.bind('timeupdate', seekUpdate);
/* Progressbar Slider */
/* Buffer Slider */
var buffersliding;
var createBuffer = function() {
if($hdVideo.attr('readyState'))
{
$hd_video_timer_tot_time.text(gTimeFormat($hdVideo.attr('duration')));
var video_duration = $hdVideo.attr('duration');
$hd_video_buffer.slider({
value: 0,
step: 0.01,
orientation: "horizontal",
range: "min",
max: video_duration,
animate: true,
disabled: true,
slide: function(){
buffersliding = true;
},
stop:function(e,ui){
buffersliding = false;
$hdVideo.attr("buffered",ui.value).end(0);
}
});
$video_controls.show();
}
else {
setTimeout(createBuffer, 150);
}
return false;
};
createBuffer();
// var buffertime = $hdVideo.get(0).buffered.end(0);
var buffertime = $hdVideo[0].buffered.end(0);
var currenttime = $hdVideo.attr('currentTime');
if(!buffersliding)
{
if(currenttime>buffertime){
$hd_video_buffer.slider('value', currenttime);
}
else{
$hd_video_buffer.slider('value', buffertime);
}
}
return false;
};
$hdVideo.bind('timeupdate', bufferUpdate);
/* Buffer Slider end*/
/* Volume Control */
var video_volume = 1;
$hd_volume.slider({
value: 0.4,
orientation: "horizontal",
range: "min",
max: 1,
step: 0.05,
animate: true,
slide:function(e,ui){
$hdVideo.attr('muted',false);
video_volume = ui.value;
$hdVideo.attr('volume',ui.value);
$hd_volume_btn.removeClass('hd-volume-mute');
if(ui.value*100 == 0) {
$hd_volume_btn.css('background-position', '-244px -126px');
}
else if(ui.value*100 <= 15) {
$hd_volume_btn.css('background-position', '-244px -96px');
}
else if (ui.value*100 <= 45) {
$hd_volume_btn.css('background-position', '-244px -66px');
}
else if (ui.value*100 <= 85) {
$hd_volume_btn.css('background-position', '-244px -36px');
}
else {
$hd_volume_btn.css('background-position', '-244px -6px');
}
}
});
var muteVolume = function() {
if($hdVideo.attr('muted')==true) {
$hdVideo.attr('muted', false);
$hd_volume.slider('value', video_volume);
$hd_volume_btn.removeClass('hd-volume-mute');
}else{
$hdVideo.attr('muted', true);
$hd_volume.slider('value', '0');
$hd_volume_btn.addClass('hd-volume-mute');
}
return false;
};
/* Volume Control */
/* Full Screen */
var fullScreen = function(){
if(full_screen == 0){
full_screen = 1;
$(".hd-video-player").addClass("fullscreen-video-container");
$(".hd-video-player video.hd-flv-player").addClass("fullscreen-video");
$(".hd-video-main-control").addClass("fullscreen-hd-video-main-control");
$(".hd-video-controls").addClass("fullscreen-control-elements");
}
else
{
full_screen = 0;
$(".hd-video-player").removeClass("fullscreen-video-container");
$(".hd-video-player video.hd-flv-player").removeClass("fullscreen-video");
$(".hd-video-main-control").removeClass("fullscreen-hd-video-main-control");
$(".hd-video-controls").removeClass("fullscreen-control-elements");
}
return false;
};
$('body').keydown(function(e){
if (e.keyCode == 27 && full_screen == 1) {
fullScreen();
}
console.log(e);
return false;
});
/* Full Screen Ends*/
/* Default Video Quality */
var defaultVideoQuality = function(videoAttr){
var vidStatistics = {};
vidStatistics.support_vid_count=0;
var i, isSupp, myVid=document.createElement('video');
for(i=videoAttr.quality.length-1; i>=0; i--)
{
path = videoAttr.src[i];
var path = videoAttr.src[i],
ext = path.substr(path.lastIndexOf('.') + 1);
isSupp = myVid.canPlayType('video/'+ext+';');
if(isSupp=="maybe" || isSupp=="probably" )
{
vidStatistics.default_vid_qty = videoAttr.quality[i];
vidStatistics.default_vid_src = videoAttr.src[i];
vidStatistics.support_vid_count++;
}
}
if(vidStatistics.default_vid_qty == "hd")
$("a.hd-hd-swipe-button").addClass("hd-hd-swipe-button-hd");
else
$("a.hd-hd-swipe-button").removeClass("hd-hd-swipe-button-hd");
return(vidStatistics);
};
/* Default Video Quality Ends*/
/* HD Available Check */
var hdAvailableCheck = function(videoAttr){
var k=0, i, isSupp, sdSupport = 0;
var myVid=document.createElement('video');
for(i=0; i<videoAttr.quality.length; i++)
{
path = videoAttr.src[i];
var path = videoAttr.src[i],
ext = path.substr(path.lastIndexOf('.') + 1);
isSupp = myVid.canPlayType('video/'+ext+';');
if(isSupp=="maybe" || isSupp=="probably" )
{
if(videoAttr.quality[i]=="hd")
k=1;
else
sdSupport=1;
}
}
if (k==0)
$hd_hd_swipe_btn.css('display', 'none');
if (sdSupport==0)
$hd_hd_swipe_btn.css('pointer-events', 'none').css('cursor', 'default');
return false;
}
/* HD Available Check Ends*/
/* Video Quality Check*/
var videoQualityCheck = function(){
var i, $currVid, currQuality;
$currVid = $hdVideo[0].currentSrc;
for(i=0; i<videoAttr.quality.length; i++) //Get current video quality
if($currVid == videoAttr.src[i])
currQuality=videoAttr.quality[i];
if(currQuality == "hd")
$("a.hd-hd-swipe-button").addClass("hd-hd-swipe-button-hd");
else
$("a.hd-hd-swipe-button").removeClass("hd-hd-swipe-button-hd");
return false;
}
/* Video Quality Check Ends*/
/* Quality Swipe */
var playerstage = 0;
var hdswipe = function(){
var currVid, currExt, currVidName, currQuality, i;
if($hdVideo.attr('paused')==false)
playerstage=1;
currVid = $hdVideo[0].currentSrc;
var currVidTime = $hdVideo.attr('currentTime');
currExt = currVid.substr(currVid.lastIndexOf('.') + 1);
for(i=0; i<videoAttr.quality.length; i++) //Get current video quality
if(currVid == videoAttr.src[i])
currQuality=videoAttr.quality[i];
for(i=0; i<videoAttr.quality.length; i++) //Swipe the Video
{
if((currExt==videoAttr.src[i].substr(videoAttr.src[i].lastIndexOf('.') + 1))&&(currQuality!= videoAttr.quality[i]))
{
$hdVideo.attr('src', videoAttr.src[i]);
resumeCurrTime(currVidTime);
gPlay();
createSeek();
createBuffer();
playerstage=0;
break;
}
}
alert(currQuality);
if(currQuality == "sd")
$("a.hd-hd-swipe-button").addClass("hd-hd-swipe-button-hd");
else
$("a.hd-hd-swipe-button").removeClass("hd-hd-swipe-button-hd");
return false;
}
var resumeCurrTime = function(currVidTime) {
if($hdVideo.attr('readyState'))
{
$hdVideo[0].currentTime = currVidTime;
}
else
setTimeout(function() { resumeCurrTime(currVidTime); }, 150);
return false;
}
/* Quality Swipe Ends */
/* HTML5 / FLV Swipe */
var playerChangeIntFn = function(){
if(full_screen==1)
fullScreen();
$hdVideo.attr('preload', 'none');
$hdVideo.load();
var trigger = "flash";
playerChange(trigger);
return false;
};
/* HTML5 / FLV Swipe Ends */
var vidStatistics = {};
vidStatistics = defaultVideoQuality(videoAttr);
hdAvailableCheck(videoAttr);
$hd_hd_swipe_btn.click(hdswipe); //HD On/Off
$hd_volume_btn.click(muteVolume); //Mute Volume
$hd_full_screen_btn.click(fullScreen); //Full Screen On/Off
$video_container.dblclick(fullScreen); //Full Screen On/Off
$player_change_btn.click(playerChangeIntFn); //Full Screen On/Off
});
};
// plugin defaults
$.fn.hdVideo.defaults = {
};
})(jQuery);
HTML is:
<video src="" width="830" height="354" class="hd-flv-player" poster="asserts/poster.png" controls="controls" data-name="demo video" data-uid="57fb2708" preload="none">
<source src="http://video-js.zencoder.com/oceans-clip.mp4" data-quality="hd"></source>
<source src="http://static.clipcanvas.com/sample/clipcanvas_14348_offline.mp4" data-quality="sd"></source>
<source src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" data-quality="hd"></source>
<source src="asserts/300_VP8.webm" data-quality="sd"></source>
</video>
Doctype: <!DOCTYPE html>
Note: I know that IE7 wont support HTML5 Video. But I just want the control code should be binded. So that I can use Flash Fall back.
Reply to your comment
That error is because of ie7 support for "myVid.canPlayType()" in
JQuery
Then that needs to be fixed, no? Even though it looks like a third-party library, you can still fix code in them, and even submit bug fixes to the developer. Maybe they even have a later version of the library out, you could check.
if (myVid.canPlayType)
will check for the existence of the function in the object. If it doesn't exist, like you said it probably doesn't support HTML video. You should then exit the plugin with an error, or have an option in the plugin which content should be used as a fallback.
DEMO

Moving repeating pattern in a div container

I have a div container which has a repeating background image that forms a pattern, and I would like to animate it with jQuery so that the pattern moves south-west.
How can this be done?
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="content/main.css">
<script src="content/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#container").animate({
'background-position': '1110px 1110px'
}, 1000, function () {
});
});
</script>
</head>
<body>
<div id="container">
</div>
</body>
Have a look at Sprightly. It's a jQuery plugin and makes animating background images reasonably easy.
To pan (animate a background image), the documentation gives this code as an example:
$('#trees').pan({fps: 30, speed: 2, dir: 'left'});
If you're looking for a simpler, lighter approach, this plugin may be a better solution. To animate a background, give it an offset:
$('.elem').animate({backgroundPosition: '500px 150px'})
Like this:
$("#container").animate({
'background-position': '1110px 1110px'
}, 1000, function () {
});
...
/**
* #author Alexander Farkas
* v. 1.22
*/
(function ($) {
if (!document.defaultView || !document.defaultView.getComputedStyle) { // IE6-IE8
var oldCurCSS = $.curCSS;
$.curCSS = function (elem, name, force) {
if (name === 'background-position') {
name = 'backgroundPosition';
}
if (name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[name]) {
return oldCurCSS.apply(this, arguments);
}
var style = elem.style;
if (!force && style && style[name]) {
return style[name];
}
return oldCurCSS(elem, 'backgroundPositionX', force) + ' ' + oldCurCSS(elem, 'backgroundPositionY', force);
};
}
var oldAnim = $.fn.animate;
$.fn.animate = function (prop) {
if ('background-position' in prop) {
prop.backgroundPosition = prop['background-position'];
delete prop['background-position'];
}
if ('backgroundPosition' in prop) {
prop.backgroundPosition = '(' + prop.backgroundPosition;
}
return oldAnim.apply(this, arguments);
};
function toArray(strg) {
strg = strg.replace(/left|top/g, '0px');
strg = strg.replace(/right|bottom/g, '100%');
strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g, "$1px$2");
var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
return [parseFloat(res[1], 10), res[2], parseFloat(res[3], 10), res[4]];
}
$.fx.step.backgroundPosition = function (fx) {
if (!fx.bgPosReady) {
var start = $.curCSS(fx.elem, 'backgroundPosition');
if (!start) {//FF2 no inline-style fallback
start = '0px 0px';
}
start = toArray(start);
fx.start = [start[0], start[2]];
var end = toArray(fx.end);
fx.end = [end[0], end[2]];
fx.unit = [end[1], end[3]];
fx.bgPosReady = true;
}
//return;
var nowPosX = [];
nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
fx.elem.style.backgroundPosition = nowPosX[0] + ' ' + nowPosX[1];
};
})(jQuery);

Categories

Resources