Javascript play/pause button for video only pauses - javascript

I've setup a play/pause video button in javascript, that was working, but now doesn't and I don't know why. It now only fires once, pausing but not playing.
Basically, the "if" part of my playButton function works correctly, but the "else" part doesn't seem to function correctly. It did previously, so I imagine there's just a missing element somewhere. I have even checked it in a code validator and it passes. What to do?
Please, see my code below...
window.onload = function() {
const video = document.getElementById('intro-video');
const playPause = document.getElementById('play-button');
const enlarge = document.getElementById('full-screen');
const progressBar = document.getElementById('progress-bar');
playPause.addEventListener('click', function playButton() {
if (video.play) {
video.pause()
playPause.innerHTML = 'Play Video'
playPause.style.backgroundImage = 'url(https://alcove.bensmiles.com/wp-content/uploads/Alcove-Icon_Play.svg)'
} else {
video.play()
playPause.innerHTML = 'Pause Video'
playPause.style.backgroundImage = 'url(https://alcove.bensmiles.com/wp-content/uploads/Alcove-Icon_Pause.svg)'
}
});
enlarge.addEventListener('click', function enlarge() {
if (video.requestFullscreen) {
video.requestFullscreen();
} else if (video.mozRequestFullScreen) {
video.mozRequestFullScreen(); // Firefox
} else if (video.webkitRequestFullscreen) {
video.webkitRequestFullscreen(); // Chrome and Safari
}
});
progressBar.addEventListener('change', function progressBar() {
const time = video.duration * (progressBar.value / 100);
video.currentTime = time;
});
video.addEventListener('timeupdate', function progressTime() {
const value = (100 / video.duration) * video.currentTime;
progressBar.value = value;
});
progressBar.addEventListener('mousedown', function progressPause() {
video.pause();
});
progressBar.addEventListener('mouseup', function progressPlay() {
video.play();
});
};
<!doctype html>
<html lang='en-ZA'>
<head>
<meta charset='UTF-8'>
<title>Alcôve – Discover Opulence</title>
<link rel='dns-prefetch' href='//fonts.googleapis.com'>
<link rel='fonts' href='https://fonts.googleapis.com/css2?family=Work+Sans:wght#400;500;600;700&display=swap'>
<link rel='stylesheet' href='Style.css'>
<script rel='javascript' src='Controls.js'></script>
</head>
<body>
<div id='container'>
<div id='top' class='section dark'>
<div id='row1' class='row'>
<div id='main-menu'>
<ul>
<li><a href='https://alcove.bensmiles.com'>About Us</a></li>
<li><a href='https://alcove.bensmiles.com/committee'>Executive Committee</a></li>
<li><a href='https://alcove.bensmiles.com/news'>The Opulent News</a></li>
<li><a href='https://alcove.bensmiles.com/foundation'>Foundation</a></li>
<li><a href='https://alcove.bensmiles.com/contact'>Contact</a></li>
</ul>
</div>
<div class='column left'>
<div id='logo'>
<img src='https://alcove.bensmiles.com/wp-content/uploads/Alcove-Logo.svg'>
</div>
<div id='header-headline'>
<p>Alcôve Holdings</p>
<h1>Discover<br>Opulence</h1>
</div>
</div>
<div class='column right'>
<div id='menu-block'>
<img id='header-image' src='https://alcove.bensmiles.com/wp-content/uploads/Alcove-Header.png'>
<div id='header-copy'>
<p>Alcôve finds satisfaction in establishing an atmosphere where excellence is celebrated, and confidence is originated. We inspire the youth to lead with precision and passion by igniting their desire to discover opulence through Alcôve.</p>
</div>
<div id='video-console'>
<div id='video-player'>
<video autoplay muted id='intro-video'poster='https://alcove.bensmiles.com/wp-content/uploads/Alcove-Video_Poster.png' width='214px' height='120px'>
<source src='https://alcove.bensmiles.com/wp-content/uploads/Alcove-Video_Intro.mp4' type='video/mp4'>
<source src='https://alcove.bensmiles.com/wp-content/uploads/Alcove-Video_Intro.ogv' type='video/ogv'>
<source src='https://alcove.bensmiles.com/wp-content/uploads/Alcove-Video_Intro.webm' type='video/webm'>
</video>
<div id='video-details'>
<button id='full-screen' type='button'><img src='https://alcove.bensmiles.com/wp-content/uploads/Alcove-Icon_Enlarge.svg'></button>
<div id='video-headline'>
<p>Headline of the video playing</p>
</div>
</div>
</div>
<div id='video-controls'>
<button id='play-button' type='button'>Pause Video</button>
<input id='progress-bar' type='range' value='0'>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

video.play references the play method of video. In Javascript, every non-null (non-zero, etc respectively) counts as true. Because the play method exists, it will never go to the else part. Instead, use if (!video.paused).
Just one more thing: decide whether to use semicolons or to not. If you use both styles, it makes the code a bit weird.

Try this:
playPause.addEventListener('click', function playButton() {
if (video.paused || video.ended) {
video.play()
playPause.innerHTML = 'Pause Video'
playPause.style.backgroundImage = 'url(https://alcove.bensmiles.com/wp-content/uploads/Alcove-Icon_Pause.svg)'
} else {
video.pause()
playPause.innerHTML = 'Play Video'
playPause.style.backgroundImage = 'url(https://alcove.bensmiles.com/wp-content/uploads/Alcove-Icon_Play.svg)'
}
});

Related

Same functionality without having to remove classes?

I have three HTML 5 audio elements on a page, each with a different ID (sound,1 sound2, sound3). I have a piece of code to trigger those sounds when a div block is clicked but I made some modifications so that there is no need to double click the same div block in order to trigger the code again. The problem is that the modification I made prohibits the code from pausing the audio.
Is there any way of having this same functionality but with the possibility of pausing the audio when the div block is clicked again?
<script type="text/javascript">
$(".play").on('click', function () {
var $this = $(this);
var id = $this.attr('id').replace(/area/, '');
$.each($('audio'), function () {
this.pause();
$(".play").removeClass("active");
});
$this.toggleClass('active');
if($this.hasClass('active')) {
$('audio[id^="sound"]')[id-1].play();
} else {
$('audio[id^="sound"]')[id-1].pause();
}
});
</script>
html as follows
<body class="body-2">
<div class="viewport-div"><a id="muteaudio" href="#" class="mute w-inline-block"></a>
<div class="image-div"><img src="image" loading="lazy" alt="" class="gif" /><a id="2" href="#" class="link-block-3 play w-inline-block"></a><a id="1" href="#" class="link-block-1 play w-inline-block"></a><a id="3" href="#" class="link-block-4 play w-inline-block"></a></div>
</div>
<div class="w-embed w-script">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>>
<script type="text/javascript">
$(".play").on('click', function() {
var $this = $(this);
var id = $this.attr('id').replace(/area/, '');
$.each($('audio'), function() {
this.pause();
$(".play").removeClass("active");
});
$this.toggleClass('active');
if ($this.hasClass('active')) {
$('audio[id^="sound"]')[id - 1].play();
} else {
$('audio[id^="sound"]')[id - 1].pause();
}
});
</script>
<script type="text/javascript">
</script>
<audio id="sound1" src="sound1.mp3"> </audio>
<audio id="sound2" src="sound2.mp3"> </audio>
<audio id="sound3" src="sound3.mp3"> </audio>
</div>
<div class="s-hero-nav-wrapper-2">
<div data-collapse="medium" data-animation="over-right" data-duration="400" role="banner" class="nav-2 w-nav">
<div class="c-1200-2 w-clearfix"><img src="https://assets.website-files.com/60ae8c4857598e31ccef08c2/60af6746a2ede9432d6cdc33_NFTeaLand_logo.png" loading="lazy" width="998" alt="" class="image" />
<nav role="navigation" class="nav-menu-2 w-nav-menu">page1page2</nav>
<div data-w-id="d6104950-09a0-2661-ce3e-80774ebb96bd" class="nav-menu-btn w-nav-button">
<div class="nav-menu-icon w-icon-nav-menu"></div>
</div>
</div>
</div>
</div>
<script src="https://d3e54v103j8qbb.cloudfront.net/js/jquery-3.5.1.min.dc5e7f18c8.js?site=60ae8c4857598e31ccef08c2" type="text/javascript" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://assets.website-files.com/60ae8c4857598e31ccef08c2/js/webflow.2a88899ee.js" type="text/javascript"></script>
<!--[if lte IE 9]><script src="//cdnjs.cloudflare.com/ajax/libs/placeholders/3.0.2/placeholders.min.js"></script><![endif]-->
</body>
Note that you are removing the active class form all element that has paly class even from current element that has been clicked, by this line: $(".play").removeClass("active");.
So simply you need to check if the element is the current item you shouldn't remove active class:
$.each($('audio'), function (e, el) {
if ("sound" + (id-1) != el.id) {
this.pause();
el.classList.remove("active");
}
});
Here is working snippet:
$(".play").on('click', function (event) {
var $this = $(this);
var id = $this.attr('id').replace(/area/, '');
$.each($('audio'), function (e, el) {
if ("sound" + (id-1) != el.id) {
this.pause();
el.classList.remove("active");
}
});
$this.toggleClass('active');
if ($this.hasClass('active')) {
$('audio[id^="sound"]')[id - 1].play();
} else {
$('audio[id^="sound"]')[id - 1].pause();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<a id="2" href="#" class="link-block-3 play w-inline-block">sound 1</a>
<a id="1" href="#" class="link-block-1 play w-inline-block">sound 2</a>
<a id="3" href="#" class="link-block-4 play w-inline-block">sound 3</a>
<div class="w-embed w-script">
<audio id="sound1" src="https://www.elated.com/res/File/articles/authoring/html/html5-audio/WhiteChristmas.mp3"> </audio>
<audio id="sound2" src="https://www.elated.com/res/File/articles/authoring/html/html5-audio/WhiteChristmas.mp3"> </audio>
<audio id="sound3" src="https://www.elated.com/res/File/articles/authoring/html/html5-audio/WhiteChristmas.mp3"> </audio>
</div>

Jquery working in firefox but not working in google chrome

I am trying to make clone of live channel.
I get video of that specific time from database, load it in player. And seek the video player at played time with jquery and don't let the user seek video forward. After calculating deifference of video's current and ending time i set the page to reload itself after that time to load next video.
My code is working on firefox and internet explorer but not
on chrome.
Here it is HTML
<meta http-equiv="refresh" content="<?php echo $reload_sec; ?>" >
<link href="http://vjs.zencdn.net/5.8.0/video-js.css" rel="stylesheet"
>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<!-- If you'd like to support IE8 -->
<script src="http://vjs.zencdn.net/ie8/1.1.2/videojs-ie8.min.js"></script>
<div class="main-content container">
<div class="row">
<div class="col-sm-1"></div>
<div class="col-sm-10">
<div align="center" class="embed-responsive embed-responsive-4by3">
<video id="my-video" class="video-js embed-responsive-item" controls preload="auto" width="840" height="264" data-setup="{}" autoplay="1">
<source src="<?php echo base_url('uploads/channelvideos/'.$file) ?>" type='video/mp4'>
<p class="vjs-no-js">
To view this video please enable JavaScript, and consider upgrading to a web browser that
supports HTML5 video
</p>
</video>
</div>
<button onclick="setCurTime()" type="button" class="btn btn-info" style="margin-top:5px"><span class="fa fa-television"></span> Live</button>
</div>
<div class="col-sm-1">
<input type="text" name="seektime" id="seektime" value="<?php echo $seek_at; ?>" />
</div>
</div>
</div>
<script src="http://vjs.zencdn.net/5.8.0/video.js"></script>
Now Jquery
<script type="text/javascript">
function setCurTime()
{
location.reload();
}
var vid = document.getElementById("my-video");
vid.onloadedmetadata = function()
{
$(window).on("load", function()
{
var seektimej = $("#seektime").val();
if (document.getElementById("my-video"))
{
videojs("my-video").ready(function()
{
var myPlayer = this;
setTimeout(function()
{
//Set initial time to seeked time
myPlayer.currentTime(seektimej);
setTimeout(function()
{
var currentTime = 0;
myPlayer.on("seeking", function(event)
{
if (currentTime < myPlayer.currentTime())
{
myPlayer.currentTime(currentTime);
}
});
myPlayer.on("seeked", function(event)
{
if (currentTime < myPlayer.currentTime())
{
myPlayer.currentTime(currentTime);
}
});
setInterval(function()
{
if (!myPlayer.paused())
{
currentTime = myPlayer.currentTime();
}
}, 10);
}, 50);
}, 50);
});
}
});
};
</script>

changing webpage randomly without getting the same page twice

I am trying to link 35 webpages with math.random. However I dont want it to go to each site more then once. So I have this:
function myFunction() {
var pages = ['sang1.html', 'sang2.html', 'sang3.html', 'sang4.html', 'sang5.html', 'sang6.html', 'sang7.html', 'sang8.html', 'sang9.html', 'sang10.html', 'sang11.html', 'sang12.html', 'sang13.html', 'sang14.html', 'sang15.html', 'sang17.html', 'sang18.html', 'sang19.html', 'sang20.html', 'sang21.html'];
var page, visitedPages = JSON.parse(localStorage.getItem("visitedPages"));
if (visitedPages === null) {
visitedPages = [];
}
if (pages.length !== visitedPages.length) {
for (var i = 0; i < pages.length; i++) {
page = pages[Math.floor((Math.random() * pages.length) + 1)];
if (visitedPages.indexOf(page) === -1) { //unvisited yet
localStorage.setItem("visitedPages", JSON.stringify(visitedPages.push(page)));
window.location.href = page;
break;
}
}
} else {window.location.href = score.html //All pages visited at once
}
}
a random page:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Gæt en sang</title>
<link rel="stylesheet" type="text/css" href="main.css">
<script src="Test.js"></script>
</head>
<body>
<audio class="hidden" controls autoplay>
<source src="horse.ogg" type="audio/ogg">
<source src="Original GhostBusters Theme Song.mp3" type="audio/mpeg">
</audio>
<div id="header">
<h2> Gæt sangen og hejs flagstangen!</h2>
</div>
<div id="left">
<ul> Hvilken sang er dette?
</br>
<button type="button" onclick="myFunction()">
<li> Ghost busters</li>
</button>
</br>
<button type="button" onclick="myFunction()">
<li> Poltergeist</li>
</button>
</br>
<button type="button" onclick="myFunction()">
<li> Something strange<li>
</button>
</br>
<button type="button" onclick="myFunction()">
<li> Who are you gonna call<li>
</button>
</ul>
</div>
</div>
<p id="Test"></p>
</body>
</html>
so I have a button you press and then it starts myfunction. This goes for all my sites. However when i press my button it always goes to page 2. And only from page 1. Any suggestions to what is wrong?
Instead of having a list of visited pages, have a list of all pages which you splice a random one out of on every click. An example without the finishing page:
var pages = JSON.parse(localStorage.getItem("pages"));
if (pages === null) {
pages = ['sang1.html', 'sang2.html', 'sang3.html', 'sang4.html', 'sang5.html', 'sang6.html', 'sang7.html', 'sang8.html', 'sang9.html', 'sang10.html', 'sang11.html', 'sang12.html', 'sang13.html', 'sang14.html', 'sang15.html', 'sang17.html', 'sang18.html', 'sang19.html', 'sang20.html', 'sang21.html'];
}
function onClick () {
var randomIdx = Math.floor(Math.random() * pages.length),
page = pages[randomIdx];
pages.splice(randomIdx, 0);
localStorage.setItem("pages", JSON.stringify(pages));
window.location.href = page;
}

javascript audio load not letting it pause

I am building a list of music, and each music has a play button. So when you click play the button turns to pause button.
So when you music plays i want to be able to go down the list and click on another song with the current song stopping and the one i clicked to start.
At the moment i can go down the list and its playing the song but not its not letting me pause . When i click pause it just starts the song again.
here is my code
window.player = document.getElementById('player');
$('ul.tracks li span.play').click(function(){
$('ul.tracks li span.play').find('i').removeClass().addClass('fi-play');
var trackid = $(this).attr('id');
var track;
if(trackid == 'play1'){
track = 'img/music.mp3';
} else if(trackid == 'play2'){
track = 'img/music2.mp3';
} else {
track = 'img/music3.mp3';
}
$('#player_track').attr('src', track);
player.load();
if (player.paused) {
player.play();
$(this).html('<i class="fi-pause"></i>');
} else {
player.pause();
player.empty();
$(this).html('<i class="fi-play"></i>');
}
});
And here is the html
<audio id="player">
<source id="player_track" src="img/music.mp3" />
</audio>
<ul class="tracks">
<li>
<div class="row">
<div class="large-8 columns">1. No Church in the Wild (feat. Frank Ocean)</div>
<div class="large-2 columns"><span class="play" id="play1"><i class="fi-play"></i></span></div>
</div>
<li>
<div class="row">
<div class="large-8 columns">2. Lift Off (feat. Beyonce)</div>
<div class="large-2 columns"><span class="play" id="play2"><i class="fi-play"></i></span></div>
</div>
</li>
<li>
<div class="row">
<div class="large-8 columns">3. Niggas in Paris</div>
<div class="large-2 columns"><span class="play" id="play3"><i class="fi-play"></i></span></div>
</div>
</li>
</ul>
But when i move player.load() into the if statement, i can pause it but when i click on another song while one is playing, it just stops. So what am i doing wrong?
You need to check if the file clicked is the one loaded by the player. You can do that by wrapping the track-setting code and the player.load in this if-statement.
if ($('#player_track').attr('src') !== track){
$('#player_track').attr('src', track);
player.load();
}
The whole code:
window.player = document.getElementById('player');
$('ul.tracks li span.play').click(function(){
$('ul.tracks li span.play').find('i').removeClass().addClass('fi-play');
var trackid = $(this).attr('id');
var track;
if(trackid == 'play1'){
track = 'img/music.mp3';
} else if(trackid == 'play2'){
track = 'img/music2.mp3';
} else {
track = 'img/music3.mp3';
}
if ($('#player_track').attr('src') !== track){
$('#player_track').attr('src', track);
player.load();
}
if (player.paused) {
player.play();
$(this).html('<i class="fi-pause"></i>');
} else {
player.pause();
player.empty();
$(this).html('<i class="fi-play"></i>');
}
});

Win8 Metro (JS/HTML5) - Video not visible after page navigation

I'm working on a media playback app that has two navigatable pages. I would like to store the video object so that if the user navigates away from the video page and then returns, the same object is loaded into the div and the user can simply pick up where they left off.
My problem: When the user returns to the video page, the video element reloads from scratch and I can't load it with the pre-existing video data. As a result, there is no video visible on the screen. My player controls, however, are tied to the original video object and continue to work as expected.
I'm new to these languages so any advice would be a great help. I can't figure it out for the life of me.
Here's the code. I initialize mediaSession and the flags in another script so they persist during page navigation.
The player page HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>homepage</title>
<!-- WinJS references -->
<link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
<link href="/css/default.css" rel="stylesheet" />
<link href="/pages/mediacontent/mediacontent.css" rel="stylesheet" />
<!-- <script src="/js/appData.js"></script> -->
<script src="/pages/mediacontent/mediacontent.js"></script>
</head>
<body>
<div class="body_div">
<header id="header_titlearea">
<h1 class="win-type-ellipsis">
<img src="/images/logo.png" /><span> Decoder Sample App</span>
</h1>
</header>
<div id="article_maintext">
<video id="playbackVideo" height="100%" preload="auto">
<!--<video id="Video1" height="100%" preload="auto" >-->
<!--<source src="/media/demo.mp4" />-->
</video>
</div>
<footer id="footer">
<br />
<input type="range" class="s_Class" id="s_Seek" value="0"><br />
<button class="action secondary" id="b_playFromFile">File Picker</button>
<button class="action secondary" id="b_playbackPause">Play</button>
<button class="action secondary" id="b_playbackStop">Stop</button>
<button class="action secondary" id="b_playbackRewind">Rewind</button>
<button class="action secondary" id="b_playbackForward">Forward</button>
<button class="action secondary" id="b_playbackMute">Mute</button>
<button id="navButton" class="navButton" title="Nav" >About</button><br />
<p id="outputtext">debug monitor</p>
</footer>
</div>
</body>
</html>
The player page JS (excerpt):
(function f() {
"use strict";
WinJS.UI.Pages.define("/pages/mediacontent/mediacontent.html", {
ready: function(element, options) {
if (mediaSession.navflag === false) {
mediaSession.vid = WinJS.Utilities.query("#playbackVideo")[0];
mediaSession.vid.src = "/media/demo.mp4";
document.getElementById('outputtext').innerHTML = "new mediaSession set!"
} else if (mediaSession.navflag === true) {
if (mediaSession.pauseflag === false) {
//mediaSession.vid.play();
}
document.getElementById('outputtext').innerHTML = "existing mediaSession!"
*-Here is where I need help-*
mediaSession.navflag = false;
}
...
}
}
}
After a few false leads, I figured out how to swap out the reloaded video element with my video data, using the replaceChild() method.
the new javascript looks like this:
(function f() {
"use strict";
WinJS.UI.Pages.define("/pages/mediacontent/mediacontent.html", {
ready: function(element, options) {
if (mediaSession.navflag === false) {
mediaSession.vid = WinJS.Utilities.query("#playbackVideo")[0];
mediaSession.vid.src = "/media/demo.mp4";
document.getElementById('outputtext').innerHTML = "new mediaSession set!"
} else if (mediaSession.navflag === true) {
if (mediaSession.pauseflag === false) {
//mediaSession.vid.play();
}
document.getElementById('outputtext').innerHTML = "existing mediaSession!"
var mediaParent = document.getElementById("article_maintext");
mediaParent.replaceChild(mediaSession.vid, mediaParent.firstElementChild);
mediaSession.navflag = false;
}
...
}
}
}

Categories