Start Video When It becomes In Focus - javascript

I'm trying to figure out a way to get my video to start playing only once it becomes in focus of the viewport. The video will be in a bunch of text of an article and I would like it to only play when the user scrolls down to it
<script>
window.onload = function() {
// Video
var video = document.getElementById("video");
// Buttons
var playButton = document.getElementById("play-pause");
var playButtonImg = document.getElementById("playButtonImg");
var muteButton = document.getElementById("mute");
var muteButtonImg = document.getElementById("muteButtonImg");
// Event listener for the play/pause button
playButton.addEventListener("click", function() {
if (video.paused == true) {
// Play the video
video.play();
// Update the button text to 'Pause'
playButtonImg.src = "pause-sm.png";
} else {
// Pause the video
video.pause();
// Update the button text to 'Play'
playButtonImg.src = "play-sm.png";
}
});
video.addEventListener("ended", function(){
playButtonImg.src = "replay-sm.png";
});
// Event listener for the mute button
muteButton.addEventListener("click", function() {
if (video.muted == false) {
// Mute the video
video.muted = true;
// Update the button text
muteButtonImg.src = "mute-sm.png";
} else {
// Unmute the video
video.muted = false;
// Update the button text
muteButtonImg.src = "volume-sm.png";
}
});
// Pause the video when the seek handle is being dragged
seekBar.addEventListener("mousedown", function() {
video.pause();
});
}
</script>

If you can use jQuery, waypoints is what you seek:
http://imakewebthings.com/waypoints/

Related

Moving through Vimeo videos with Javascript

I would like to play through Vimeo videos in sequence with JavaScript with continuous playback and looping through items. The following code moves to the second video at the end of the first but the same functions are not called at the end of the second video. Only the end of the first video shows Called! in the Javascript console, not the end of the second.
The Vimeo Player SDK has player.getVideoId() but not player.setVideoId() so I used a hack to load the next video: setting the source of the iframe and starting the Vimeo player anew. I wonder if this is the problem and the listener for the end of the video is attached to the discarded player.
Another issue with this code is that it exits fullscreen to load the next video.
I attempted this CodePen that sets the Vimeo Player on any element instead of an iframe and was unable to change the played video.
What is a cleaner or effective way of changing videos with the Vimeo Player SDK?
The HTML is:
<div class="vimeo">
<div class="resp-iframe-container container-centered">
<iframe class="resp-iframe" scrolling="no" frameborder="no" src="https://player.vimeo.com/video/238301525" allowfullscreen="" data-ready="true"></iframe></div></div>
And the javascript is:
var l = ["238301525", "496371201", "238301525", "496371201", "..."];
window.current = 0;
var increment = function() {
window.current += 1;
if (window.current == l.length) {
window.current = 0;
}
};
var decrement = function() {
window.current -= 1;
if (window.current < 0) {
window.current = l.length - 1;
}
};
prevA.addEventListener("click", function() {
decrement();
loadPlayer();
});
nextA.addEventListener("click", function() {
increment();
console.log("here!");
loadPlayer();
console.log("there!");
});
var loadPlayer = function() {
console.log("Called!");
var iframe = document.querySelector('iframe');
iframe.src = "https://player.vimeo.com/video/" + l[window.current];
var player = new Vimeo.Player(iframe);
player.autoplay = true;
var treatEvent = function(data, eventLabel) {
// Custom code...
if ("end" == eventLabel) {
console.log("incrementing automatically");
increment();
loadPlayer();
}
};
var onPlay = function(data) {
treatEvent(data, "play");
}
var onPause = function(data) {
treatEvent(data, "pause");
}
var onSeeked = function(data) {
treatEvent(data, "seeked");
}
var onEnd = function(data) {
treatEvent(data, "end");
}
player.on('play', onPlay);
player.on('pause', onPause);
player.on('seeked', onSeeked);
player.on('ended', onEnd);
setTimeout(function() {
//console.log("Trying to play...");
player.play().then(function() {
// the video was played
console.log("success: video played");
}).catch(function(error) {
console.log("Error! " + error.name);
});
}, 1000);
}
loadPlayer();
It seems that the Vimeo Player keeps track of whether it was initialized, adding a tag data-vimeo-initialized="true" in the HTML element.
One solution is to use the Vimeo Player SDK function .loadVideo():
var song_iframe = document.querySelector("iframe#song_video");
var song_player = new Vimeo.Player(song_iframe);
var on_song_end = function(data) {
// Logic to get the new id.
song_player.loadVideo(newId).then(function() {
song_player.play();
});
};
song_player.on("ended", on_song_end);

how can the audio going to play if the code given is correct on js

i am currently practicing my html and js skills and i have this code which is when i click the unlock button the audio will automatically play but the problem is even the unlock code is wrong the audio will still play this is my html on the button and on the audio
the audio tag:
<audio id="music" src="bgmusic.mp3" controls hidden loop></audio>
the button tag:
<button id="unlock" class="round pink" onclick="playAudio()">
Unlock
</button>
and here's my current js for the onlick event on the button
var x =
document.getElementById("music");
function playAudio() {
x.play();
}
that is my current syntax but what i want to happen is when the audio will only play if i enter the correct code
and here's the js function for the unlock code functionality:
var number = 0;
$('#unlock').on('click', function(event) {
event.preventDefault();
event.stopPropagation();
$('#textMachine').css('display', 'inline-block');
var code = '';
$.each($('.code'), function(i, v) {
code += $(v).val();
});
if(code == '30')
{
// success
var machine = $('#textMachine').slotMachine({
active: 0,
delay: 500,
randomize : function(activeElementIndex){
return 3;
}
});
machine.setRandomize(3);
machine.shuffle(5, function(){
answerCorrect();
});
} else {
if(number == 3) { number = 0; }
// fail
var machine = $('#textMachine').slotMachine({
active: 1,
delay: 500,
randomize : function(activeElementIndex){
return number;
}
});
machine.shuffle(5, function(){
number++;
});
}
});
var answerCorrect = function() {
$('.login-form').fadeOut();
$('.congratulation-text').fadeIn();
$('.success-area').css('display','block');
};
})();
well actually you can do this
function playSound () {
var audio = new Audio('audio_file.mp3');
audio.play();
}
and you can call it on your button or your function

Custom Controls for HTML5 Videos don't work

I am customising a video in html and css. So far the play button works and the full screen mode works too. But if I try to drag the slider (the one next to PLAY button) it is meant to change the position in the video too. Same with the volume button (next to MUTE button) - it doesn’t work if I try to slide it.
I wonder what is wrong with my code as I was partially following a tutorial and that’s the way they used for the tutorial.
<div id="video-container">
<!-- Video -->
<video id="video-container__video" width="640" height="365">
<source src='_assets/media/big_buck_bunny.mp4' type='video/mp4'>
</video>
<!-- Video Controls -->
<div id="video-controls">
<button type="button" id="video-controls__play-pause">Play</button>
<input type="range" id="video-controls__seek-bar" value="0">
<button type="button" id="video-controls__mute">Mute</button>
<input type="range" id="video-controls__volume-bar" min="0" max="1" step="0.1" value="1">
<button type="button" id="video-controls__full-screen">Full-Screen</button>
</div>
window.onload = function() {
//video
var video = document.getElementById("video-container__video");
//Buttons
var playButton = document.getElementById("video-controls__play-pause");
var muteButton = document.getElementById("video-controls__mute");
var fullScreenButton = document.getElementById("video-controls__full-screen");
//sliders
var seekBar = document.getElementById("video-controls__seek-bar");
var volumeBar = document.getElementById("video-controls__volume-bar");
//event listener for the play and pause button
playButton.addEventListener("click", function() {
if (video.paused == true) {
video.play();
//button text will change to Pause
playButton.innerHTML = "Pause";
} else {
//pause the video
video.pause();
//button will update its text to play
playButton.innerHTML = "Play";
}
});
// Event listener for the full-screen button
fullScreenButton.addEventListener("click", function() {
if (video.requestFullscreen) {
video.requestFullscreen();
} else if (video.mozRequestFullScreen) {
video.mozRequestFullScreen(); // Firefox
} else if (video.webkitRequestFullscreen) {
video.webkitRequestFullscreen(); // Chrome and Safari
}
});
//event listener for the change bar
seekBar.addEventListener("change", function() {
//calculate the new time
var time = video.duration * (seekBar.value / 100);
//update the video time
video.currentTime = time;
});
//the change bar will move as the video plays
video.addEventListener("timeupdate", function() {
//Calculate the slider value
var value = (100 / video.duration) * video.currentTime;
//Update the slider value
seekBar.value = value;
})
//pause the video when the slider handle is being dragged
seekBar.addEventListener("mousedown", function() {
video.pause();
});
//play the video when the
seekBar.addEventListener("mouseup", function() {
video.play();
});
volumeBar.addEventListener("change", function() {
//update the video volume
video.volume = volumeBar.value;
});
}

how do i add two event listeners/actions to one button

i'm trying to make the pause and play on "button" but am not sure how to do it. im guessing it needs to know that one click is active to switch to the other, but im not sure how to do that.
// Initialize variables
var button = document.getElementById("button");
var button2 = document.getElementById("button2");
var rect = document.getElementById("rect");
var polygon = document.getElementById("polygon");
var circle = document.getElementById("circle");
// Define functions
function play() {
rect.setAttribute("class", "anim");
polygon.setAttribute("class", "anim");
circle.setAttribute("class", "anim");
}
function pause() {
rect.setAttribute("class", "pause");
polygon.setAttribute("class", "pause");
circle.setAttribute("class", "pause");
}
// Add event listeners
button.addEventListener("click", play, false);
button2.addEventListener("click", pause, false);
You can write a toggle handler instead:
function playPause()
{
if (this.playState) {
rect.className = polygon.className = circle.className = 'pause';
} else {
rect.className = polygon.className = circle.className = 'anim';
}
// update button text to indicate state?
this.playState = !this.playState;
}
It keeps a state on the DOM element itself and switches between paused and playing.
If you are using two different buttons then Try this,
var isplaying = false;
function play() {
isplaying = true;
rect.setAttribute("class", "anim");
polygon.setAttribute("class", "anim");
circle.setAttribute("class", "anim");
}
function pause() {
isplaying = false;
rect.setAttribute("class", "pause");
polygon.setAttribute("class", "pause");
circle.setAttribute("class", "pause");
}
// Add event listeners
button.addEventListener("click",function(){ if(!isplaying){
button.disable(); button2.enable(); play();}});
button2.addEventListener("click",function(){ if(isplaying){
button2.disable(); button.enable(); pause();}});

How pause the (playing) background music when the next tab button is pressed

I have a HTML5 audio background music player that has one button to play and pause. It has animate effect so music fades in or out in case of playing or pausing. Also I have 2 tabs in my page which in one of them there is a youtube video. So I would like the fade out the background music when the button of the next slide is pressed. And when the button of the slide is pressed again (back to the first slide which has no video) the music fades in and plays.
Here is the DEMO on JSFiddle
And this is my jquery code:
$('#go').on('click',function(evt){
var active = $('.accordion:visible');
var nextElement = active.next();
active.hide();
if(nextElement.hasClass("accordion")){
nextElement.fadeIn(1000);
}else{
$('.accordion:first').fadeIn(1000);
}
});
//Music player
var beepTwo = $("#musicBeat");
beepTwo[0].play();
$("#dan").click(function() {
if (beepTwo[0].paused == false) {
beepTwo[0].pause();
beepTwo.animate({volume: 0}, 2000, 'swing', function() {
// really stop the music
});
$(this).addClass("is-paused");
} else {
beepTwo[0].play();
beepTwo.animate({volume: 1}, 2000);
$(this).removeClass("is-paused");
}
});
There you go:
$('#go').on('click',function(evt){
var active = $('.accordion:visible');
var nextElement = active.next();
active.hide();
if(!nextElement.hasClass("accordion")){
nextElement = $('.accordion:first');
}
nextElement.fadeIn(1000);
if(nextElement.attr('id') == 'one') {
playBackgroundMusic();
}else {
pauseBackgroundMusic();
}
});
function mute() {
muted = true;
pauseBackgroundMusic();
}
function unmute() {
muted = false;
playBackgroundMusic();
}
function pauseBackgroundMusic() {
if (beepTwo[0].paused == false) {
beepTwo.animate({volume: 0}, 2000, 'swing', function() {
// really stop the music
beepTwo[0].pause();
});
$('#dan').addClass("is-paused");
}
}
function playBackgroundMusic() {
// only play music if the player is not muted
if (beepTwo[0].paused == true && muted == false) {
beepTwo[0].play();
beepTwo.animate({volume: 1}, 2000);
$('#dan').removeClass("is-paused");
}
}
function toggleBackgroundMusic() {
if (muted) {
unmute();
} else {
mute();
}
}
$('#dan').click(toggleBackgroundMusic);
//Music player
var beepTwo = $("#musicBeat");
var muted = false;
playBackgroundMusic();
What the script now does it to look whether the next open accordion tab has the id "one". In this case the music is played. If any other tab is opened the music is paused.
The toggleBackgroundMusic() method is used for the player to switch.
In case you want to add more tabs and play/pause the music you can simply edit the if clause in the #go element's onClick function.
The working demo is at:
http://jsfiddle.net/4Trwc/4/
Edit:
And with the new muting feature:
http://jsfiddle.net/4Trwc/6/
Edit-2:
Fade-out fixed:
http://jsfiddle.net/4Trwc/7/

Categories

Resources