I am able to create a full background video using jquery on a new page, but I am having issues filling an existing container on a page with the video. I am looking to be able to use this code to add the video to a couple of different containers on a single page. Such as a section and the hero unit. Although for now I am just trying to figure out how to add it to the hero unit and I can go from there. I tried replacing all videobg class and videobg_wrapper classes with the hero class, although it still isn't working.
Can anyone assist me? Any help would be appreciated. Here is a jfiddle with the jquery and css class.
Jfiddle with code: http://jsfiddle.net/NN276/12/
Fullscreen Jfiddle: http://jsfiddle.net/NN276/12/embedded/result/
Here is an attempt to change videobg to the hero class:
(function( $ ){
$.fn.videoBG = function( selector, options ) {
var options = {};
if (typeof selector == "object") {
options = $.extend({}, $.fn.videoBG.defaults, selector);
}
else if (!selector) {
options = $.fn.videoBG.defaults;
}
else {
return $(selector).videoBG(options);
}
var container = $(this);
// check if elements available otherwise it will cause issues
if (!container.length)
return;
// container to be at least relative
if (container.css('position') == 'static' || !container.css('position'))
container.css('position','relative');
// we need a width
if (options.width == 0)
options.width = container.width();
// we need a height
if (options.height == 0)
options.height = container.height();
// get the wrapper
var wrap = $.fn.videoBG.wrapper();
wrap.height(options.height)
.width(options.width);
// if is a text replacement
if (options.textReplacement) {
// force sizes
options.scale = true;
// set sizes and forcing text out
container.width(options.width)
.height(options.height)
.css('text-indent','-9999px');
}
else {
// set the wrapper above the video
wrap.css('z-index',options.zIndex+1);
}
// move the contents into the wrapper
wrap.html(container.clone(true));
// get the video
var video = $.fn.videoBG.video(options);
// if we are forcing width / height
if (options.scale) {
// overlay wrapper
wrap.height(options.height)
.width(options.width);
// video
video.height(options.height)
.width(options.width);
}
// add it all to the container
container.html(wrap);
container.append(video);
return video.find("video")[0];
}
// set to fullscreen
$.fn.videoBG.setFullscreen = function($el) {
var windowWidth = $(window).width(),
windowHeight = $(window).height();
$el.css('min-height',0).css('min-width',0);
$el.parent().width(windowWidth).height(windowHeight);
// if by width
if (windowWidth / windowHeight > $el.aspectRatio) {
$el.width(windowWidth).height('auto');
// shift the element up
var height = $el.height();
var shift = (height - windowHeight) / 2;
if (shift < 0) shift = 0;
$el.css("top",-shift);
} else {
$el.width('auto').height(windowHeight);
// shift the element left
var width = $el.width();
var shift = (width - windowWidth) / 2;
if (shift < 0) shift = 0;
$el.css("left",-shift);
// this is a hack mainly due to the iphone
if (shift === 0) {
var t = setTimeout(function() {
$.fn.videoBG.setFullscreen($el);
},500);
}
}
$('body > .hero').width(windowWidth).height(windowHeight);
}
// get the formatted video element
$.fn.videoBG.video = function(options) {
$('html, body').scrollTop(-1);
// video container
var $div = $('<div/>');
$div.addClass(hero')
.css('position',options.position)
.css('z-index',options.zIndex)
.css('top',0)
.css('left',0)
.css('height',options.height)
.css('width',options.width)
.css('opacity',options.opacity)
.css('overflow','hidden');
// video element
var $video = $('<video/>');
$video.css('position','absolute')
.css('z-index',options.zIndex)
.attr('poster',options.poster)
.css('top',0)
.css('left',0)
.css('min-width','100%')
.css('min-height','100%');
if (options.autoplay) {
$video.attr('autoplay',options.autoplay);
}
// if fullscreen
if (options.fullscreen) {
$video.bind('canplay',function() {
// set the aspect ratio
$video.aspectRatio = $video.width() / $video.height();
$.fn.videoBG.setFullscreen($video);
})
// listen out for screenresize
var resizeTimeout;
$(window).resize(function() {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(function() {
$.fn.videoBG.setFullscreen($video);
},100);
});
$.fn.videoBG.setFullscreen($video);
}
// video standard element
var v = $video[0];
// if meant to loop
if (options.loop) {
loops_left = options.loop;
// cant use the loop attribute as firefox doesnt support it
$video.bind('ended', function(){
// if we have some loops to throw
if (loops_left)
// replay that bad boy
v.play();
// if not forever
if (loops_left !== true)
// one less loop
loops_left--;
});
}
// when can play, play
$video.bind('canplay', function(){
if (options.autoplay)
// replay that bad boy
v.play();
});
// if supports video
if ($.fn.videoBG.supportsVideo()) {
// supports webm
if ($.fn.videoBG.supportType('webm')){
// play webm
$video.attr('src',options.webm);
}
// supports mp4
else if ($.fn.videoBG.supportType('mp4')) {
// play mp4
$video.attr('src',options.mp4);
// $video.html('<source src="'.options.mp4.'" />');
}
// throw ogv at it then
else {
// play ogv
$video.attr('src',options.ogv);
}
}
// image for those that dont support the video
var $img = $('<img/>');
$img.attr('src',options.poster)
.css('position','absolute')
.css('z-index',options.zIndex)
.css('top',0)
.css('left',0)
.css('min-width','100%')
.css('min-height','100%');
// add the image to the video
// if suuports video
if ($.fn.videoBG.supportsVideo()) {
// add the video to the wrapper
$div.html($video);
}
// nope - whoa old skool
else {
// add the image instead
$div.html($img);
}
// if text replacement
if (options.textReplacement) {
// force the heights and widths
$div.css('min-height',1).css('min-width',1);
$video.css('min-height',1).css('min-width',1);
$img.css('min-height',1).css('min-width',1);
$div.height(options.height).width(options.width);
$video.height(options.height).width(options.width);
$img.height(options.height).width(options.width);
}
if ($.fn.videoBG.supportsVideo()) {
v.play();
}
return $div;
}
// check if suuports video
$.fn.videoBG.supportsVideo = function() {
return (document.createElement('video').canPlayType);
}
// check which type is supported
$.fn.videoBG.supportType = function(str) {
// if not at all supported
if (!$.fn.videoBG.supportsVideo())
return false;
// create video
var v = document.createElement('video');
// check which?
switch (str) {
case 'webm' :
return (v.canPlayType('video/webm; codecs="vp8, vorbis"'));
break;
case 'mp4' :
return (v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"'));
break;
case 'ogv' :
return (v.canPlayType('video/ogg; codecs="theora, vorbis"'));
break;
}
// nope
return false;
}
// get the overlay wrapper
$.fn.videoBG.wrapper = function() {
var $wrap = $('<div/>');
$wrap.addClass('videoBG_wrapper')
.css('position','absolute')
.css('top',0)
.css('left',0);
return $wrap;
}
// these are the defaults
$.fn.videoBG.defaults = {
mp4:'',
ogv:'',
webm:'',
poster:'',
autoplay:true,
loop:true,
scale:false,
position:"absolute",
opacity:1,
textReplacement:false,
zIndex:0,
width:0,
height:0,
fullscreen:false,
imgFallback:true
}
})( jQuery );
$(document).ready(function() {
$('body').videoBG({
position:"fixed",
zIndex:0,
mp4:'http://www.pete.dj/video/video.mp4',
ogv:'http://www.pete.dj/video/video.ogv',
webm:'http://www.pete.dj/video/video.webm',
opacity:1,
fullscreen:true,
});
})
Not the complete solution as they all don't play immediately, but somewhere to start.
$('.hero').each(function() {
$(this).videoBG({
position:"relative",
zIndex:0,
mp4:'http://www.pete.dj/video/video.mp4',
ogv:'http://www.pete.dj/video/video.ogv',
webm:'http://www.pete.dj/video/video.webm',
opacity:1,
fullscreen:false,
});
});
Working JSFiddle: http://jsfiddle.net/NN276/15/
Also, the creator provides the following warning on his plugin site.
Don't abuse this code... Don't use it too often, too many video
instances will slow down the browser.
Please bear in mind bandwidth usage for both you, and your visitors
Related
I was coding a simple audio player with plain javascript. when i test it in my laptop work fine but when i access it from phone isnt work.
my source code:
window.addEventListener("resize", resizeAud, false);
window.addEventListener("DOMContentLoaded", function() {
audEl = document.querySelector("#audioElement"); // Audio Element
if (audEl) {
audEl.removeAttribute("controls");
audEl.load();
// Resize audio player on load window //
resizeAud();
document.querySelector("#tc3").addEventListener("click", function() {
setTimeout(resizeAud, 10);
});
/*############################################################################################*\
|*# #*|
|*# # ADDeVENTLISTENER # #*|
|*# #*|
|*############################################################################################*/
// Toggle sound details //
document.querySelector(".show-snd-d").addEventListener("click", function(e) {
e.stopPropagation();
document.querySelector(".snd-detail").classList.toggle("active-snd-detail");
});
// Hide sound detail on click outside //
document.querySelector("html").addEventListener("click", function() {
document.querySelector(".snd-detail").classList.remove("active-snd-detail");
});
// Rest show sound detail on click inside //
document.querySelector(".snd-detail").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
});
// Toggle sound playlist for mobile screen < 768px //
document.querySelector(".show-list").addEventListener("click", function() {
document.querySelector("#snd-list").classList.toggle("active-snd-list");
});
// is mouse down or up on ".git" element//
var isDown = false; // default mouse is up
document.addEventListener("mousedown", function(e) {
if (e.target.classList.contains("progressbar") || e.target.classList.contains("heared")) {isDown="progressbar"}
else if (e.target.classList.contains("snd-volume")
|| e.target.classList.contains("volume-pro")
|| e.target.classList.contains("pro")) {isDown="volPro"}
else {isDown=false}
});
document.addEventListener("mouseup", function() {
isDown = false; // is mouseup
});
// Change progressbar width on click //
document.querySelector(".proAna").addEventListener("click", (e) => { reportPro(e); });
// Change progressbar width on mousedown and move at the same time //
document.addEventListener("mousemove", (e) => { (isDown=="progressbar")?reportPro(e):false; });
// Change progrssbar on timeupdate
audEl.addEventListener("timeupdate", function() {
setInterval(function() {
reportPro("timeupdate");
},10);
})
// init play to 0 on audio ended
audEl.addEventListener("ended", () => {togglePlay("manual");});
// Change volumebar height on click //
document.querySelector(".volume-pro").addEventListener("click", (e) => { reportVol(e); });
// Change volumebar height on mousedown and move at the same time //
document.addEventListener("mousemove", (e) => { (isDown=="volPro")?reportVol(e):false; });
// Toggle mute on click on mute button
document.querySelector(".mute").addEventListener("click", () => { reportVol("mute"); })
// backward audio //
document.querySelector(".backward").addEventListener("click", () => { wardAud("backward"); });
// Toggle play audio //
document.querySelector(".play-snd").addEventListener("click", togglePlay);
// forward audio //
document.querySelector(".forward").addEventListener("click", () => { wardAud("forward"); });
}
}, false);
/*############################################################################################*\
|*# #*|
|*# # FUNCTIONS # #*|
|*# #*|
|*############################################################################################*/
var audEl = document.querySelector("#audioElement");
// Report progressbar width one click,timeupdate or mouse (down + move) //
if (audEl) {
function reportPro(event) {
var newWid;
var duration = !isNaN(audEl.duration)?audEl.duration:0;
var prWidth = document.querySelector(".progressbar").offsetWidth;
if (event!="timeupdate") {
event.preventDefault();
var bounds = document.querySelector(".progressbar").getBoundingClientRect();
var x = event.clientX - bounds.left;
if (x>prWidth) {newWid=prWidth}
else if(x<=0){newWid=0}
else {newWid=(x)}
audEl.currentTime = (newWid/prWidth)*duration;
}
var current = audEl.currentTime;
newWid = (current/duration)*100;
document.querySelector(".heared").style.width = newWid+"%";
document.querySelector(".sure").innerHTML = secondsToHms(current)+" / "+secondsToHms(duration);
}
//Convert seconds to h-m-s
function secondsToHms(d) {
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
return ((h>0)?h+":":"")
+((h>0)?((m<10)?"0"+m:m):((m>0)?m:"0"))+":"
+((s<10)?"0"+s:s);
}
// Change volumebar height function //
function reportVol(event) {
var volHeight = document.querySelector(".volume-pro").offsetHeight;
if (event=="mute") {
if (audEl.muted) {
audEl.muted = false;
bottom = audEl.volume*100;
}else{
audEl.muted = true;
bottom = 0;
}
var muteIcon = document.querySelector(".mute").childNodes[0];
muteIcon.classList.contains("fa-volume-up")? muteIcon.rempClass("fa-volume-up","fa-volume-mute")
: muteIcon.rempClass("fa-volume-mute","fa-volume-up");
}else{
event.preventDefault();
var bounds = document.querySelector(".volume-pro").getBoundingClientRect();
var y = bounds.bottom - event.clientY;
if ((y)>volHeight) {bottom=volHeight}
else if((y)<=0){bottom=0}
else {bottom=(y)}
bottom = (bottom/volHeight)*100;
audEl.volume = bottom/100;
}
document.querySelector(".pro").style.height = bottom+"%";
}
// Toggle Play Function //
function togglePlay(type="") {
var playBut = document.querySelector(".play-snd");
var playIcon = playBut.childNodes[0]; // icon element
if (type=="manual") {
audEl.currentTime = 0;
audEl.pause();
}else if(type=="ward"){
audEl.play();
}else{
(audEl.paused)?audEl.play():audEl.pause(); // Toggle play audio
}
// toggle play pause icon
(!audEl.paused)? playIcon.rempClass("fa-play","fa-pause")+playBut.classList.add("active-play-snd")
: playIcon.rempClass("fa-pause","fa-play")+playBut.classList.remove("active-play-snd");
}
// backward and award function //
function wardAud(wardType,elId="") {
var sndList = document.getElementsByClassName("snd-item");
var newActive;
for (var i=0; i < sndList.length; i++) {
if (sndList[i].classList.contains("active-snd")) { var activeItem = i; }
}
if (wardType=="backward") {
newActive = (activeItem!=0)? sndList[activeItem-1]:false;
}else if (wardType=="forward"){
newActive = (activeItem!=(sndList.length-1))? sndList[activeItem+1]:false;
}else if (wardType=="specific") {
newActive = sndList[elId];
console.log(elId);
}
if(newActive!=false && newActive!=sndList[activeItem]){
var newSrc= newActive.getAttribute("data-ref");
togglePlay();
document.getElementById("audSrc").setAttribute("src", newSrc);
audEl.load();
togglePlay("ward");
newActive.classList.add("active-snd");
sndList[activeItem].classList.remove("active-snd");
newActive.parentNode.scrollTop = newActive.offsetHeight*(((wardType=="backward")?activeItem-1
:(wardType=="forward"?activeItem+1:elId))-2);
newActive.children[0].children[0].rempClass("fa-play","fa-pause");
sndList[activeItem].children[0].children[0].rempClass("fa-pause","fa-play");
newActive.children[1].children[1].children[0].rempClass("fa-folder","fa-folder-open");
sndList[activeItem].children[1].children[1].children[0].rempClass("fa-folder-open","fa-folder");
}
}
// Resize player element function //
function resizeAud() {
var playerElment = document.getElementById("player").getBoundingClientRect().width;
var audElment = document.getElementById("audio").getBoundingClientRect().width;
if (document.body.getBoundingClientRect().width<=767){
document.getElementById("snd-list").style.width = "100%";
document.querySelector(".show-list").style.display = 'block';
document.getElementById("snd-list").classList.add("mobile-snd-list");
}else{
document.getElementById("snd-list").style.width = (playerElment - audElment)+"px";
document.querySelector(".show-list").style.display = 'none';
document.getElementById("snd-list").classList.remove("mobile-snd-list");
}
}
// remplace class by another class //
Element.prototype.rempClass = function(first,second) {
this.classList.remove(first);
this.classList.add(second);
};
}
as you see i have player interface and playlist menu
in pc audioplayer work fine and can get audio duration & other audio details.
but when i access from phone even audio details cant get.
Thank you all
Demo
I cant seem to get this to work, all I am trying to do is make it so that this div's width increases as the audio player is playing so it acts as a progress bar. Everytime I run the script I get this in the console:
TypeError: player.bind is not a function
Here is my Javascript:
var player = document.getElementById('audio_player');
var progress = document.getElementsByClassName('progress-bar');
$(".play_btn").click(function() {
if(player.paused) {
player.play();
} else {
player.pause();
}
$(this).toggleClass('pause');
});
$(function() {
var check,
reached25 = false,
reached50 = false,
reached75 = false;
player.bind("play", function(event) {
var duration = player.get(0).duration;
check = setInterval(function() {
var current = player.get(0).currentTime,
perc = (current / duration * 100).toFixed(2);
if (Math.floor(perc) >= 25 &&! reached25) {
console.log("25% reached");
reached25 = true;
}
console.log(perc);
}, 500);
});
player.bind("ended pause", function(event) {
clearInterval(check);
});
});
You should use jQuery wrapper when call jquery methods on elements:
$(player).bind...
I have a directive in a table element that allows horizontal scroll. I have a fixed header which left position I update by binding the scroll event to the element that holds the directive(the table):
The link function of the directive updates the header position on the screen and brings a div over the table to block pointer-events.
It is obvious that this function forces some style recalc so my question is:
In the angular.js world what would be the best aproach. Should I use $animate, should I be setting the timeout the way I do it, would I avoid extended frames by requesting an animation frame(how is that done for this example?). Which way is best for performance?
Here is my current directive:
app.directive('checkScroll', function() {
return {
// require: '^?listeditorController',
link: function(scope, elem, attrs) {
var timer = null;
var screenBlock= document.getElementsByClassName('blockEventsScreen')[0];
// var lastLeft = 0;
// requestAnimationFrame( scope.onScroll );
elem.bind('scroll', function() {
if(timer !== null) {
//clear previous timer that turned off the during scroll tweaks
clearTimeout(timer);
clearInterval(scope.interval);
scope.interval = undefined;
//This sets the left style attribute of the table header container to the same value as the table body
var el=document.getElementsByClassName('fixedHeader')[0];
var newLeft = elem[0].getElementsByClassName('superResponsive')[0].getBoundingClientRect().left;
screenBlock.style['transform'] = 'translateX(0px)';
screenBlock.style['msTransform'] = 'translateX(0px)';
screenBlock.style['MozTransform'] = 'translateX(0px)';
screenBlock.style['WebkitTransform'] = 'translateX(0px)';
screenBlock.style['OTransform'] = 'translateX(0px)';
// var diff= Math.abs(newLeft - lastLeft );
// if(diff>0){
el.style['transform'] = 'translateX('+newLeft+'px)';
el.style['msTransform'] = 'translateX('+newLeft+'px)';
el.style['MozTransform'] = 'translateX('+newLeft+'px)';
el.style['WebkitTransform'] = 'translateX('+newLeft+'px)';
el.style['OTransform'] = 'translateX('+newLeft+'px)';
// lastLeft=newLeft;
// scope.$apply(function(){
// $scope.headerLeft=newLeft+'px';
// });
// requestAnimationFrame( scope.onScroll );
// }
}
timer = setTimeout(function() {
//remove screen of table to enable pointer-events
screenBlock.style['transform'] = 'translateX(-10000px)';
screenBlock.style['msTransform'] = 'translateX(-10000px)';
screenBlock.style['MozTransform'] = 'translateX(-10000px)';
screenBlock.style['WebkitTransform'] = 'translateX(-10000px)';
screenBlock.style['OTransform'] = 'translateX(-10000px)';
//restart scaleheader after scrolling
scope.interval = setInterval( function(){scope.scaleHeader();}, 200);
}, 200);
});
}
}
});
I'm using the jQuery plugin Images-rotation in order to create a slideshow that plays when hovering over an image. I'd like to add transitions between the images, such as jQuery's fadeIn. The images are preloaded, which is why I think what I've attempted so far hasn't been successful.
I've also created this (http://jsfiddle.net/Lydmn2xn/) to hopefully easily show what's being used, although all of the code is found in the Javascript plugin itself. So far I've tried adding variations of the line $this.fadeIn("slow"); in various spots with no luck. Below is the code for the Javascript plugin with changes I've tried to make. Not sure how to point them out as I can't bold the text in the code. (Note: said changes are not in the Jfiddle, as they don't produce any changes).
$.fn.imagesRotation = function (options) {
var defaults = {
images: [], // urls to images
dataAttr: 'images', // html5 data- attribute which contains an array with urls to images
imgSelector: 'img', // element to change
interval: 1500, // ms
intervalFirst: 1500, // first image change, ms
callback: null // first argument would be the current image url
},
settings = $.extend({}, defaults, options);
var clearRotationInterval = function ($el) {
clearInterval($el.data('imagesRotaionTimeout'));
$el.removeData('imagesRotaionTimeout');
clearInterval($el.data('imagesRotaionInterval'));
$el.removeData('imagesRotaionInterval');
},
getImagesArray = function ($this) {
var images = settings.images.length ? settings.images : $this.data(settings.dataAttr);
return $.isArray(images) ? images : false;
},
preload = function (arr) { // images preloader
$(arr).each(function () {
$('<img/>')[0].src = this;
$this.fadeIn("slow");
});
},
init = function () {
var imagesToPreload = [];
this.each(function () { // preload next image
var images = getImagesArray($(this));
if (images && images.length > 1) {
imagesToPreload.push(images[1]);
}
});
preload(imagesToPreload);
};
init.call(this);
this.on('mouseenter.imagesRotation', function () {
var $this = $(this),
$img = settings.imgSelector ? $(settings.imgSelector, $this) : null,
images = getImagesArray($this),
imagesLength = images ? images.length : null,
changeImg = function () {
var prevIndex = $this.data('imagesRotationIndex') || 0,
index = (prevIndex + 1 < imagesLength) ? prevIndex + 1 : 0,
nextIndex = (index + 1 < imagesLength) ? index + 1 : 0;
$this.data('imagesRotationIndex', index);
if ($img && $img.length > 0) {
if ($img.is('img')) {
$img.attr('src', images[index]);
$this.fadeIn('slow');
}
else {
$img.css('background-image', 'url(' + images[index] + ')');
$img.fadeIn('slow');
}
}
if (settings.callback) {
settings.callback(images[index]);
}
preload([images[nextIndex]]); // preload next image
};
if (imagesLength) {
clearRotationInterval($this); // in case of dummy intervals
var timeout = setTimeout(function () {
changeImg();
var interval = setInterval(changeImg, settings.interval);
$this.data('imagesRotaionInterval', interval); // store to clear interval on mouseleave
}, settings.intervalFirst);
$this.data('imagesRotaionTimeout', timeout);
}
}).on('mouseleave.imagesRotation', function () {
clearRotationInterval($(this));
}).on('imagesRotationRemove', function () {
var $this = $(this);
$this.off('.imagesRotation');
clearRotationInterval($this);
});
};
$.fn.imagesRotationRemove = function () {
this.trigger('imagesRotationRemove');
};
Would that do the trick if it was in the right spot, or does fadeIn/Out not apply to preloaded images? Any help or tips are appreciated.
Thanks.
I can't figure out how to modify the below code to include a toggle button. When in 'normal' mode the button would make the element go fullscreen and then change its function to go back to 'normal' state.
I've modified the code from John Dyer's Native Fullscreen JavaScript API example:
var fsButton = document.getElementById('fsbutton'),
fsElement = document.getElementById('specialstuff'),
fsStatus = document.getElementById('fsstatus');
if (window.fullScreenApi.supportsFullScreen) {
fsStatus.innerHTML = 'YES: Your browser supports FullScreen';
fsStatus.className = 'fullScreenSupported';
// handle button click
fsButton.addEventListener('click', function() {
window.fullScreenApi.requestFullScreen(fsElement);
}, true);
fsElement.addEventListener(fullScreenApi.fullScreenEventName, function() {
if (fullScreenApi.isFullScreen()) {
fsStatus.innerHTML = 'Whoa, you went fullscreen';
} else {
fsStatus.innerHTML = 'Back to normal';
}
}, true);
} else {
fsStatus.innerHTML = 'SORRY: Your browser does not support FullScreen';
}
to this:
var container = document.getElementById('canvas'),
fsButton = document.getElementById('fsbutton');
if (window.fullScreenApi.supportsFullScreen) { // fullscreen supported
fsButton.style.display = 'block';
container.addEventListener(fullScreenApi.fullScreenEventName, function() {
fsButton.addEventListener('click', function() {
if (fullScreenApi.isFullScreen()) { // fullscreen is on
window.fullScreenApi.CancelFullScreen( container );
fsButton.className = 'fs-off';
} else { // fullscreen is off
window.fullScreenApi.requestFullScreen( container );
container.style.width = "100%";
container.style.height = "100%";
fsButton.className = 'fs-on';
}
}, true)
}, true);
} else {
// no fullscreen support - do nothing
}
But it doesn't work. Any suggestions much appreciated!
The other problem you'll have is that Mozilla wants you to listen to the fullscreenchange event on the document element, not the element that is going fullscreen.
// which object can handle a fullscreen event
var fullscreenObj = (fullScreenApi.fullScreenEventName.indexOf('moz') > -1 : document : container;
fullscreenObj.addEventListener(fullScreenApi.fullScreenEventName, function() {
if (fullScreenApi.isFullScreen()) {
container.style.width = container.style.height = '100%';
fsButton.className = 'fs-on';
} else {
fsButton.className = 'fs-off';
}
}, true);
First of all, you shouldn't nest fsButton click event listener into fullScreenApi's event listener because it won't work until container goes fullscreen. fsButton's click is responsible for going fullscreen, event listener is being attached after going fullscreen so the action will never happen.
Here's a modified version of the code which should suit your needs:
var fsButton = document.getElementById('fsbutton'),
container = document.getElementById('canvas');
if (window.fullScreenApi.supportsFullScreen) {
fsButton.style.display = 'block';
fsButton.addEventListener('click', function() {
if (fsButton.className == 'fs-off') {
window.fullScreenApi.requestFullScreen(container);
} else {
window.fullScreenApi.cancelFullScreen(container);
}
}, true);
container.addEventListener(fullScreenApi.fullScreenEventName, function() {
if (fullScreenApi.isFullScreen()) {
container.style.width = container.style.height = '100%';
fsButton.className = 'fs-on';
} else {
fsButton.className = 'fs-off';
}
}, true);
} else {
// no fullscreen support - do nothing
}
I'd advise using something like https://github.com/sindresorhus/screenfull.js/
This wraps most of the browser quirks in a cleaner interface.