Progress bar for multiple audio player - javascript

I am working on creating a player in a page. In the page there will be multiple players. So progress bar needs to be shown for the current player that is being played. But the issue is when i play the player the progress bar is rendered in some other place because of multiple id's of the progress bar div. How can i target the progress div of the current player that is being played.
I am using javascript to render the progress bar.
Below is the HTML code: There will be multiple html blocks like below in different tabs of the page.
<div class="prabhata-play audio-playlist ">
<div class="d-flex justify-content-between">
<ul class="d-flex list-inline">
<li>
<button class="togglePlay" onclick="togglePlay('1445')" id="toogle1445">
<img src="./play-round.svg" alt="play" class="play-img" id="playImage">
</button>
</li>
<li>
<p class="title">Contentment in professional life</p>
<p class="auth-title">Swami Bhoomananda Tirtha</p>
</li>
</ul>
<div class="d-inline text-end">
<ul class="list-inline d-flex icons-sec">
<li><img src="./video-list.svg" alt="video-list"></li>
<li><img src="./heart.svg" alt="heart"></li>
<li><img src="./download-icon.svg" alt="download"></li>
</ul>
<span class="time-duration">0:39</span>
</div>
</div>
<div class="progress" id="progress1445"></div>
<audio id="audio1445" class="audio-link" src="./AkashavallepaVidooragoham.mp3"></audio>
Javascript Code :
function togglePlay (count, e) {
e = e || window.event;
var btn = e.target;
var timer;
var percent = 0;
var audio1 = document.getElementById("audio"+count);
audio1.addEventListener("playing", function(_event) {
var duration = _event.target.duration;
advance(duration, audio1);
});
audio1.addEventListener("pause", function(_event) {
clearTimeout(timer);
});
var advance = function(duration, element) {
var progress = document.getElementById("progress"+count);
increment = 10/duration
percent = Math.min(increment * element.currentTime * 10, 100);
progress.style.width = percent+'%'
startTimer(duration, element);
}
var startTimer = function(duration, element){
if(percent < 100) {
timer = setTimeout(function (){advance(duration, element)}, 100);
}
}
if (!audio1.paused) {
btn.classList.remove('active');
audio1.pause();
isPlaying = false;
} else {
btn.classList.add('active');
audio1.play();
isPlaying = true;
}
}

Your question is a bit confusing, but I'm assuming the issue is from there being multiple divs with the same id on the page. To fix this, try using document.querySelector() Documentation Here
For example, each player could be like this:
Html:
<div class="prabhata-play audio-playlist " id="player1">
<div class="progress" id="progress1445"></div>
<audio id="audio1445" class="audio-link" src="http://nat.verifinow.in/wp-content/uploads/2021/06/AkashavallepaVidooragoham.mp3"></audio>
</div>
Then in the JS, you could access the progress div using:
document.querySelector("div#player1 > div#progress1445");

Related

HTML + JavaScript custom player for multiple videos on a website page

EDIT: I have found the solution, posted and marked as the best answer below.
I'm coding a portfolio website for myself using HTML, CSS and JS and I need to add multiple videos on a lot of pages.
I followed some tutorials to learn how to customize the video player, but it only works for one specific video on the page. If I were to add more videos, I'd need to have one .js custom player file for each video and manually select them on the website.
How can I apply this single .js custom video player to all of my videos using purely javascript?
I have found similar topics about the subject here, but all of them uses jQuery and I'm struggling to make it work with javascript.
My HTML for the video player:
<section class="videoplayer">
<div class="c-video">
<div id="video_player">
<video src="./media/portfolio/videos/Show-Reel-2021.mp4" id="main-video"></video>
<div class="progressAreaTime">00:00</div>
<div class="controls">
<div class="progress-area">
<div class="progress-bar">
<span></span>
</div>
<div class="buffered-progress-bar"></div>
</div>
<div class="controls-list">
<div class="controls-left">
<span class="icon">
<i class="material-icons fast-rewind" title="Retroceder 10 segundos">first_page</i>
</span>
<span class="icon">
<i class="material-icons play_pause" title="Reproduzir">play_arrow</i>
</span>
<span class="icon">
<i class="material-icons fast-forward" title="Avançar 10 segundos">last_page</i>
</span>
<span class="icon">
<i class="material-icons volume" title="Sem áudio">volume_up</i>
<input type="range" min="0" max="100" class="volume_range">
</span>
<div class="timer">
<span class="current">00:00</span> / <span class="duration">0:00</span>
</div>
</div>
<div class="controls-right">
<span class="icon">
<i class="material-icons auto-play" title="A repetição automática está desativada"></i>
</span>
<span class="icon">
<i class="material-icons settingsBtn" title="Detalhes">settings</i>
</span>
<span class="icon">
<i class="material-icons picture_in_picture" title="Miniplayer">picture_in_picture_alt</i>
</span>
<span class="icon">
<i class="material-icons fullscreen" title="Tela inteira">fullscreen</i>
</span>
</div>
</div>
</div>
<div id="settings">
<div class="playback">
<span>Velocidade da Reprodução</span>
<ul>
<li data-speed="0.25">0.25</li>
<li data-speed="0.5">0.5</li>
<li data-speed="0.75">0.75</li>
<li data-speed="1" class="active">Normal</li>
<li data-speed="1.25">1.25</li>
<li data-speed="1.5">1.5</li>
<li data-speed="1.75">1.75</li>
<li data-speed="2">2</li>
</ul>
</div>
</div>
</div>
</div>
My JavaScript for the video player:
// Select elements
const vidsrc = document.querySelector('#main-video').src;
const video_player = document.querySelector('#video_player'),
mainVideo = video_player.querySelector('#main-video'),
progressAreaTime = video_player.querySelector('.progressAreaTime'),
controls = video_player.querySelector('.controls'),
progressArea = video_player.querySelector('.progress-area'),
progress_Bar = video_player.querySelector('.progress-bar'),
buffered_Bar = video_player.querySelector('.buffered-progress-bar'),
fast_rewind = video_player.querySelector('.fast-rewind'),
play_pause = video_player.querySelector('.play_pause'),
fast_forward = video_player.querySelector('.fast-forward'),
volume = video_player.querySelector('.volume'),
volume_range = video_player.querySelector('.volume_range'),
current = video_player.querySelector('.current'),
totalDuration = video_player.querySelector('.duration'),
auto_play = video_player.querySelector('.auto-play'),
settingsBtn = video_player.querySelector('.settingsBtn'),
picture_in_picture = video_player.querySelector('.picture_in_picture'),
fullscreen = video_player.querySelector('.fullscreen'),
settings = video_player.querySelector('#settings'),
playback = video_player.querySelectorAll('.playback li');
mainVideo.addEventListener('loadeddata',()=>{
setInterval(() => {
let bufferedTime = mainVideo.buffered.end(0);
let duration = mainVideo.duration;
let width = (bufferedTime / duration) * 100;
buffered_Bar.style.width = `${width}%`
}, 500);
})
// Play
function playVideo() {
play_pause.innerHTML = "pause";
play_pause.title = "Pausar";
video_player.classList.add('paused')
mainVideo.play();
}
// Pause
function pauseVideo() {
play_pause.innerHTML = "play_arrow";
play_pause.title = "Reproduzir";
video_player.classList.remove('paused')
mainVideo.pause();
}
play_pause.addEventListener('click',()=>{
const isVideoPaused = video_player.classList.contains('paused');
isVideoPaused ? pauseVideo() : playVideo();
})
mainVideo.addEventListener('play',()=>{
playVideo();
})
mainVideo.addEventListener('pause',()=>{
pauseVideo();
})
// Rewind
fast_rewind.addEventListener('click',()=>{
mainVideo.currentTime -= 10;
})
// Forward
fast_forward.addEventListener('click',()=>{
mainVideo.currentTime += 10;
})
// Total duration
mainVideo.addEventListener("loadeddata",(e)=>{
let videoDuration = e.target.duration;
let totalMin = Math.floor(videoDuration / 60);
let totalSec = Math.floor(videoDuration % 60);
// Complete with zero at beggining
totalSec < 10 ? totalSec = "0"+totalSec:totalSec;
totalMin < 10 ? totalMin = "0"+totalMin:totalMin;
totalDuration.innerHTML = `${totalMin}:${totalSec}`;
})
// Current duration
mainVideo.addEventListener('timeupdate',(e)=>{
let currentVideoTime = e.target.currentTime;
let currentMin = Math.floor(currentVideoTime / 60);
let currentSec = Math.floor(currentVideoTime % 60);
// Complete with zero at beggining
currentSec < 10 ? currentSec = "0"+currentSec:currentSec;
currentMin < 10 ? currentMin = "0"+currentMin:currentMin;
current.innerHTML = `${currentMin}:${currentSec}`;
let videoDuration = e.target.duration
// Seek bar
let progressWidth = (currentVideoTime / videoDuration) * 100;
progress_Bar.style.width = `${progressWidth}%`;
})
// Update current duration
progressArea.addEventListener('click',(e)=>{
let videoDuration = mainVideo.duration;
let progressWidthval = progressArea.clientWidth;
let ClickOffsetX = e.offsetX;
mainVideo.currentTime = (ClickOffsetX / progressWidthval) * videoDuration;
})
// Volume
function changeVolume() {
mainVideo.volume = volume_range.value / 100;
if (volume_range.value == 0) {
volume.innerHTML = "volume_off";
}else if(volume_range.value < 40){
volume.innerHTML = "volume_down";
}else{
volume.innerHTML = "volume_up";
}
}
function muteVolume() {
if (volume_range.value == 0) {
volume_range.value = 80;
mainVideo.volume = 0.8;
volume.innerHTML = "volume_up";
volume.title = "Sem áudio";
}else{
volume_range.value = 0;
mainVideo.volume = 0;
volume.innerHTML = "volume_off";
volume.title = "Reativar o som";
}
}
volume_range.addEventListener('change',()=>{
changeVolume();
})
volume.addEventListener('click',()=>{
muteVolume();
})
// Update on mouse move
progressArea.addEventListener('mousemove',(e)=>{
let progressWidthval = progressArea.clientWidth;
let x = e.offsetX;
progressAreaTime.style.setProperty('--x',`${x}px`);
progressAreaTime.style.display = "block";
let videoDuration = mainVideo.duration;
let progressTime = Math.floor((x/progressWidthval)*videoDuration);
let currentMin = Math.floor(progressTime / 60);
let currentSec = Math.floor(progressTime % 60);
// Complete with zero at beggining
currentSec < 10 ? currentSec = "0"+currentSec:currentSec;
currentMin < 10 ? currentMin = "0"+currentMin:currentMin;
progressAreaTime.innerHTML = `${currentMin}:${currentSec}`;
})
progressArea.addEventListener('mouseleave',()=>{
progressAreaTime.style.display = "none";
})
// Loop
auto_play.addEventListener('click',()=>{
auto_play.classList.toggle('active')
if(auto_play.classList.contains('active')){
auto_play.title = "A repetição automática está ativada";
}else{
auto_play.title = "A repetição automática está desativada";
}
});
mainVideo.addEventListener("ended",()=>{
if (auto_play.classList.contains('active')) {
playVideo();
}else{
play_pause.innerHTML = "replay";
play_pause.title = "Reproduzir novamente";
}
});
// Picture in picture
picture_in_picture.addEventListener('click',()=>{
mainVideo.requestPictureInPicture();
})
// Full screen
fullscreen.addEventListener('click',()=>{
if (!video_player.classList.contains('openFullScreen')) {
video_player.classList.add('openFullScreen');
fullscreen.innerHTML = "fullscreen_exit";
fullscreen.title = "Sair da tela inteira";
video_player.requestFullscreen();
}else{
video_player.classList.remove('openFullScreen');
fullscreen.innerHTML = "fullscreen";
fullscreen.title = "Tela inteira";
document.exitFullscreen();
}
});
// Settings
settingsBtn.addEventListener('click',()=>{
settings.classList.toggle('active');
settingsBtn.classList.toggle('active');
})
// Speed
playback.forEach((event)=>{
event.addEventListener('click',()=>{
removeActiveClasses();
event.classList.add('active');
let speed = event.getAttribute('data-speed');
mainVideo.playbackRate = speed;
})
})
function removeActiveClasses() {
playback.forEach(event => {
event.classList.remove('active')
});
}
// Get URL
let xhr = new XMLHttpRequest();
xhr.open("GET",vidsrc);
xhr.responseType = "arraybuffer";
xhr.onload = (e)=>{
let blob = new Blob([xhr.response]);
let url = URL.createObjectURL(blob);
mainVideo.src = url;
}
xhr.send();
// Store duration
window.addEventListener('unload',()=>{
let setDuration = localStorage.setItem('duration',`${mainVideo.currentTime}`);
let setSrc = localStorage.setItem('src',`${mainVideo.getAttribute('src')}`);
})
window.addEventListener('load',()=>{
let getDuration = localStorage.getItem('duration');
let getSrc = localStorage.getItem('src');
if (getSrc) {
mainVideo.src = getSrc;
mainVideo.currentTime = getDuration;
}
})
mainVideo.addEventListener('contextmenu',(e)=>{
e.preventDefault();
})
// Hide and show controls (mouse)
video_player.addEventListener('mouseover',()=>{
controls.classList.add('active');
})
video_player.addEventListener('mouseleave',()=>{
if (video_player.classList.contains('paused')) {
if (settingsBtn.classList.contains('active')) {
controls.classList.add('active');
}else{
controls.classList.remove('active')
}
}else{
controls.classList.add('active')
}
})
if (video_player.classList.contains('paused')) {
if (settingsBtn.classList.contains('active')) {
controls.classList.add('active');
}else{
controls.classList.remove('active')
}
}else{
controls.classList.add('active')
}
// Hide and show controls (mobile)
video_player.addEventListener('touchstart',()=>{
controls.classList.add('active');
setTimeout(() => {
controls.classList.remove('active')
}, 8000);
})
video_player.addEventListener('touchmove',()=>{
if (video_player.classList.contains('paused')) {
controls.classList.remove('active')
}else{
controls.classList.add('active')
}
})
Helper function which you can use to write the HTML skeleton once and then have it dynamically created for multiple instances
function renderVideoPlayers() {
const sources = [
'../my-video-src-1',
'../my-video-src-2',
'../my-video-src-3',
'../my-video-src-4',
]
const videoPlayers = sources.map((video) => `
<section class="videoplayer">
<div class="c-video">
<div id="video_player">
<video src="${video}" class="video"></video>
<div class="progressAreaTime">00:00</div>
<div class="controls">
<div class="progress-area">
<div class="progress-bar">
<span></span>
</div>
<div class="buffered-progress-bar"></div>
</div>
<div class="controls-list">
<div class="controls-left">
<span class="icon">
<i class="material-icons fast-rewind" title="Retroceder 10 segundos">first_page</i>
</span>
<span class="icon">
<i class="material-icons play_pause" title="Reproduzir">play_arrow</i>
</span>
<span class="icon">
<i class="material-icons fast-forward" title="Avançar 10 segundos">last_page</i>
</span>
<span class="icon">
<i class="material-icons volume" title="Sem áudio">volume_up</i>
<input type="range" min="0" max="100" class="volume_range">
</span>
<div class="timer">
<span class="current">00:00</span> / <span class="duration">0:00</span>
</div>
</div>
<div class="controls-right">
<span class="icon">
<i class="material-icons auto-play" title="A repetição automática está desativada"></i>
</span>
<span class="icon">
<i class="material-icons settingsBtn" title="Detalhes">settings</i>
</span>
<span class="icon">
<i class="material-icons picture_in_picture" title="Miniplayer">picture_in_picture_alt</i>
</span>
<span class="icon">
<i class="material-icons fullscreen" title="Tela inteira">fullscreen</i>
</span>
</div>
</div>
</div>
<div id="settings">
<div class="playback">
<span>Velocidade da Reprodução</span>
<ul>
<li data-speed="0.25">0.25</li>
<li data-speed="0.5">0.5</li>
<li data-speed="0.75">0.75</li>
<li data-speed="1" class="active">Normal</li>
<li data-speed="1.25">1.25</li>
<li data-speed="1.5">1.5</li>
<li data-speed="1.75">1.75</li>
<li data-speed="2">2</li>
</ul>
</div>
</div>
</div>
</div>
`)
// get an element already on the page add the rendered
// html for each video into that section.
const container = document.getElementById('container')
container.innerHTML = videoPlayers.join("")
}
// call this function when you want it to be displayed
renderVideoPlayers()
<html>
<head>
</head>
<body>
<div id="container">
</div>
</body>
</html>
You will also need to do the same with Javascript as well as ensure that there aren't multiple instance of the same id. This shouldn't be too hard as you can switch similiar styles to class and make the id's something like video-1, video-2, video-3, etc.
A couple notes
sources: this is an array of all video urls you wish to display on the page.
sources.map: will iterate through the array and interpolate a string with the video player HTML and video source
videoPlayers: is now an array of HTML markup
container: will be a parent element on the page where you wish to append all the HTML markup
I HAVE FOUND THE SOLUTION
For anyone in the future seeking for the same solution, I was able to make it work by first selecting every videoplayer div:
const videoContainers = document.querySelectorAll(".video-container")
Then using the .forEach() function so that the code will generate a button for every individual videoplayer:
videoContainers.forEach((container) => {
let playPauseBtn = container.querySelector(".play-pause-btn");
let theaterBtn = container.querySelector(".theater-btn");
let fullScreenBtn = container.querySelector(".full-screen-btn");
...
// The entire code for one videoplayer
}
You can reference "container" for the individual videoplayer or "document" for every videoplayer at once. It just works like magic!

Javascript play/pause button for video only pauses

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)'
}
});

Hide/show cards in bootstrap

Im trying to hide and show a few cards in bootstrap, but I can't figure it out.
All cards have the class card (of course) and im trying to hide all those cards when a button is clicked. Here is what I have now:
function myFunction() {
jQuery(document).ready(function($) {
$(".card").hide();
});
var game = document.getElementById("game").value;
var resolution = document.getElementById("resolution").value;
var graphic = document.getElementById("graphic").value;
if (game == "Black" && graphic == "high" && resolution == "1080") {
alert("Hello " + game + "! You will now be redirected to www.w3Schools.com");
} else if (book == "Red") {
} else if (book == "Green") {
} else {
}
}
The call for the function is correct cause the alert does work properly.
For some reason the
jQuery(document).ready(function($) {
$(".card").hide();
});
part does work when outside the js function (when it's not connected to the button).
No idea if it helps but here is also a snipped of my bootstrap doc:
<button type="submit" class="btn btn-primary" id="btn" onclick="myFunction()">Submit</button>
</form>
</div>
<!-- Results -->
<div class="card" id="p2" style="width:200px; margin:30px">
<img class="card-img-top" src="https://image" alt="Card image" style="width:100%">
<div class="card-body">
<h5 class="card-title">Processor</h5>
<p>Newegg</p>
<p>Newegg</p>
<p>Newegg</p>
</div>
</div>
<div class="card" id="p3" style="width:200px; margin:30px">
<img class="card-img-top" src="https://image" alt="Card image" style="width:100%">
<div class="card-body">
<h5 class="card-title">Graphic card</h5>
<p>Newegg</p>
<p>Newegg</p>
<p>Newegg</p>
</div>
</div>
Here the things I've tried already:
The toggle How to hide and show bootstrap 4 cards by hovering over navigation menu through css?
Standard js document.getElementById(".card").style.display = "none";
I've looked at the react stuff, but I don't understand that.
I think what you have to do is this if you want to make a show and hide toggle of all the elements that have the card class in your DOM.
var myFunction = function() {
var divsToHide = document.getElementsByClassName("card");
if(divsToHide.length>0){
for(var i = 0; i < divsToHide.length; i++){
if( divsToHide[i].style.display== "none"){
divsToHide[i].style.display = "block";
}else{
divsToHide[i].style.display = "none"; // depending on what you're doing
}
}} }
I hope it helps you

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>');
}
});

Sliding "cards" effect -- slides out, but not in

I'm using the following code to create a sliding card effect where each "card" is a list element and they slide across the screen. They are only visible within the "stage" I've set with specific height and width. It's working great -- except that, while the cards slide out nicely to the left, they don't perform the same sliding function inwards from the right. Instead, it simply jumps onto the page and looks a bit startling.
Does anyone know how I could get the next list item to slide in from the right instead of simply appearing?
Thanks!
JS:
window.addEvent('domready', function () {
var totIncrement = 0;
var increment = 968;
var maxRightIncrement = increment * (-303); //this is -303 because there are 303 cards, but the example below only has 3
var fx = new Fx.Style('slider-list', 'margin-left', {
duration: 300,
//transition: Fx.Transitions.Back.easeInOut,
wait: true
});
// EVENTS for the button "previous"
var pbuttons = document.getElementsByClassName('prevButton');
for(i = 0; i < pbuttons.length; i++) {
$(pbuttons[i]).addEvents({
'click': function (event) {
if(totIncrement > maxRightIncrement) {
totIncrement = totIncrement + increment;
fx.stop()
fx.start(totIncrement);
}
}
});
}
//-------------------------------------
// EVENTS for the button "next"
// var buttons = $('.nextButton');
var buttons = document.getElementsByClassName('nextButton');
for(i = 0; i < buttons.length; i++) {
$(buttons[i]).addEvents({
'click': function (event) {
if(totIncrement > maxRightIncrement) {
totIncrement = totIncrement - increment;
fx.stop()
fx.start(totIncrement);
}
}
});
}
});
HTML:
<div id="slider-stage">
<ul id="slider-list">
<li id="l1">
<!-- previous button -->
<div class="prev"><a class="prevButton" href="#">Previous</a></div>
<div>
<!-- content goes here -->
<!-- next button -->
<div class="slider-buttons">
<a class="nextButton" href="#">Next</a>
</div>
</div>
</li>
<li id="l2">
<!-- previous button -->
<div class="prev"><a class="prevButton" href="#">Previous</a></div>
<div>
<!-- content goes here -->
<!-- next button -->
<div class="slider-buttons">
<a class="nextButton" href="#">Next</a>
</div>
</div>
</li>
<li id="l3">
<!-- previous button -->
<div class="prev"><a class="prevButton" href="#">Previous</a></div>
<div>
<!-- content goes here -->
<!-- next button -->
<div class="slider-buttons">
<a class="nextButton" href="#">Next</a>
</div>
</div>
</li>
</ul>
</div>

Categories