Replace Javascript ID's with Clases for HTML5 Video Controls - javascript

I've replaced all ID's with Classes in the HTML and in the Javascript for the Video Player, but it's still doesn't work. I"m a newbie in javascript so I'm going to need some help to figure out why it's not runing the way that it should.
Here's a fiddle:
http://jsfiddle.net/k37Bs/
The updated JS suggested by Chris Ferdinandi still doesnt work. The JS is pasted below:
I replaced the Add Event Listener code completely and removed the setobject reference section of codes, still no dice. Any further help will be greatly appreciated.
//----------------------------Video Player--------------------------------------
var vid, playbtn, seekslider, curtimetext, durtimetext, mutebtn, volumeslider, fullscreenbtn;
//--------Functions------------------------------
// Initialize Player
function intializePlayer(){
window.onload = intializePlayer;
// Play/Pause Function
function playPause(){
if(vid.paused){
vid.play();
playbtn.style.background = "url(pause.png)";
} else { vid.pause();
playbtn.style.background = "url(play.png)";
}
}
// Video Seek Function
function vidSeek(){
var seekto = vid.duration * (seekslider.value / 100);
vid.currentTime = seekto;
}
// Seektime Update
function seektimeupdate(){
var nt = vid.currentTime * (100 / vid.duration);
seekslider.value = nt;
var curmins = Math.floor(vid.currentTime / 60);
var cursecs = Math.floor(vid.currentTime - curmins * 60);
var durmins = Math.floor(vid.duration / 60);
var dursecs = Math.floor(vid.duration - durmins * 60);
if(cursecs < 10){ cursecs = "0"+cursecs; }
if(dursecs < 10){ dursecs = "0"+dursecs; }
if(curmins < 10){ curmins = "0"+curmins; }
if(durmins < 10){ durmins = "0"+durmins; }
curtimetext.innerHTML = curmins+":"+cursecs;
durtimetext.innerHTML = durmins+":"+dursecs;
}
// Mute Function
function vidmute(){
if(vid.muted){
vid.muted = false;
mutebtn.innerHTML = "Mute";
} else {
vid.muted = true;
mutebtn.innerHTML = "Unmute";
}
}
// Set Volume Function
function setvolume(){ vid.volume = volumeslider.value / 100; }
// Full Screen Function
function toggleFullScreen(){
if(vid.requestFullScreen){
vid.requestFullScreen();
} else if(vid.webkitRequestFullScreen){
vid.webkitRequestFullScreen();
} else if(vid.mozRequestFullScreen){ vid.mozRequestFullScreen();
}
}
// ------------Add event listeners-----------------------------------------
var i;
for (i = 0; i < playbtn.length; i++) {
playbtn[i].addEventListener("click",playPause,false);
}
for (i = 0; i < seekslider.length; i++) {
seekslider[i].addEventListener("change",vidSeek,false);
}
for (i = 0; i < vid.length; i++) {
vid[i].addEventListener("timeupdate",seektimeupdate,false);
}
for (i = 0; i < seekslider.length; i++) {
mutebtn[i].addEventListener("click",vidmute,false);
}
for (i = 0; i < vid.length; i++) {
volumeslider[i].addEventListener("change",setvolume,false);
}
for (i = 0; i < seekslider.length; i++) {
fullscreenbtn[i].addEventListener("click",toggleFullScreen,false);
}
}
The Original JS:
//----------------------------Video Player--------------------------------------
var vid, playbtn, seekslider, curtimetext, durtimetext, mutebtn, volumeslider, fullscreenbtn;
//--------Functions------------------------------
// Initialize Player
function intializePlayer(){
window.onload = intializePlayer;
// Play/Pause Function
function playPause(){
if(vid.paused){
vid.play();
playbtn.style.background = "url(pause.png)";
} else { vid.pause();
playbtn.style.background = "url(play.png)";
}
}
// Video Seek Function
function vidSeek(){
var seekto = vid.duration * (seekslider.value / 100);
vid.currentTime = seekto;
}
// Seektime Update
function seektimeupdate(){
var nt = vid.currentTime * (100 / vid.duration);
seekslider.value = nt;
var curmins = Math.floor(vid.currentTime / 60);
var cursecs = Math.floor(vid.currentTime - curmins * 60);
var durmins = Math.floor(vid.duration / 60);
var dursecs = Math.floor(vid.duration - durmins * 60);
if(cursecs < 10){ cursecs = "0"+cursecs; }
if(dursecs < 10){ dursecs = "0"+dursecs; }
if(curmins < 10){ curmins = "0"+curmins; }
if(durmins < 10){ durmins = "0"+durmins; }
curtimetext.innerHTML = curmins+":"+cursecs;
durtimetext.innerHTML = durmins+":"+dursecs;
}
// Mute Function
function vidmute(){
if(vid.muted){
vid.muted = false;
mutebtn.innerHTML = "Mute";
} else {
vid.muted = true;
mutebtn.innerHTML = "Unmute";
}
}
// Set Volume Function
function setvolume(){ vid.volume = volumeslider.value / 100; }
// Full Screen Function
function toggleFullScreen(){
if(vid.requestFullScreen){
vid.requestFullScreen();
} else if(vid.webkitRequestFullScreen){
vid.webkitRequestFullScreen();
} else if(vid.mozRequestFullScreen){ vid.mozRequestFullScreen();
}
}
//----------------Set object references-------------------------------------
vid = document.getElementsByClassName("my_video");
playbtn = document.getElementsByClassName("playpausebtn");
seekslider = document.getElementsByClassName("seekslider");
curtimetext = document.getElementsByClassName("curtimetext");
durtimetext = document.getElementsByClassName("durtimetext");
mutebtn = document.getElementsByClassName("mutebtn");
volumeslider = document.getElementsByClassName("volumeslider");
fullscreenbtn = document.getElementsByClassName("fullscreenbtn");
// ------------Add event listeners-----------------------------------------
playbtn.addEventListener("click",playPause,false);
seekslider.addEventListener("change",vidSeek,false);
vid.addEventListener("timeupdate",seektimeupdate,false);
mutebtn.addEventListener("click",vidmute,false);
volumeslider.addEventListener("change",setvolume,false);
fullscreenbtn.addEventListener("click",toggleFullScreen,false);
}
The HTML:
<div id="evid">
<video class="videogunshots" width="550" height="300">
<source src="file:///C|/Users/Godsnake/Desktop/July14/content/gunshots.mp4" type="video/mp4">
<source src="file:///C|/Users/Godsnake/Desktop/July14/content/gunshots.webm" type="video/webm">
<source src="file:///C|/Users/Godsnake/Desktop/July14/content/gunshots.ogg" type="video/ogg">
</video>
<div class="videocontrols">
<button class="playpausebtn" onclick="playPause()">Play</button>
<input class="seekslider" type="range" min="0" max="100" value="0" step="1">
<span class="curtimetext">00:00</span> / <span class="durtimetext">00:00</span>
<button class="mutebtn">Mute</button>
<input class="volumeslider" type="range" min="0" max="100" value="100" step="1">
<button class="fullscreenbtn">[ ]</button>
</div>
</div>
On a different note the video I"m playing doesnt seem to fit the container with Object-fit:fill any idea why?

document.getElementsByClassName returns a collection of elements rather than just a single element. In order to attach an event listener, you will need to loop through each one and attach individually.
Something like this:
var i;
for (i = 0; i < playbtn.length; i++) {
playbtn[i].addEventListener("click",playPause,false);
}
for (i = 0; i < seekslider.length; i++) {
seekslider[i].addEventListener("change",vidSeek,false);
}
...
Update:
I just took a look at your JSFiddle. You're calling local resources (things on your computer) that cannot be accessed on the web. The buttons, even the file itself, need to live on a server where they can be accessed. Until that happens, none of this will work.
One of the biggest things that helped me when I was learning was figuring out how to use the console in Chrome Developer Tools (Firefox has a good set of tools as well). Any errors will get spat out there.

Related

Range Slider not working in audio player ,JQuery,HTML

I have an mp3 player I built with jQuery ,in it Range slider not working in audio player. I tried the following code but it doesn't worked. I've tried lots of different code from different places but nothing seems to work. On Mozilla browser its working correctly but on chrome slider does not works. My latest attempt looks like this.
let previous = document.querySelector('#pre');
let play = document.querySelector('#play');
let next = document.querySelector('#next');
let title = document.querySelector('#title');
let recent_volume = document.querySelector('#volume');
let volume_show = document.querySelector('#volume_show');
let slider = document.querySelector('#duration_slider');
let show_duration = document.querySelector('#show_duration');
let track_image = document.querySelector('#track_image');
let auto_play = document.querySelector('#auto');
let present = document.querySelector('#present');
let total = document.querySelector('#total');
let artist = document.querySelector('#artist');
let timer;
let autoplay = 0;
let index_no = 0;
let Playing_song = false;
//create a audio Element
let track = document.createElement('audio');
//All songs list
let All_song = [{
name: "{{ $data->name }}",
path: "{{ asset('assets/' . $data->file) }}",
img: "/assets/images/quran.jpg",
singer: "{{ $data->description }}"
}
];
// All functions
// function load the track
function load_track(index_no) {
clearInterval(timer);
reset_slider();
track.src = All_song[index_no].path;
title.innerHTML = All_song[index_no].name;
track_image.src = All_song[index_no].img;
artist.innerHTML = All_song[index_no].singer;
track.load();
timer = setInterval(range_slider, 500); // update the range slider every 500 milliseconds
total.innerHTML = All_song.length;
present.innerHTML = index_no + 1;
}
load_track(index_no);
//mute sound function
function mute_sound() {
track.volume = 0;
volume.value = 0;
volume_show.innerHTML = 0;
}
// checking.. the song is playing or not
function justplay() {
if (Playing_song == false) {
playsong();
} else {
pausesong();
}
}
// reset song slider
function reset_slider() {
slider.value = 0;
}
// play song
function playsong() {
track.play();
Playing_song = true;
play.innerHTML = '<i class="fa fa-pause" aria-hidden="true"></i>';
}
//pause song
function pausesong() {
track.pause();
Playing_song = false;
play.innerHTML = '<i class="fa fa-play" aria-hidden="true"></i>';
}
// next song
function next_song() {
if (index_no < All_song.length - 1) {
index_no += 1;
load_track(index_no);
playsong();
} else {
index_no = 0;
load_track(index_no);
playsong();
}
}
// previous song
function previous_song() {
if (index_no > 0) {
index_no -= 1;
load_track(index_no);
playsong();
} else {
index_no = All_song.length;
load_track(index_no);
playsong();
}
}
// change volume
function volume_change() {
volume_show.innerHTML = recent_volume.value;
track.volume = recent_volume.value / 100;
}
// change slider position
function change_duration() {
slider_position = track.duration * (slider.value / 100);
track.currentTime = slider_position;
setInterval(range_slider, 1000); // update the range slider every 1000 milliseconds (1 second)
}
// autoplay function
function autoplay_switch() {
if (autoplay == 1) {
autoplay = 0;
auto_play.style.background = "rgba(255,255,255,0.2)";
} else {
autoplay = 1;
auto_play.style.background = "#FF8A65";
}
}
function range_slider() {
let current_time = Math.floor(track.currentTime); // get the current time of the audio in seconds
let duration = Math.floor(track.duration); // get the total duration of the audio in seconds
let minutes = Math.floor(current_time / 60); // calculate the minutes for the current time
let seconds = current_time % 60; // calculate the seconds for the current time
let total_minutes = Math.floor(duration / 60); // calculate the minutes for the total duration
let total_seconds = duration % 60; // calculate the seconds for the total duration
// display the current time and total duration in the format "mm:ss"
show_duration.innerHTML = `${minutes}:${seconds} / ${total_minutes}:${total_seconds}`;
// update the range slider to reflect the current time
slider.value = (current_time / duration) * 100;
}
HTML
<div class="duration">
<input type="range" min="0" max="100" value="0"
id="duration_slider"
onchange="change_duration()">
</div>
I've removed the unnecessary variables minutes, seconds, total_minutes, and total_seconds by combining the calculation and assignment into one line.
function range_slider() {
let current_time = Math.floor(track.currentTime);
let duration = Math.floor(track.duration);
show_duration.innerHTML = `${Math.floor(current_time / 60)}:${current_time % 60} / ${Math.floor(duration / 60)}:${duration % 60}`;
slider.value = (current_time / duration) * 100;
}

How can i play multiple audio file gotten from a database without using same audio id

I got this code here on stack overflow which is a custom audio player. But then modified the code to fetch audio from my database. The problem am having is only the first song gotten from my database is been played.
This is my code that displays the audio with the controls
<?php
require '../db.php';
$sql = "select * from songs order by song_id asc";
$sql_query = mysqli_query($con,$sql);
$i=0;
while ($row = mysqli_fetch_array($sql_query)) {
$image = $row['song_image'];
$song_name = $row['song_name'];
$audio = $row['song_audio'];
?>
<audio controls="controls" class='podcast-audio hide' id="player">
<source src="../Admin/Song/songAudio/<?php if(isset($audio)){ echo $audio;}?>" type="audio/mpeg"
/>
</audio>
<div id="audio-player">
<div id="controls">
<i id="play" class="fa fa-play cursor-pointer"></i>
<span id="time" class="time">00:00</span>
<div id="progressbar" class='cursor-pointer ui-progressbar'></div>
<span id="end-time" class="time">00:00</span>
<i id="mute" class="fa fa-volume-up cursor-pointer"></i>
<div id="volume" class='cursor-pointer ui-progressbar'></div>
</div>
</div>
<?php
$i++;
}
?>
This is my javascript code responsible for playing the audio
$(document).ready(function() {
var audio_player = $("#audio-player");
var play_button = $('#play');
var progress_bar = $("#progressbar");
var time = $("#time");
var mute_button = $('#mute');
var volume_bar = $('#volume');
var more_info = $('#more-info-box');
var player = $('#player')[0];
var duration = 0;
var volume = 0.5;
var end_time = $('#end-time');
player.onloadedmetadata = function () {
duration = player.duration;
var minutes = parseInt(duration / 60, 10);
var seconds = parseInt(duration % 60);
// finding and appending full duration of audio
end_time.text(minutes + ':' + seconds);
console.log('ddd', progress_bar)
progress_bar.progressbar("option", { 'max': duration });
};
player.load();
player.volume = 0.5;
player.addEventListener("timeupdate", function () {
progress_bar.progressbar('value', player.currentTime);
time.text(getTime(player.currentTime));
}, false);
volume_bar.progressbar({
value: player.volume * 100,
});
volume_bar.click(function (e) {
var info = getProgressBarClickInfo($(this), e);
volume_bar.progressbar('value', info.value);
player.volume = info.value / info.max;
});
progress_bar.progressbar({
value: player.currentTime,
});
progress_bar.click(function (e) {
var info = getProgressBarClickInfo($(this), e);
player.currentTime = player.duration / info.max * info.value;
});
play_button.click(function () {
player[player.paused ? 'play' : 'pause']();
$(this).toggleClass("fa-play", player.paused);
$(this).toggleClass("fa-pause", !player.paused);
});
mute_button.click(function () {
if (player.volume == 0) {
player.volume = volume;
} else {
volume = player.volume;
player.volume = 0;
}
volume_bar.progressbar('value', player.volume * 100);
$(this).toggleClass("fa-volume-up", player.volume != 0);
$(this).toggleClass("fa-volume-off", player.volume == 0);
});
more_info.click(function () {
audio_player.animate({
height: (audio_player.height() == 50) ? 100 : 50
}, 1000);
});
});
function getTime(t) {
var m = ~~(t / 60), s = ~~(t % 60);
return (m < 10 ? "0" + m : m) + ':' + (s < 10 ? "0" + s : s);
}
function getProgressBarClickInfo(progress_bar, e) {
var offset = progress_bar.offset();
var x = e.pageX - offset.left; // or e.offsetX (less support, though)
var y = e.pageY - offset.top; // or e.offsetY
var max = progress_bar.progressbar("option", "max");
var value = (x * max) / progress_bar.width();
return { x: x, y: y, max: max, value: value };
}
It looks like you're using the same javascript/HTML ID on each of the play, pause buttons.
Eg. if you're returning 3 songs, then the id within Javascript will be appearing 3 times...
<audio ... id="player">
<audio ... id="player">
<audio ... id="player">
So, as an ID on a page can only be created once, when your javascript function goes to find the song, it finds the first ID, gets it's the source and plays it.
I'd suggest that you either:
I can see you're using a counter. Change the ID of each player id to be player1, player2, etc and refer to that, OR
Get your player code to search by class instead of by id. Eg.
var player = $('.podcast-audio')[0][0];

Timer doesn't start running

I tried to make a normal Timer in Javascript and started coding something with help of some Tutorials.
I did it the same way as in the tutorial but my timer actually doesn't start running, and i don't know why.
Here is my Code:
var time = 0;
var running = 0;
function startPause() {
if(running == 0){
running = 1;
increment();
}
else{
running = 0;
}
}
function reset(){
running = 0;
time = 0;
document.getElementById("startPause").innerHTML = "Start";
}
function increment() {
if(running == 1){
setTimeout(function(){
time++;
var mins = Math.floor(time / 10 / 60);
var secs = Math.floor(time / 10);
var tenths = time % 10;
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + tenths;
}, 100);
}
}
</script>
i also made a fiddle you can check out here: https://jsfiddle.net/adamswebspace/5p1qgsz9/
what is wrong with my code?
I cleared a bit your code, and used setInterval instead of setTimeOut;
note that you have to use clearInterval in order to stop the timer
var time = 0;
var running = 0;
var timer = null;
function increment() {
time++;
var mins = Math.floor(time / 10 / 60);
var secs = Math.floor(time / 10);
var tenths = time % 10;
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + tenths;
}
function startPause() {
if (running === 0) {
running = 1;
timer = setInterval(increment, 1000);
} else {
running = 0;
clearInterval(timer);
}
}
function reset() {
running = 0;
time = 0;
document.getElementById("startPause").innerHTML = "Start";
}
you have to bind the function like the following
var vm = this;
vm.startPause = function startPause() {
if (running == 0) {
running = 1;
vm.increment();
} else {
running = 0;
}
}
https://jsfiddle.net/f7hmbox7/
In order for onclick to find the function in your code. It must be supplied in a <script> tag for JSFiddle.
You can just add
<script>
/** JS Here */
</script>
and it will work.
Keep in mind that all the errors coming from JS are showed in the console of your browser inspector.
https://jsfiddle.net/dzskncpw/

how to create a timer on a video with JavaScript?

I wrote the code like this, and the play button works but the timer does not.
<input type="button" id="play" onclick="videoplay();" value=">"/>
....
<span id="timer">0%</span>
....
function videoplay() {
var video = document.getElementById("video");
var button = document.getElementById("play");
if (video.paused) {
video.play();
button.value = "||";
var timer = getElementbyId("timer");
var update = setInterval(function () {
timer.textContent = Math.round(video.currentTime / video.duration * 100) + "%";
}, 500);
} else {
video.pause();
button.value = ">";
if (update)
clearInterval(update);
}
}
timer.innerText = Math.round(video.currentTime / video.duration * 100) + "%";

Adding start, stop, and reset buttons for a timer

I'm making a timer and have it working already one load. I want to add a start, stop, and reset button to it. This is my code as is atm.
(function() {
"use strict";
var secondsLabel = document.getElementById('seconds'),
minutesLabel = document.getElementById('minutes'),
hoursLabel = document.getElementById('hours'),
totalSeconds = 0,
startButton = document.getElementById('start'),
resetButton = document.getElementById('reset'),
onOff = 0;
startButton.onclick = function() {
onOff = 1;
};
resetButton.onclick = function() {
totalSeconds = 0;
onOff = 0;
};
if ( onOff == 1 ) {
setInterval( setTime, 1000 );
function setTime() {
totalSeconds++;
secondsLabel.innerHTML = pad( totalSeconds % 60 );
minutesLabel.innerHTML = pad( parseInt( totalSeconds / 60 ) );
hoursLabel.innerHTML = pad( parseInt( totalSeconds / 3600 ) )
}
function pad( val ) {
var valString = val + "";
if( valString.length < 2 ) {
return "0" + valString;
} else {
return valString;
}
}
}
})();
The buttons are not working atm however. I'm not sure if this the best solution for the goal as well, so suggestions are welcome.
(function() {
"use strict";
var secondsLabel = document.getElementById('seconds'), minutesLabel = document.getElementById('minutes'), hoursLabel = document
.getElementById('hours'), totalSeconds = 0, startButton = document.getElementById('start'), stopButton = document.getElementById('stop'), resetButton = document
.getElementById('reset'), timer = null;
startButton.onclick = function() {
if (!timer) {
timer = setInterval(setTime, 1000);
}
};
stopButton.onclick = function() {
if (timer) {
clearInterval(timer);
timer = null;
}
};
resetButton.onclick = function() {
if (timer) {
totalSeconds = 0;
stop();
}
};
function setTime() {
totalSeconds++;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
hoursLabel.innerHTML = pad(parseInt(totalSeconds / 3600))
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
})();
<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;
function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}
function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>
<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()" />
<input type="text" id="txt" />
<input type="button" value="Stop count!" onclick="stopCount()" />
</form>
<p>
Click on the "Start count!" button above to start the timer. The input field will count forever, starting at 0. Click on the "Stop count!" button to stop the counting. Click on the "Start count!" button to start the timer again.
</p>
</body>
</html>

Categories