My video player isn't working, it doesn't play when I click on the play button. I am testing it on chrome browser.
This is my code (I think the problem is in the JS part):
function dofirst() {
barSize = 500;
video = document.getElementById('video');
playbutton = document.getElementById('playbutton');
defaultBar = document.getElementById('defaultBar');
progressbar = document.getElementById('progressbar');
playbutton.addEventListener(click, PlayOrPause ,false);
defaultBar.addEventListener(click, clickedBar ,false);
}
function PlayOrPause() {
If( !video.paused && !video.ended){
video.pause();
playbutton.innerHTML = 'play';
window.clearInterval(updatebar);
} else {
video.play();
playbutton.innerHTML = 'pause';
updatebar = setInterval(update,500);
}
}
function update(){
if(!video.ended){
var size= parseInt(video.currentTime*barsize/video.duration);
progressbar.style.width = size +'px';
} else {
progressbar.style.width ='0px';
playbutton.innerHTML = 'play';
window.clearInterval(updatebar);
}
}
function clickedBar(e) {
If( !video.paused && !video.ended){
var mouseX = e.pageX-bar.offsetLeft;
var newtiem = mouseX*video.duration/barSize;
myMovie.currentTime = newtime;
progressbar.style.width = mouseX+'px';
}
}
window.addEventListener('load',dofirst,false);
body {
text-align: center;
}
#skin {
background: #5C6366;
width: 700px;
margin: 10px auto;
padding: 50px;
border: 2px black auto;
border-radius: 30px;
}
nav {
margin: 2px 0px;
}
#buttons {
float: left;
width: 70px;
height: 20px;
margin-left: 20px;/* 90px total 610 remaining*/
}
#defaultBar {
margin-top: 5px;
position: relative;
width: 500px;
float : left;
height: 5px;
background-color: black;
}
#progressbar {
position: absolute;
width: 0px;
height: 5px;
background-color: white;
}
<section id="skin" >
<video width=640px height=360px id="video" >
<source src="e:\dc\SampleVideo_1080x720_5mb.mp4" type="video/mp4"/>
</video>
<nav>
<div id="buttons">
<button type="button" id="playbutton">play</button>
</div>
<div id="defaultBar">
<div id="progressbar"></div>
</div>
<div style="clear:both" ></div>
</nav>
</section>
What is wrong? What do I need to fix to make it work?
There are two errors that make this not work:
JavaScript is a case sensitive language, and you are not using the right syntax for the keyword if (you wrote If in two different places):
if( !video.paused && !video.ended){
The same way that you are adding the event name between quotes in the addEventListener for the load event, you need to do the same for the click event:
playbutton.addEventListener("click", PlayOrPause ,false);
defaultBar.addEventListener("click", clickedBar ,false);
Once you fix those two things, it will work. Here is the code with the corrections:
function dofirst() {
barSize = 500;
video = document.getElementById('video');
playbutton = document.getElementById('playbutton');
defaultBar = document.getElementById('defaultBar');
progressbar = document.getElementById('progressbar');
playbutton.addEventListener("click", PlayOrPause ,false);
defaultBar.addEventListener("click", clickedBar ,false);
}
function PlayOrPause() {
if( !video.paused && !video.ended){
video.pause();
playbutton.innerHTML = 'play';
window.clearInterval(updatebar);
} else {
video.play();
playbutton.innerHTML = 'pause';
updatebar = setInterval(update,500);
}
}
function update(){
if(!video.ended){
var size= parseInt(video.currentTime*barsize/video.duration);
progressbar.style.width = size +'px';
} else {
progressbar.style.width ='0px';
playbutton.innerHTML = 'play';
window.clearInterval(updatebar);
}
}
function clickedBar(e) {
if( !video.paused && !video.ended){
var mouseX = e.pageX-bar.offsetLeft;
var newtiem = mouseX*video.duration/barSize;
myMovie.currentTime = newtime;
progressbar.style.width = mouseX+'px';
}
}
window.addEventListener('load',dofirst,false);
body {
text-align: center;
}
#skin {
background: #5C6366;
width: 700px;
margin: 10px auto;
padding: 50px;
border: 2px black auto;
border-radius: 30px;
}
nav {
margin: 2px 0px;
}
#buttons {
float: left;
width: 70px;
height: 20px;
margin-left: 20px;/* 90px total 610 remaining*/
}
#defaultBar {
margin-top: 5px;
position: relative;
width: 500px;
float : left;
height: 5px;
background-color: black;
}
#progressbar {
position: absolute;
width: 0px;
height: 5px;
background-color: white;
}
<section id="skin" >
<video width=640px height=360px id="video" >
<source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4"/>
</video>
<nav>
<div id="buttons">
<button type="button" id="playbutton">play</button>
</div>
<div id="defaultBar">
<div id="progressbar"></div>
</div>
<div style="clear:both" ></div>
</nav>
</section>
Note: I updated the video path to one that was actually available online to show that the video works after the changes specified above.
Related
I am working on a static portfolio site and have styled some Javascript audio players.
The site is live here with the first audio player working almost exactly as desired (except the progress bar displays at the top of the div, I'd like it at the bottom). A photo is attached of the desired visual outcome.
I need five total audio players. How can I achieve this?
Current Javascript:
const audioPlayer = document.querySelector(".audio-player");
const audio = new Audio(
"https://jsomerset.uk/images/victory.mp3"
);
console.dir(audio);
audio.addEventListener(
"loadeddata",
() => {
audioPlayer.querySelector(".time .length").textContent = getTimeCodeFromNum(
audio.duration
);
audio.volume = .75;
},
false
);
const timeline = audioPlayer.querySelector(".timeline");
timeline.addEventListener("click", e => {
const timelineWidth = window.getComputedStyle(timeline).width;
const timeToSeek = e.offsetX / parseInt(timelineWidth) * audio.duration;
audio.currentTime = timeToSeek;
}, false);
setInterval(() => {
const progressBar = audioPlayer.querySelector(".progress");
progressBar.style.width = audio.currentTime / audio.duration * 100 + "%";
audioPlayer.querySelector(".time .current").textContent = getTimeCodeFromNum(
audio.currentTime
);
}, 500);
const playBtn = audioPlayer.querySelector(".controls .toggle-play");
playBtn.addEventListener(
"click",
() => {
if (audio.paused) {
playBtn.classList.remove("play");
playBtn.classList.add("pause");
audio.play();
} else {
playBtn.classList.remove("pause");
playBtn.classList.add("play");
audio.pause();
}
},
false
);
You code can't run properly, since you're selecting non existent elements.
Check you dev tools console for errors.
E.g. you're trying to display the current time in an element with the class time – but yout html does not contain such an element.
Besides, you haven't defined the method getTimeCodeFromNum().
See the cleaned up code – not usable blocks are commented out :
const audioPlayer = document
.querySelectorAll(".audio-player")
.forEach((audioPlayer) => {
const audio = new Audio(audioPlayer.dataset.src);
//console.dir(audio);
/*
audio.addEventListener(
"loadeddata",
() => {
audioPlayer.querySelector(
".time .length"
).textContent = getTimeCodeFromNum(audio.duration);
audio.volume = 0.75;
},
false
);
*/
const timeline = audioPlayer.querySelector(".timeline");
timeline.addEventListener(
"click",
(e) => {
const timelineWidth = window.getComputedStyle(timeline).width;
const timeToSeek =
(e.offsetX / parseInt(timelineWidth)) * audio.duration;
audio.currentTime = timeToSeek;
},
false
);
setInterval(() => {
const progressBar = audioPlayer.querySelector(".progress");
progressBar.style.width =
(audio.currentTime / audio.duration) * 100 + "%";
/*
audioPlayer.querySelector(
".time .current"
).textContent = getTimeCodeFromNum(audio.currentTime);
*/
}, 500);
const playBtn = audioPlayer.querySelector(".controls .toggle-play");
playBtn.addEventListener(
"click",
() => {
if (audio.paused) {
playBtn.classList.remove("play");
playBtn.classList.add("pause");
audio.play();
} else {
playBtn.classList.remove("pause");
playBtn.classList.add("play");
audio.pause();
}
},
false
);
/*
audioPlayer
.querySelector(".volume-button")
.addEventListener("click", () => {
const volumeEl = audioPlayer.querySelector(".volume-container .volume");
audio.muted = !audio.muted;
if (audio.muted) {
volumeEl.classList.remove("icono-volumeMedium");
volumeEl.classList.add("icono-volumeMute");
} else {
volumeEl.classList.add("icono-volumeMedium");
volumeEl.classList.remove("icono-volumeMute");
}
});
*/
});
body {
background: #000
}
.audio-player {
display: grid;
grid-template-rows: 6px auto;
overflow: hidden;
height: 200px;
width: 100vw;
color: #efefef;
}
.timeline {
background: none;
width: 100%;
position: relative;
cursor: pointer;
height: 5px;
}
.progress {
background: #efefef;
width: 0%;
height: 5px;
transition: 0.25s;
-webkit-transition: 0.25s;
}
.controls {
display: flex;
align-items: center;
justify-content: center;
width: 100px;
}
.controls * {
display: flex;
justify-content: center;
align-items: center;
}
.play {
cursor: pointer;
position: relative;
left: 0;
height: 0;
width: 0;
border: 7px solid #0000;
border-left: 13px solid white;
}
.pause {
height: 15px;
width: 20px;
cursor: pointer;
position: absolute;
margin-left: 15px;
}
.pause:before {
position: absolute;
top: 0;
left: 0px;
background: white;
content: "";
height: 15px;
width: 3px;
}
.pause:after {
position: absolute;
top: 0;
right: 9px;
background: white;
content: "";
height: 15px;
width: 3px;
}
<div class="audio-player a-one font" data-src="https://jsomerset.uk/images/swain.mp3">
<div class="timeline">
<div class="progress" style="width: 0%;"></div>
</div>
<div class="name">Action</div>
<div class="controls">
<div class="play-container">
<div class="toggle-play play">
</div>
</div>
</div>
</div>
<div class="audio-player a-two font" data-src="https://jsomerset.uk/images/victory.mp3">
<div class="timeline">
<div class="progress"></div>
</div>
<div class="name">Victory Song</div>
<div class="controls">
<div class="play-container">
<div class="toggle-play play">
</div>
</div>
</div>
</div>
Use document.querySelectorAll, then loop over the selection. You can store the mp3 URL for each div inside a data-src attribute:
<div class="audio-player" data-src="https://jsomerset.uk/images/victory.mp3">...</div>
<div class="audio-player" data-src="https://jsomerset.uk/images/anotherFile.mp3">...</div>
<div class="audio-player" data-src="https://jsomerset.uk/images/etc.mp3">...</div>
document.querySelectorAll(".audio-player").forEach(audioPlayer => {
const audio = new Audio(audioPlayer.dataset.src);
// rest of your code
});
I´m trying to do a test extension for chrome for a university project but I can´t find a way to make the background or body of the extension´s html completely invisible, just for a clean interface. The problems I´m having are those white corners on the background.
This is the code of the extension:
// Define variables
let audio, playbtn, title, poster, artists, mutebtn, seekslider, volumeslider,
seeking = false, seekto, curtimetext, durtimetext, playlist_status, dir, playlist,
ext, agent, playlist_artist, repeat, randomSong;
// Initialization of YouTube Api
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var id = '5_385OOZlIg';
var url = 'https://www.youtube.com/watch?v=' + id;
// Initialization of Array of Music, Tittle, Poster Image, Artists
dir = "music/";
playlist = ["Cartoon-On-_-On","Elektronomia","Johnning","Popsicle","Fearless"];
title = ["Cartoon - On & On","Elektronomia","Janji-Heroes Tonight","Popsicle","Lost Sky - Fearless"];
artists = ["(feat. Daniel Levi) [NSC Release]","Elektronomia - Sky High [NCS Release]","(feat. Johnning) [NCS Release]",
"LFZ - [NCS Release]","(feat. Chris Linton)[NCS Release]"];
poster = ["images/ncs1.jpeg","images/ncs2.jpg","images/ncs3.jpg","images/ncs4.jpg","images/ncs5.jpg"];
// Used to run on every browser
ext = ".mp3";
agent = navigator.userAgent.toLowerCase();
if(agent.indexOf('firefox') != -1 || agent.indexOf('opera') != -1){
ext = ".ogg";
}
// Set object references
playbtn = document.getElementById("playpausebtn");
nextbtn = document.getElementById("nextbtn");
prevbtn = document.getElementById("prevbtn");
mutebtn = document.getElementById("mutebtn");
visibilitybtn = document.getElementById("visibility");
seekslider = document.getElementById("seekslider");
volumeslider = document.getElementById("volumeslider");
curtimetext = document.getElementById("curtimetext");
durtimetext = document.getElementById("durtimetext");
playlist_status = document.getElementById("playlist_status");
playlist_artist = document.getElementById("playlist_artist");
repeat = document.getElementById("repeat");
randomSong = document.getElementById("random");
playlist_index = 0;
// Audio Object
audio = new Audio();
audio.src = dir + playlist[0] + ext; // music/musicname.mp3
audio.loop = false;
// First song title and artist
playlist_status.innerHTML = title[playlist_index];
playlist_artist.innerHTML = artists[playlist_index];
// Add event handling
playbtn.addEventListener("click", playPause);
nextbtn.addEventListener("click", nextSong);
prevbtn.addEventListener("click", prevSong);
mutebtn.addEventListener("click", mute);
visibilitybtn.addEventListener("click", toggle);
seekslider.addEventListener("mousedown", function(event){seeking = true; seek(event);});
seekslider.addEventListener("mousemove", function(event){seek(event);});
seekslider.addEventListener("mouseup", function(){seeking = false;});
volumeslider.addEventListener("mousemove", setvolume);
audio.addEventListener("timeupdate", function(){seektimeupdate();});
audio.addEventListener("ended",function(){switchTrack();});
repeat.addEventListener("click", loop);
randomSong.addEventListener("click", random);
// Functions
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '315',
width: '560',
videoId: id,
playerVars: {'autoplay': 0, 'controls': 0, 'loop': 1},
events: {
'onStateChange': onPlayerStateChange
}
});
}
/*
function onPlayerReady(event) {
let pgd = player.getDuration();
let vpb = document.getElementById("video_progress_bar");
vpb.setAttribute("max",pgd);
}*/
//Intento de que la barra de progreso avance con forme al video onPlayerStateChange(event) y onPlay()
var testThread;
function onPlayerStateChange(event) {
if(event.data == 1)
{
testThread = setInterval(seektimeupdate,500);
}else{
clearInterval(testThread);
}
}
// Oculta o hace visible el video de YouTube en la interfaz
function toggle(element){
let ventana = document.getElementById("player");
if(ventana.style.display != 'none'){
ventana.style.display = 'none';
}else{
ventana.style.display = '';
}
}
function fetchMusicDetails(){
// Poster Image, Pause/Play Image
$("#playpausebtn img").attr("src", "images/pause-red.png");
$("#bgImage").attr("src", poster[playlist_index]);
$("#image").attr("src",poster[playlist_index]);
// Title and Artist
playlist_status.innerHTML = title[playlist_index];
playlist_artist.innerHTML = artists[playlist_index];
// Audio
audio.src = dir + playlist[playlist_index] + ext;
audio.play();
}
function playPause(element){
let playButton = document.getElementById("playpausebtn");
if(playButton.value == "play"){
playButton.setAttribute("value","pause");
player.playVideo()
$("#playpausebtn img").attr("src","images/pause-red.png");
}else{
playButton.setAttribute("value","play");
player.pauseVideo();
$("#playpausebtn img").attr("src","images/play-red.png");
}
}
function nextSong(){
playlist_index++;
if(playlist_index > playlist.length - 1){
playlist_index = 0;
}
fetchMusicDetails();
}
function prevSong(){
playlist_index--;
if(playlist_index < 0){
playlist_index = playlist.length - 1;
}
fetchMusicDetails();
}
function mute(){
if(player.isMuted()){
player.unMute();
$("#mutebtn img").attr("src","images/speaker.png");
}else{
player.mute();
$("#mutebtn img").attr("src","images/mute.png");
}
}
function seek(event){
if(player.getDuration() == 0){
null;
}else{
if(seeking){
seekslider.value = event.clientX - seekslider.offsetLeft;
seekto = player.getDuration() * (seekslider.value / 100);
player.seekTo(seekto);
}
}
}
function setvolume(){
player.setVolume(volumeslider.value);
}
function seektimeupdate(){
if(player.getDuration()){
let nt = player.getCurrentTime() * (100 / player.getDuration());
seekslider.value = nt;
var curmins = Math.floor(player.getCurrentTime() / 60);
var cursecs = Math.floor(player.getCurrentTime() - curmins * 60);
var durmins = Math.floor(player.getDuration() / 60);
var dursecs = Math.floor(player.getDuration() - 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;
}else{
curtimetext.innerHTML = "00" + ":" + "00";
durtimetext.innerHTML = "00" + ":" + "00";
}
}
function switchTrack(){
if(playlist_index == (playlist.length -1)){
playlist_index = 0;
}else{
playlist_index++;
}
fetchMusicDetails();
}
function loop(){
if(audio.loop){
audio.loop = false;
$("#repeat img").attr("src", "images/rep.png");
}else{
audio.loop = true;
$("#repeat img").attr("src", "images/rep1.png");
}
}
function getRandomNumber(min, max){
let step1 = max - min + 1;
let step2 = Math.random() * step1;
let result = Math.floor(step2) + min;
return result;
}
function random(){
let randomIndex = getRandomNumber(0 , playlist.length - 1);
playlist_index = randomIndex;
fetchMusicDetails();
}
body{
margin: 0;
padding: 0;
height: 100vh;
width: 100%;
background-color: rgba(0,0,0,0);
font-family: 'Poppins', sans-serif;
}
button{
border: none;
outline: none;
background: none;
cursor: pointer;
}
.music-container{
height: 100vh;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.music-content{
position: relative;
width: 245px;
height: 450px;
background-color: #000;
border-width: 8px 4px !important;
border: solid;
border-radius: 20px;
overflow: hidden;
box-shadow: 5px 5px 10px rgba(0, 0, 0, .52);
}
#bg-image img{
width: 110%;
height: 110%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
z-index: 1;
filter: blur(6px);
-webkit-filter: blur(5px);
}
#blacklayer{
height: 450px;
width: 100%;
background-color: rgba(0,0,0,.404);
position: absolute;
z-index: 2;
}
#menu{
position: relative;
z-index: 3;
padding: 15px;
display: flex;
justify-content: space-between;
align-items: center;
}
#menu img{
width: 15px;
height: 15px;
cursor: pointer;
}
#volume-container{
position: relative;
width: 100%;
height: 15px;
z-index: 3;
display: flex;
justify-content: center;
align-items: center;
}
#volume-container img{
width: 16px;
height: 16px;
margin: 0 5px;
}
.slider{
width: 110px;
height: 1px !important;
-webkit-appearance: none;
border-radius: 10px;
background-color: #fff;
z-index: 100;
outline: none;
position: relative;
}
.slider::-webkit-slider-thumb{
-webkit-appearance: none;
width: 10px;
height: 10px;
background-color: #e62c2f;
border-radius: 50%;
cursor: pointer;
outline: none;
transform: scale(1);
}
.slider:active::-webkit-slider-thumb{
transform: scale(1.2);
}
#music-image{
position: relative;
width: 100%;
height: 215px;
z-index: 3;
}
#circle-image{
position: absolute;
top: -33%;
left: 50%;
transform: translate(-50%,50%);
width: 120px;
height: 120px;
background-color: #000;
border-radius: 50%;
border: 5px solid rgba(221,221,221,0.897);
overflow: hidden;
}
#music-image img{
width: 100%;
height: 100%;
}
#player{
position: absolute;
top: -33%;
left: 50%;
transform: translate(-50%,27%);
width: 120px;
height: 120px;
background-color: #000;
border-radius: 50%;
border: 5px solid rgba(221,221,221,0.897);
overflow: hidden;
}
#music-title{
position: relative;
padding: 0 25px;
top: 65%;
color: #fff;
}
#music-title h5{
color: #fff;
font-size: 20px;
margin: 20px 0 5px;
font-weight: 300;
text-align: center;
line-height: 1.2;
}
#music-title h6{
margin: 0;
font-size: 12.5px;
text-align: center;
font-weight: 400;
}
#music-menu{
width: 90%;
height: 40px;
position: relative;
z-index: 3;
display: flex;
justify-content: space-around;
align-items: center;
margin: 0 auto;
}
#music-menu img{
width: 15px;
height: 15px;
cursor: pointer;
}
#visibility{
width: 20px;
height: 20px;
cursor: pointer;
}
#currentTime{
position: relative;
z-index: 3;
padding: 0 12px 5px;
color: #fff;
display: flex;
justify-content: space-between;
margin-top: 8px;
}
#currentTime span{
font-size: 12px;
}
.seekslider{
width: 100px;
height: 2px !important;
-webkit-appearance: none;
border-radius: 10px;
background-color: #fff;
z-index: 3;
outline: none;
position: fixed;
margin-left: 70px;
}
.seekslider::-webkit-slider-thumb{
-webkit-appearance: none;
width: 10px;
height: 10px;
background-color: #e62c2f;
border-radius: 50%;
cursor: pointer;
outline: none;
transform: scale(1);
}
.seekslider:active::-webkit-slider-thumb{
transform: scale(1.2);
}
#buttons{
position: relative;
width: 100%;
height: 50px;
z-index: 3;
margin-top: 20px;
}
#buttons div{
display: flex;
justify-content: center;
align-items: center;
}
.play{
width: 60px;
height: 50px;
margin: 0 5px;
}
.play img{
width: 100%;
height: 100%;
}
.prev img,
.next img{
width: 20px;
height: 20px;
}
#buttons .like{
position: absolute;
top: 25%;
right: 8%;
cursor: pointer;
}
#buttons .like i{
color: rgba(255,255,255,0.883);
}
#buttons .repeat{
position: absolute;
top: 30%;
left: 6%;
font-size: 15px;
cursor: pointer;
}
#repeat img{
width: 16px;
height: 16px;
}
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="UTF-8">
<title>Music Player</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<div class="music-container">
<div class="music-content">
<div id="bg-image">
<div id="blackLayer"></div>
<img src="images/ncs1.jpeg" alt="" id="bgImage">
</div>
<div id="menu">
<img src="images/menu.png" alt="">
<img src="images/search.png" alt="">
</div>
<div id="volume-container">
<img src="images/volume-low.png" alt="" id="volumn-down">
<input type="range" class="slider" id="volumeslider" min="0" max="100" value="100" step="1">
<img src="images/volumn-high.png" alt="" id="volumn-up">
</div>
<div id="music-image">
<div id="circle-image">
<div id="player"></div>
<img src="images/ncs1.jpeg" alt="" id="image">
</div>
<div id="music-title">
<h5 id="playlist_status"></h5>
<h6 id="playlist_artist"></h6>
</div>
</div>
<div id="music-menu">
<button id="random"><img src="images/random.png" alt=""></button>
<button id="visibility"><img src="images/video-on.png" alt=""></button>
<button id="mutebtn"><img src="images/speaker.png" alt=""></button>
</div>
<div id="currentTime">
<span id="curtimetext">00:00</span>
<span id="durtimetext">00:00</span>
</div>
<input type="range" class="seekslider" id="seekslider" min="0" max="100" value="0" step="1">
<div id="buttons">
<button class="repeat" id="repeat"><img src="images/rep.png" alt=""></button>
<div>
<button class="prev" id="prevbtn"><img src="images/backward.png" alt=""></button>
<button class="play" id="playpausebtn" value="play"><img src="images/play-red.png" alt=""></button>
<button class="next" id="nextbtn"><img src="images/forward.png" alt=""></button>
</div>
<span class="like">
<i class="far fa-heart" aria-hidden="true"></i>
</span>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
<!-- begin snippet: js hide: false console: true babel: false -->
// Manifest.json
{
"manifest_version" : 2,
"name" : "OdisseyChromeExtension",
"description" : "Reproductor de musica youtube",
"version" : "0.3",
"browser_action" : {
"default_popup" : "index.html",
"default_title" : "odissey"
},
"content_security_policy": "script-src 'self' https://www.youtube.com/iframe_api https://www.youtube.com/s/player/9f996d3e/www-widgetapi.vflset/www-widgetapi.js https://code.jquery.com/jquery-3.5.1.min.js; object-src 'self'",
"permissions": [
"activeTab",
"storage",
"tabs",
"http://*/*" , "https://*/*",
"cookies",
"identity",
"identity.email"
]
}
This is the extension appearance
Okey this might actually solve your problem.
As the background is there because of the iframe, embed a player into an <object> or <video> tag..
<object width={ width } height={ height }>
<video src={ playlists['mylist'].JSON[index].source } type="video/webp" width="100%" height="333" objectFit="cover" />
</object>
Then just get a JSON of the playlist. If you want higher functionality like search or managment of user created playlists you need to go through Googles Data API. It can be finicky in the beggining but well worth the time.
here are some code examples:
https://developers.google.com/youtube/v3/docs/playlists/list?apix=true
Otherwise if you have set playlists in the player, you can just datamine separately and create your own JSON arrays, even manually its really simple and won't even take a minute per list when you have your mining snippet. A small upside here is you can dynamically create custom playlists outside of youtube.
then you can have three players and have them preload the previous and next video for a smoother switching experience ( an option for a fade inbetween can also be nice )
I have snippets of code somewhere for this kind of setup, if this sounds like something you care to do I can try to dig them up for you.
happy coding! :)
I am using Froogaloop.js to pause and play the vimeo video externally . Now I want to show a div after 20 second of video has been played. How to achieve this, I searched a lot and was not able to crack the code for it. This is what I have tried so far..
var iframe = document.getElementById('video');
// $f == Froogaloop
var player = $f(iframe);
// bind events
var playButton = document.getElementById("play-button");
playButton.addEventListener("click", function() {
player.api("play");
});
var pauseButton = document.getElementById("pause-button");
pauseButton.addEventListener("click", function() {
player.api("pause");
});
.button {
width: 48px;
height: 48px;
cursor: pointer;
}
.defs {
position: absolute;
top: -9999px;
left: -9999px;
}
iframe {
float: left;
width: 350px;
height: 200px;
}
.buttons {
padding: 1rem;
background: #f06d06;
float: left;
}
body {
padding: 1rem;
}
.show--div-20sec {
width: 100%;
background: red;
height: 80px;
float: left;
display: none;
}
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/froogaloop.js"></script>
<iframe src="https://player.vimeo.com/video/80312270?api=1" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen id="video"></iframe>
<!-----------Show this div when video has been played for 20 seconds----->
<div class="show--div-20sec">
Show me after 20 second of video play
</div>
<div class="buttons">
<button id="play-button">Play</button>
<button id="pause-button">Pause</button>
</div>
Help much appriciated.. Thanks in advance :)
Try this code
$(function() {
var iframe = $('#player1')[0];
var player = $f(iframe);
var status = $('.status');
var playButton = document.getElementById("play-button");
playButton.addEventListener("click", function() {
player.api("play");
});
var pauseButton = document.getElementById("pause-button");
pauseButton.addEventListener("click", function() {
player.api("pause");
});
setTimeout(function () {
player.addEvent('ready', function() {
player.addEvent('playProgress', onPlayProgress);
});
});
function onPlayProgress(data, id) {
var Time = data.seconds;
if (Time >= '20') {
$('.show--div-20sec').show();
}
}
});
DEMO
This is answer of your question i guess, you just need to modify the console.log part.
$(function() {
var iframe = $('#video')[0];
console.log()
var player = $f(iframe);
// When the player is ready, add listeners for pause, finish, and playProgress
player.addEvent('ready', function() {
status.text('ready');
player.addEvent('pause', onPause);
player.addEvent('finish', onFinish);
player.addEvent('playProgress', onPlayProgress);
});
// Call the API when a button is pressed
$('button').bind('click', function() {
player.api($(this).text().toLowerCase());
});
function onPause() {}
function onFinish() {}
function onPlayProgress(data) {
if (data.seconds >= 20) {
$('.show--div-20sec').css('display', 'block')
}
}
});
.button {
width: 48px;
height: 48px;
cursor: pointer;
}
.defs {
position: absolute;
top: -9999px;
left: -9999px;
}
iframe {
float: left;
width: 350px;
height: 200px;
}
.buttons {
padding: 1rem;
background: #f06d06;
float: left;
}
body {
padding: 1rem;
}
.show--div-20sec {
width: 100%;
background: red;
height: 80px;
float: left;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://f.vimeocdn.com/js/froogaloop2.min.js"></script>
<iframe src="//player.vimeo.com/video/80312270?api=1&player_id=video" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen id="video"></iframe>
<!-----------Show this div when video has been played for 20 seconds----->
<div class="show--div-20sec">
Show me after 20 second of video play
</div>
<div class="buttons">
<button id="play-button">Play</button>
<button id="pause-button">Pause</button>
</div>
I've a function called fadeIn and I want to return it until a condition is met.
I tried to put an alert in the else line along with clearInterval(myVar), but it just keeps alerting.
CSS:
* {
background-color: black;
padding: 0;
margin: 0;
height: 100%;
}
#title {
background-color: white;
height: 50px;
}
audio {
display: none;
}
#audio-icon {
width: 50px;
background-color: white;
}
#focus {
background-color: black;
margin: auto;
width: 100%;
height: 700px;
border: 5px, solid, grey;
border-style: inset;
border-radius: 10px;
}
#text-box {
background-color: black;
width: 100%;
height: 200px;
margin-top: 500px;
float: left;
border: 5px, solid, grey;
border-style: inset;
border-radius: 10px;
}
#command-line {
background-color: black;
width: 100%;
height: 50px;
margin-top: 150px;
float: left;
border: 5px, solid, grey;
border-style: inset;
border-radius: 10px;
}
#element {
opacity: 0.1;
}
HTML:
<audio id="background-audio" controls autoplay="autoplay" loop>
<source src="Darkness.mp3" type="audio/mpeg">
</audio>
<div id="title">
<img id="audio-icon" src="unmute.png" onclick="mute()">
<img id="element" src="123.png">
</div>
<div id="focus">
<div id="text-box">
<div id="command-line"></div>
</div>
</div>
JavaScript:
function fadeIn() {
var myVar = setInterval(fadeIn, 500);
var element = document.getElementById('element');
if (element.style.opacity < 1) {
element.style.opacity -= '-0.1';
} else {
clearInterval(myVar);
}
}
function mute() {
var audio = document.getElementById('background-audio');
var img = document.getElementById('audio-icon');
if (audio.muted) {
audio.muted = false;
img.src = 'unmute.png';
} else {
audio.muted = true;
img.src = 'mute.png';
}
}
document.onload = fadeIn();
UPDATE:
I have put the variables outside of the function and all of the sudden my code seems to work correctly. Not sure how this is possible since I have tried this already. My code wouldn't run at all and alert would keep alerting. Anyway thanks for all the help. This was my first question so apart from a few typos and the way I listed my code I don't really know why I get downvoted so any feedback about that is welcome! Here is my current working code:
<script>
var myVar = setInterval(fadeIn, 500);
var element = document.getElementById('element');
function fadeIn() {
console.log(element.style.opacity)
if (element.style.opacity < 1) {
element.style.opacity -= '-0.1';
} else {
clearInterval(myVar);
}
}
function mute() {
var audio = document.getElementById('background-audio');
var img = document.getElementById('audio-icon');
if (audio.muted) {
audio.muted = false;
img.src = 'unmute.png';
} else {
audio.muted = true;
img.src = 'mute.png';
}
}
document.onload = fadeIn();
</script>
See the snippet .it will stop the reach with 1 .see the console.log
var myVar;
var element = document.getElementById('element');
function fadeIn() {
console.log(element.style.opacity)
if (element.style.opacity < 1) {element.style.opacity -= -0.1;
}
else {
clearInterval(myVar);
}
}
function mute(){
var audio = document.getElementById('background-audio');
var img = document.getElementById('audio-icon');
if (audio.muted) {
audio.muted = false;
img.src = 'unmute.png';
}
else {
audio.muted = true;
img.src = 'mute.png';
}
}
window.onload =function(){
myVar = setInterval(fadeIn, 500);
}
* {
background-color: black;
padding: 0;
margin: 0;
height: 100%;
}
#title {
background-color: white;
height: 50px;
}
audio {
display: none;
}
#audio-icon {
width: 50px;
background-color: white;
}
#focus {
background-color: black;
margin: auto;
width: 100%;
height: 700px;
border: 5px, solid, grey;
border-style: inset;
border-radius: 10px;
}
#text-box {
background-color: black;
width: 100%;
height: 200px;
margin-top: 500px;
float: left;
border: 5px, solid, grey;
border-style: inset;
border-radius: 10px;
}
#command-line {
background-color: black;
width: 100%;
height: 50px;
margin-top: 150px;
float: left;
border: 5px, solid, grey;
border-style: inset;
border-radius: 10px;
}
#element {
opacity: 0.1;
}
<audio id="background-audio" controls autoplay="autoplay" loop>
<source src="Darkness.mp3" type="audio/mpeg">
</audio>
<div id="title">
<img id="audio-icon" src="unmute.png" onclick="mute()">
<img id="element" src="123.png">
</div>
<div id="focus">
<div id="text-box">
<div id="command-line"></div>
</div>
</div>
var myVar ;
var element = document.getElementById('element');
function fadeIn() {
console.log(element.style.opacity)
if (element.style.opacity < 1) {
element.style.opacity -= -0.1;
}
else {
clearInterval(myVar);
}
}
window.onload= function (){
myVar = setInterval(fadeIn, 100);
}
<p id="element">hi</p>
The problem here is that setInterval is called independently of the if clauses, and that you're spamming unobserved intervals, intervals on which you don't have access anymore in the fadeIn function's block.
In this case you could have also used setTimeout instead, because it asynchronously evaluate its first argument just once, and because you don't have access to the intervals in the way you handle them.
Note: your condition for fade in is wrong, because you're decreasing the element opacity while its opacity is only bigger than 1... i just changed this 1 by 0.
var element, lastFadeInTimeout;
element = document.getElementById('element');
function fadeIn() {
// The element is not totally
// transparent yet
if (element.style.opacity > 0) {
element.style.opacity -= 0.1;
// Let's wait 500ms to fade the element
// again, only once
lastFadeInTimeout = setTimeout(fadeIn, 500);
}
}
Now, if you want to stop your fade-in action you can call clearTimeout with lastFadeInTimeout, where lastFadeInTimeout is the identifier of the last timeout created by the fade-in action.
clearTimeout(lastFadeInTimeout);
You call the fadIn func onload (that's fine) but then you create a queue to execute the function every half a second, in each iteration you create another queue to execute the functio every half a sec.... sooner or later you're going to kill the browser with this.
What you're looking for is probably more like so:
function fadeIn() {
if (opacity < 1) {
opacity += 0.1;
setTimeout(fadeIn, 500);
}
}
document.onLoad = fadeIn();
If not for purpose of learning JavaScript you should probably do things like fadeIn / fadeOut using CSS transitions rather than JavaScript.
The following code initially loads more content when the bottom button is clicked but I need it to work when the scroll reach the bottom of the page... I've tried the code under the words //HERE IS THE PROBLEM// but it seems not to work.... any idea?
var lazyload = lazyload || {};
(function($, lazyload) {
"use strict";
var page = 2,
buttonId = "#button-more",
loadingId = "#loading-div",
container = "#container";
//HERE IS THE PROBLEM
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
lazyload.load = function() {
var url = "./" + page + ".html";
$(buttonId).hide();
$(loadingId).show();
$.ajax({
url: url,
success: function(response) {
if (!response || response.trim() == "NONE") {
$(buttonId).fadeOut();
$(loadingId).text("No more entries to load!");
return;
}
appendContests(response);
},
error: function(response) {
$(loadingId).text("Sorry, there was some error with the request. Please refresh the page.");
}
});
};
}
});
var appendContests = function(response) {
var id = $(buttonId);
$(buttonId).show();
$(loadingId).hide();
$(response).appendTo($(container));
page += 1;
};
})(jQuery, lazyload);
body{
background-color: #ccc;
margin: 0;
}
#wrapper{
width:100%;
margin: 0 auto;
min-height: 500px;
background-color: #e9e9e9;
color: #333;
padding: 10px;
text-align: center;
}
#data-container{
margin: 10px;
}
#data-container .data-item{
background-color: #444444;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
padding: 105px;
margin: 5px;
color: #fff;
}
#loading-div{
display: none;
}
#button-more{
cursor: pointer;
margin: 0 auto;
background-color: #aeaeae;
color: #fff;
width: 200px;
height: 50px;
line-height: 50px;
}
.child{
width:100%;
height:1000px;
background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<h1>Lazy Load Demo</h1>
<div id="container">
<div class="child">
</div>
</div>
<div id="button-more" onclick="lazyload.load()">
Load more items
</div>
<div id="loading-div">
loading more items
</div>
</div>
let more = document.querySelector("button");
let show = document.querySelector(".show");
let loading = document.querySelector(".loading");
let bottom = document.querySelector(".bottom");
let allowAjax = true;
function getAjax(){
loading.classList.add("show");
if(allowAjax === true){
allowAjax = false;
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let back = xhttp.response;
back = JSON.parse(back);
let imgSrc = back.results[0].picture.large;
let imgEl = document.createElement("img");
imgEl.src = imgSrc;
show.appendChild(imgEl);
loading.classList.remove("show");
allowAjax = true;
}
};
xhttp.open("GET", "https://randomuser.me/api/", true);
xhttp.send();
}
}
window.addEventListener("scroll",function(){
let scrollPos = window.pageYOffset;
let bottomPos = bottom.offsetTop;
if(bottomPos / 1.5 <= scrollPos){
// Almost to the bottom of the page
getAjax();
}
});
more.addEventListener("click",function(){
getAjax();
});
img{
display: block;
width: 30em;
height: 30em;
}
.more{
position: fixed;
top: 1em;
right: 5em;
background: skyblue;
color: #FFF;
padding: 0.5em;
border: none;
cursor: pointer;
outline: none;
}
.loading{
width: 10em;
height: 10em;
display: none;
position: fixed;
top: 5em;
right: 1em;
background: #212323;
padding: 0.5em;
}
.loading.show{
display: block;
}
.show img{
display: block;
width: 30em;
height: 30em;
}
<img src="https://unsplash.it/300/300/?random" />
<img src="https://unsplash.it/300/300/?random" />
<img src="https://unsplash.it/300/300/?random" />
<img src="https://unsplash.it/300/300/?random" />
<div class="show"></div>
<div class="bottom"></div>
<button class="more">More</button>
<img src="http://www.lettersmarket.com/uploads/lettersmarket/blog/loaders/common_metal/ajax_loader_metal_512.gif"class="loading">
initially loads