javascript code written in separate to the html markup - javascript

what's wrong with this code, i have included the file but when i run it doesn't give the result i intended(customized design of video player),any one who is aware about javascript can help.......
function dofirst() {
//get values of buttons
var movie = document.getElementById("movie");
var playOrpause = document.getElementById("playOrpause");
var mute = document.getElementById("mute");
var fullscreen = document.getElementById("fullscreen");
//get values of sliders
var seekbar = document.getElementById("seekbar");
var myvolume = document.getElementById("volume");
//add the event listeners to buttons
playOrpause.addEventListener('click', playme, false);
mute.addEventListener('click', mute_me, false);
fullscreen.addEventListener('click', scree_full, false);
//add the event listener to sliders
seekbar.addEventListener('change', change_me, false);
seekbar.addEventListener('timeupdate', update_me, false);
seekbar.addEventListener('mousedown', mous_down, false);
seekbar.addEventListener('mouseup', mous_up, false);
myvolume.addEventListener('change', volume_up, false);
}
//the functions of play button
function playme() {
if (movie.paused == true) {
movie.play();
//update button status
playOrpause.innerHTML = 'pause';
else {
movie.pause();
//update button status
playOrpause.innerHTML = 'play';
}
}
}
//the functions of mute button
function mute_me() {
if (movie.muted == false) {
movie.muted = true;
//update button status
mute.innerHTML = 'unmute';
} else {
movie.muted = false;
//update button status
mute.innerHTML = 'mute';
}
}
//the functions of fullscreen button
function scree_full() {
if (movie.requestFullscreen) {
movie.requestFullscreen();
}
//for mozilla firefox browser
else if (movie.mozRequestFullscreen) {
movie.mozRequestFullscreen();
}
//for google chrome browsers
else if (movie.webkitRequestFullscreen) {
movie.webkitRequestFullscreen();
}
}
//the functions for seekbar
function change_me() {
//calculate current time of the video
var time = movie.duration * (seekbar.value / 100);
//update the current time of the video
movie.currentTime = time;
}
//update the seekbar when the video plays
function update_me() {
var size = movie.currentTime * (100 / movie.duration);
//update the size of the seekbar
seekbar.value = size;
}
//pause the video when the seekbar is dragged
function mous_down() {
movie.pause();
}
//play the video when the seekbar is dropped
function mous_up() {
movie.play();
}
//the function for the volume bar
function volume_up() {
movie.volume = myvolume.value;
}
window.addEventListener("load", dofirst, false);

Make sure that there are no syntax errors in your code....For instance, you seem to be using 'mous_up()' instead of 'mouse_up()'. From my own experience, javascript code doesn't run when there are any syntax errors.

Related

Plain javascript audio player not working on mobile phone

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

TypeError: player.bind is not a function - jQuery

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...

Shuffle song when it ends - javascript html5

I have this code that randomizes and play a song from a list of them:
var sounds = [
"sounds/royksopp.mp3",
"sounds/9thwonder.mp3",
"sounds/thisbeat.mp3",
"sounds/mosdef.mp3",
"sounds/bewater.mp3",
"sounds/boutdre.mp3",
"sounds/masterflash.mp3",
"sounds/2ep.mp3",
"sounds/drewestcoast.mp3",
"sounds/poetry.mp3",
"sounds/mfdoom.mp3",
"sounds/dreams.mp3",
"sounds/oizo.mp3", ];
function StartOrStop(audioFile) {
srcAudio = sounds[Math.floor(Math.random() * sounds.length)];
var audie = document.getElementById("myAudio");
audie.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
if (audie.paused == false) {
audie.pause();
} else {
audie.src = srcAudio;
audie.play();
}
}
When the song stops playing, it restarts with th same one. How can I make it so when the music ends, it will grab a new song from my list and automatically play it?
The problem is that you are simply calling this.play() in your ended event listener. Instead, you should be updating the src attribute with the random choice of song with this.src = srcAudio, similar to how you are for the initial selection:
function StartOrStop(audioFile) {
srcAudio = sounds[Math.floor(Math.random() * sounds.length)];
var audie = document.getElementById("myAudio");
audie.addEventListener('ended', function() {
this.currentTime = 0;
this.src = srcAudio;
this.play();
}, false);
if (audie.paused == false) {
audie.pause();
} else {
audie.src = srcAudio;
audie.play();
}
}
Hope this helps! :)

While mousedown JS

I'm trying to run a function while mousedown but for the life of me I can't get it to work while holding down but everything works by just clicking. I'm trying to change color of countries on a map as I hold down.
Here's my code:
var int;
var mouseStillDown = false;
function mousedown(geography)
{ console.log('mousedown '+mousedownID);
mouseStillDown = true;
int = setInterval( performWhileMouseDown(geography), 100);
}
function mouseup()
{
clearInterval(int);
mouseStillDown = false;
}
function mouseout()
{
clearInterval(int);
}
function performWhileMouseDown(geography)
{
if (!mouseStillDown)
{console.log('error');}
if (mouseStillDown) {
if(data[geography.id])
{
data[geography.id] ++;
}else
{
data[geography.id] = 1;
}
var m = {};
m[geography.id] = color(data[geography.id]);
map.updateChoropleth(m);
}
/* if (mouseStillDown)
{ setInterval(performWhileMouseDown(geography), 100); }*/
}
You could try to use mousemove instead, mousedown will only fire once.
var mouseDown = false;
window.addEventListener('mousedown', function() { mouseDown = true })
window.addEventListener('mouseup', function() { mouseDown = false })
window.addEventListener('mousemove', function() {
if (!mouseDown) {
return;
}
// perform while mouse is moving
})
here's what worked for me
var timeout ;
function mouseDown(geography){
timeout = setInterval( function(){
if(data[geography.id]){
data[geography.id] ++;
}else{
data[geography.id] = 1;
}
var m = {};
m[geography.id] = color(data[geography.id]);
map.updateChoropleth(m);}, 100);
return false;
}
function mouseUp(geography){
clearInterval(timeout);
return false;
}
The two conditions for your event are that the code executes every time there is an update in mouse position AND the mouse button is pressed.
Addressing the first part can be done with the 'mousemove' event, which fires when the mouse is moved over the element.
The second filter can be solved, by checking the mouse event, on if the button is pressed. If not, we don't execute the following code.
window.addEventListener('mousemove', function() { // Attach listener
if (event.buttons == 0) // Check event for button
return; // Button not pressed, exit
// perform while mouse is moving
})

Why event is triggered more than once?

I'm trying to add an event handler for an audio Javascript plugin using the SoundManager2. This is the function that plays a song and wait for the end of the song to execute the function again:
function songPlay (newSrc) {
htmlSound.src = newSrc;
htmlSound.load();
thisPlayer.find( ".total-position-scrubber" ).bind( "slide", function(event, ui) {
htmlSound.currentTime = ui.value;
});
var currentArtist = currentRow.find(".total-artist").text();
var currentTitle = currentRow.find(".total-title").text();
thisPlayer.find(".total-playing-artist").html(currentArtist);
thisPlayer.find(".total-playing-title").html(currentTitle);
htmlSound.addEventListener("timeupdate", function() {
var newVolume = thisPlayer.find( ".total-volume-slider" ).slider("option", "value");
htmlSound.volume = newVolume;
var duration = htmlSound.duration * 1000;
var durationTime = convertMilliseconds(duration, "mm:ss");
thisPlayer.find(".total-song-duration").html(durationTime.clock );
var position = htmlSound.currentTime * 1000;
var positionTime = convertMilliseconds(position, "mm:ss");
thisPlayer.find(".total-song-position").html(positionTime.clock );
thisPlayer.find( ".total-position-scrubber" ).slider("option", "max", duration/1000);
thisPlayer.find( ".total-position-scrubber" ).slider("option", "value", position/1000);
});
htmlSound.addEventListener("ended", function() {
// Find next checked song
currentRow = currentRow.nextAll(".can-play:first");
// If checked song exists after current song, load it
if(currentRow.length > 0)
{
var newSrc = currentRow.find("[src]").attr("src");
songPlay(newSrc);
}
else
{
// If no checked song exists after current song, load the first checked song in playlist
if(thisPlayer.find(".can-play").length > 0)
{
currentRow = thisPlayer.find(".can-play:first");
var newSrc = currentRow.find("[src]").attr("src");
songPlay(newSrc);
}
// Change pause button to play button
else
{
thisPlayer.find(".total-play").removeClass("total-pause");
}
}
// If song is playing while next button is clicked play next song
if(thisPlayer.find(".total-pause").length > 0)
{
htmlSound.play();
}
});
thisPlayer.find(".total-row .total-not-playing").removeClass("total-playing");
currentRow.find(".total-not-playing").addClass("total-playing");
}
The only problem is that the "ended" event is triggered more than once every time that a song finishes. After the "ended" event, the function is executed, and then the songPlay() function is executed again (this is the expected behavior), but then, the "ended" event is triggered again, before the song is finished, while it should wait for the end of the song. Any idea of the cause of that behavior?
The newSrc variable has always the right value.
This is the "ended" event definition in SoundManager2:
_html5_events = {
// HTML5 event-name-to-handler map
...
ended: _html5_event(function() {
var t = this._t;
_s._wD(_h5+'ended: '+t.sID);
t._onfinish();
}),
...
}
Edit:
Surprisingly, it worked just replacing the anonymous function with a declared function like this:
function eventListenerFunction() {
// Find next checked song
currentRow = currentRow.nextAll(".can-play:first");
// If checked song exists after current song, load it
if(currentRow.length > 0)
{
var newSrc = currentRow.find("[src]").attr("src");
songPlay(newSrc);
}
else
{
// If no checked song exists after current song, load the first checked song in playlist
if(thisPlayer.find(".can-play").length > 0)
{
currentRow = thisPlayer.find(".can-play:first");
var newSrc = currentRow.find("[src]").attr("src");
songPlay(newSrc);
}
// Change pause button to play button
else
{
thisPlayer.find(".total-play").removeClass("total-pause");
}
}
// If song is playing while next button is clicked play next song
if(thisPlayer.find(".total-pause").length > 0)
{
htmlSound.play();
}
});
function songPlay (newSrc) {
htmlSound.src = newSrc;
htmlSound.load();
thisPlayer.find( ".total-position-scrubber" ).bind( "slide", function(event, ui) {
htmlSound.currentTime = ui.value;
});
var currentArtist = currentRow.find(".total-artist").text();
var currentTitle = currentRow.find(".total-title").text();
thisPlayer.find(".total-playing-artist").html(currentArtist);
thisPlayer.find(".total-playing-title").html(currentTitle);
htmlSound.addEventListener("timeupdate", function() {
var newVolume = thisPlayer.find( ".total-volume-slider" ).slider("option", "value");
htmlSound.volume = newVolume;
var duration = htmlSound.duration * 1000;
var durationTime = convertMilliseconds(duration, "mm:ss");
thisPlayer.find(".total-song-duration").html(durationTime.clock );
var position = htmlSound.currentTime * 1000;
var positionTime = convertMilliseconds(position, "mm:ss");
thisPlayer.find(".total-song-position").html(positionTime.clock );
thisPlayer.find( ".total-position-scrubber" ).slider("option", "max", duration/1000);
thisPlayer.find( ".total-position-scrubber" ).slider("option", "value", position/1000);
});
htmlSound.addEventListener("ended", eventListenerFunction)
thisPlayer.find(".total-row .total-not-playing").removeClass("total-playing");
currentRow.find(".total-not-playing").addClass("total-playing");
}
However, I guess I should use $('body').off("ended") after the triggered function to remove the event listener, as #Fallenreaper has suggested.
you call songplay inside of a listener, which applies it another time.... and another time and another time.
recursion.
>_>

Categories