Replace random image on website - javascript

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.

Related

displaying images with different intervals

I am trying to display an array of images that will replace each other but will have 0.5 sec of black screen between them.
For example array_img = ["im1","im2","im3"]
show im1 for 3 seconds, show a black screen for 0.5 sec, show im2 for 3 sec, black screen for 0.5 sec...
my code is
images_array is a global variable.
time_between_images = 3000 and is a global var
time_for_black_screen = 500 and is a global var
function displayImages(){
for (i = 0; i < images_array.length; i++) {
console.log(images_array[i]);
setTimeout(function () {
console.log("1");
$('#exprBody').css('background-color', 'white');
$('#picture_frame').append(images_array[i]);
}, time_between_images)
setTimeout(function () {
console.log("2");
$("#picture_frame img:last-child").remove()
$('#exprBody').css('background-color', 'black');
}, time_for_black_screen)
}
console.log(images_array);
}
My html is simple
<body>
<div id="experiment_frame">
<div id="header">
<div id="left_cat"></div><div id="right_cat"></div>
</div>
<div id="picture_frame" class="centered">
<div id="exp_instruct"></div>
</div>
</div>
</body>
I thought I should use setTimeout because I want to switch between the two tasks for each image in the array. IMG + black screen, IMG + black screen
but nothing is showing on my page.
The array
["<img src='/images/cute/1223.jpg'>", "<img src='/images/cute/1235.jpg'>", "<img src='/images/disgusted/8878.jpg'>", "<img src='/images/disgusted/8898.jpg'>", "<img src='/images/neutral/3321.png'>", "<img src='/images/neutral/3445.png'>"]
EDIT:
function displayImageIter(number) {
$("body").toggleClass("whiteBody");
$("#picture_frame").empty().append(images_array[number]);
setTimeout(function () {
$("#picture_frame").empty();
$("body").toggleClass("blackBody");
setTimeout(function () {
displayImageIter((number + 1) % images_array.length);
}, time_for_black_screen)
}, time_between_images)
}
For some reason what I have with this code is
IMG white background
blank screen white for 0.5 sec
IMG black background
blank screen white for 0.5 sec
Take a look at the following simplified code:
function displayImage(number) {
$("#picture_frame").empty().append(images_array[number]).css('background-color', 'white');
setTimeout(function () {
$("#picture_frame").empty().css('background-color', 'black');
setTimeout(function () {
displayImage((number + 1) % images_array.length);
}, time_for_black_screen)
}, time_between_images)
}
const images_array = ["FIRST IMAGE", "SECOND IMAGE", "THIRD IMAGE"];
const time_between_images = 3000;
const time_for_black_screen = 500;
displayImage(0);
#picture_frame {width: 200px; height: 100px; background-color: white}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="picture_frame"></div>
Answering your comment:
a) To change the parent div background just use:
$("#picture_frame").empty().append(images_array[number]);
$("#parent_div").css('background-color', 'white');
b) To stop this loop you could use some flag and set it to false after 15 minutes:
function displayImage(number) {
$("#picture_frame").empty().append(images_array[number]).css('background-color', 'white');
setTimeout(function () {
$("#picture_frame").empty().css('background-color', 'black');
setTimeout(function () {
//continue only if flag is true
if (flag) displayImage((number + 1) % images_array.length);
}, time_for_black_screen)
}, time_between_images)
}
const images_array = ["FIRST IMAGE", "SECOND IMAGE", "THIRD IMAGE"];
const time_between_images = 3000;
const time_for_black_screen = 500;
let flag = true;
displayImage(0);
//used 15 seconds here for simplicity
setTimeout(() => flag = false, 15000);
<a class="img0"></a>
<a class="img1"></a>
<a class="img2"></a>
<script>
var elArr = [];
// here get the els that you wanna to display img
elArr.push(document.querySelector('.img0'));
elArr.push(document.querySelector('.img1'));
elArr.push(document.querySelector('.img2'));
// here is the img src and it's interval
var imgArr = [
{ src: 'a', interval: 3000 },
{ src: 'b', interval: 2000 },
{ src: 'c', interval: 1000 },
];
// if you wanna auto display unknown number imgs, set a variable to count the whole interval
var sumInterval = 0;
for (var i = 0; i < imgArr.length; i++) {
// the first interval is 3000, second is 5000, third is 6000
sumInterval += imgArr[i].interval;
setTimeout(function () {
elArr[i].innerHTML = imgArr[i].src;
// if is the last img, set an interval and then do the callback
if (i == imgArr.length - 1) {
setTimeout(function () {
alert('now screen shall be black');
}, 500)
}
}, sumInterval);
}
</script>

How to display moving text field during other jQuery animation?

I am attempting to replicate the loading page at http://www.alessioatzeni.com/ but the percentage loaded text on my page will not display until the loading line animation completes. You can see my project page at https://jaredblumer.github.io/atzeniStudy/
If you inspect the HTML using Chrome Developer Tools, you'll see that the #loader-percentage span text is dynamically updating, but for a reason unbeknownst to me the text is not displaying until after the line animation ends.
The code I am currently using for this is as follows:
HTML
<div id="loader" class="loader">
<span id="loader-line" class="loader-line">
<span id="loader-percentage" class="loader-percentage"></span>
</span>
</div>
Javascript (loader.js)
$(document).ready(function() {
//Loading Page
var pageLoader = function() {
var $elements = $('body').find('img[src]');
$('body [style]').each(function(){
var src = $(this).css('background-image').replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
if(src) {
$elements = $elements.add($('<img src="' + src + '"/>'));
}
});
var $loading = $('#loader');
var $loadPercentageLine = $('#loader-line');
var $loadPercentageText = $('#loader-percentage');
var elementsLoaded = 0;
var speed = 5000;
var animatePercentage = function(e) {
console.log(e);
$loadPercentageText.text(parseInt(e));
};
var loading = function() {
var percentage = 0;
if ($elements.length) {
percentage = parseInt((elementsLoaded / $elements.length) * 100);
}
$loadPercentageLine.stop().animate({
height:percentage + '%'
}, speed);
$loadPercentageText.stop().animate({
percentage:percentage
}, {
duration: speed,
step: animatePercentage
});
};
if($elements.length) {
loading();
$elements.each(function() {
elementsLoaded++;
loading();
});
}
};
pageLoader();
});
here is solution:
.loader-line{
overflow: visible !important;
}

Trying to change an image using an array in JavaScript

<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="Red.jpg" width="209" height="241">
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
<script>
index=(0)
var traffic = ["Red","Rambo","Green","Yellow"]
function changeImage() {
var image = document.getElementById('Light');
if traffic[index] === "Red" {
image.src = "Rambo.jpg";
index= (index+1)
} else if traffic[index] === "Rambo" {
image.src = "Green.jpg";
index= (index+1)
} else if traffic[index] === "Green" {
image.src = "Yellow.jpg";
index= (index+1)
} else {
image.src = "Red.jpg";
index=0
}
}
</script>
</html>
</body>
this is my code I don't understand why when i click the button the image doesn't change the images are all .jpg files are all contained inside the same folders and all are the same size any ideas why is will not change the image i'm currently guessing it's something to do with the === or the fact i'm using words instead of numbers for them
Lots of things going wrong here:
Parenthese around the if statements
Closing body tag after closing html tag
document.getElementById does not get the same id as the img id
So, this will work, but perhaps checking the javascript and HTML syntax first might be a good start:
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="Red.jpg" width="209" height="241">
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
<script>
var index = 0;
var traffic = ["Red","Rambo","Green","Yellow"];
var image = document.getElementById('myImage');
function changeImage() {
if (traffic[index] === "Red") {
image.src = "Rambo.jpg";
index++;
} else if (traffic[index] === "Rambo") {
image.src = "Green.jpg";
index++;
} else if (traffic[index] === "Green") {
image.src = "Yellow.jpg";
index++;
} else {
image.src = "Red.jpg";
index = 0;
}
}
</script>
</body>
</html>
There are few little mistakes in your code.
The id of your image is myImage, but you wrote var image = document.getElementById('Light'); which result on undefined.
As mentioned by PierreDuc, you missed parenthesis around if conditions.
Take a look at this example : https://jsfiddle.net/1wjn943x/
var images = [
"http://openphoto.net/thumbs2/volumes/mylenebressan/20120720/openphotonet_11.jpg",
"http://openphoto.net/thumbs2/volumes/sarabbit/20120322/openphotonet_DSCF5890.JPG",
"http://openphoto.net/thumbs2/volumes/Sarabbit/20120117/openphotonet_gerberadaisy3.jpg"
];
var index = 0;
var img = document.getElementById("myImage");
document.getElementById("button").addEventListener('click', function() {
// Next image.
index = (index + 1) % images.length;
// Setting `src`attribute of <img>.
img.src = images[index];
});
This is the easiest way to change the image.
Simply set the image source to be the next image in the array. You need to use the mod operator to loop from the end; back to the beginning.
Array - Index Pointer
var imageEl = document.getElementById('Light');
var index = 0;
var images = [
"http://placehold.it/150x150/FF0000/FFFFFF.jpg?text=Red",
"http://placehold.it/150x150/0000FF/FFFFFF.jpg?text=Rambo",
"http://placehold.it/150x150/00FF00/FFFFFF.jpg?text=Green",
"http://placehold.it/150x150/FFFF00/FFFFFF.jpg?text=Yellow"
];
function changeImage() {
imageEl.src = images[index++ % images.length]; // Set and increment the image index.
}
changeImage();
<img id="Light" width="150" height="150">
<br />
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
Map - Linked Pointer
var imageEl = document.getElementById('Light');
var currImage = '';
var images = {
red : {
src : "http://placehold.it/150x150/FF0000/FFFFFF.jpg?text=Red",
next : 'rambo'
},
rambo : {
src : "http://placehold.it/150x150/0000FF/FFFFFF.jpg?text=Rambo",
next : 'green'
},
green : {
src : "http://placehold.it/150x150/00FF00/FFFFFF.jpg?text=Green",
next : 'yellow'
},
yellow : {
src : "http://placehold.it/150x150/FFFF00/FFFFFF.jpg?text=Yellow",
next : 'red'
}
};
function changeImage() {
(function(img) {
imageEl.src = img.src; // Set the image source to the current image.
currImage = img.next; // Set current image as the next image.
}(images[currImage || 'red']));
}
changeImage();
<img id="Light" width="150" height="150">
<br />
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
Class - Circular Iterator
var CircularIterator = function(iterable) {
this.iterable = iterable || [];
this.index = 0;
this.get = function(index) {
return this.iterable[index] || this.next();
};
this.size = function() {
return this.iterable.length;
};
this.incr = function() {
return this.index = ((this.index + 1) % this.size());
};
this.next = function() {
return this.get(this.incr());
};
this.first = function() {
return this.get(0);
};
this.last = function() {
return this.get(this.size() - 1);
};
};
var imageEl = document.getElementById('Light');
var iterable = new CircularIterator([
"http://placehold.it/150x150/FF0000/FFFFFF.jpg?text=Red",
"http://placehold.it/150x150/0000FF/FFFFFF.jpg?text=Rambo",
"http://placehold.it/150x150/00FF00/FFFFFF.jpg?text=Green",
"http://placehold.it/150x150/FFFF00/FFFFFF.jpg?text=Yellow"
]);
function changeImage() {
imageEl.src = iterable.next(); // Set and increment the image index.
}
imageEl.src = iterable.first(); // Set the current image to the first.
<img id="Light" width="150" height="150">
<br />
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>

Cache dynamic images from array before page loads using javascript

I am trying to make 4 sliding galleries but I need to preload (cache) all images behind a splash screen before displaying the images in gallery form. I have been trying to use "jPreLoader v2 - http://www.inwebson.com/jquery/jpreloader-a-preloading-screen-to-preload-images" but with no luck.
The code below is how I have been trying to preload all images from each gallery directory on to a single gallery behind jpreloader then once load complete remove the whole gallery and display each gallery at a time.
var pictures = [
"1.jpg",
"2.jpg",
"3.jpg",
"4.jpg",
.......,
"30.jpg"
]
$(window).load(function(){
preLoad();
function preLoad(){
var max = 30;
var pic;
picture = '<table id="table" style="dipslay:table;"><tr>';
for (var i=0;i < max; i++){
if(i < 30){
pic = "images/art/"+pictures[i];
appendCell(pic);
}
if(i < 17){
pic = "images/street/"+pictures[i];
appendCell(pic);
}
if(i < 19){
pic = "images/doc/"+pictures[i];
appendCell(pic);
}
if(i < 16){
pic = "images/commercial/"+pictures[i];
appendCell(pic);
}
};
picture += '</tr></table>';
$('#imageScroller').append(picture);
}
function appendCell(pic){
picture +="<td class='image'><img class='i' src='"+pic+"'></td>";
return;
}
});
Im not quite sure how to implement the jpreloader on a dynamic image loading loop above instead of already inserted into the dom.
$(document).ready(function () {
$('body').jpreLoader();
});
Thanks.
Custom progress bar that updates as images are downloaded
var pictures = [
"1.jgp",
"2.jpg"
];
var loadedSoFar = 0;
function loaded( ) {
// do stuff
}
function updateProgress( ) {
loadedSoFar++;
var newWidth = $("#progress").width() * ( loadedSoFar / pictures.length );
$("#bar").stop( true, true );
$("#bar").animate({ width: newWidth }, 500, function( ) {
if( loadedSoFar === pictures.length ) { loaded() }
});
}
for( var i = 0; i < pictures.length; i++ ) {
var img = new Image();
img.src = pictures[ i ] + i;
img.onload = function( ) {
updateProgress();
}
}
Demo here

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

Categories

Resources