I'm having a bit of trouble I am making my own controls for a html5 video player. I have got everything working correctly but I would like for my slider to have a specified colour left of the thumb and a different colour right of the thumb. i Have seen another example on here that almost does it with jquery but I can only get it working onclick and not progessing automatically with the video. I am new to javascript and could really do with the help getting this to work.
<script>
var
vid,
playbtn,
mutebtn,
fullscreenbtn,
seekslider,
volumeslider,
curtimetext,
durtimetext;
function intializePlayer(){
//Set object references
vid = document.getElementById("my_player");
playbtn = document.getElementById("playpausebtn");
mutebtn = document.getElementById("mutebtn");
fullscreenbtn = document.getElementById("fullscreenbtn");
seekslider = document.getElementById("seekslider");
volumeslider = document.getElementById("volumeslider");
curtimetext = document.getElementById("curtimetext");
durtimetext = document.getElementById("durtimetext");
//Add event listeners
playbtn.addEventListener("click",playPause,false);
mutebtn.addEventListener("click",vidmute,false);
fullscreenbtn.addEventListener("click",toggleFullScreen,false);
seekslider.addEventListener("change",vidSeek,false);
volumeslider.addEventListener("change",setvolume,false);
vid.addEventListener("timeupdate",seektimeupdate,false);
}
window.onload = intializePlayer;
function playPause(){
if(vid.paused){
vid.play();
playbtn.style.background = "url(images/pause.png)";
} else {
vid.pause();
playbtn.style.background = "url(images/play.png)";
}
}
function vidSeek(){
var seekto = vid.duration * (seekslider.value / 100);
vid.currentTime = seekto;
}
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;
}
function vidmute(){
if(vid.muted){
vid.muted = false;
mutebtn.style.background = "url(images/volume.png)";
volumeslider.value = 100;
} else {
vid.muted = true;
mutebtn.style.background = "url(images/mute.png)";
volumeslider.value = 0;
}
}
function setvolume(){
vid.volume = volumeslider.value / 100;
}
function toggleFullScreen(){
if(vid.requestFullScreen){
vid.requestFullScreen();
} else if(vid.webkitRequestFullScreen){
vid.webkitRequestFullScreen();
} else if(vid.mozRequestFullScreen){
vid.mozRequestFullScreen();
}
}
</script>
I think what you're trying to do is update the "seektimeupdate" function every second. To do this you can use a thing called "setInterval". The code would look something like this.
var updateBar = setInterval(function(){
//You put the code you want to perform here
seektimeupdate();
},1000)
What the "1000" means is the delay, in milliseconds, between each time the code is fired. You can think of "setInterval" as a for loop that performs its code at a set rate, specified by the number at the end.
Sorry if I misunderstood your question and if you want more help on the "setInterval" function then see W3 school's documentation on it here
EDIT:
This Code works, assuming you can get the duration of the movie in seconds and the current time of the movie in seconds. The only problem you might encounter is changing the slider, depending on how the user moves the thumb or if they pause the movie. I would suggest using variables to buffer the function.
(NOTE): Just replace the jQuery in the jsFiddle link you gave me in the comments with this.
var movie = {
//duration of movie, in seconds
duration:1000,
//current time in movie, in seconds
currentTime:0
}
var update = setInterval(function(){
movie.currentTime += 1;
var val = movie.currentTime/movie.duration;
$("#range").css('background-image',
'-webkit-gradient(linear, left top, right top, '
+ 'color-stop(' + val + ', #94A14E), '
+ 'color-stop(' + val + ', #C5C5C5)'
+ ')'
);
},1000);
Related
I have a function that adds random images to my divs that disappear over time and create a mouse trail. My issue is: there are double images.
I'd like to add something that checks if the background url is already located on the page and if that's the case, skips to the next in the array and check it again until until it comes across one that is not there. So like a loop that refreshes every time a 'trail' is being created.
Maybe I am asking for something that won't work? What if all the images are already on the page? I don't really have an answer for it and I also don't have an idea how to solve that problem yet.
For now I tried adding a counter that checks the usedImages and counts them, but it seems to have flaws and I am unsure where to look or how to fix it. Does anyone have any tips on how to do this? Is it even possible?
My fiddle
var bgImages = new Array(
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/schraegluftbild-1024x725.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/pikto-608x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhausen-EG-Grundriss-913x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/lageplan-945x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhausen-EG-Grundriss-913x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhauser-Esch-Modell-2-1024x768.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/07/DSCN3481-1024x768.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/07/zoom-in-3_ASTOC-1024x683.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2016/07/IMG_1345-1024x768.jpg"
);
const numberOfImages = 10;
const timesPerSecond = .1;
var usedImages = {};
var usedImagesCount = 0;
function preloadImages(images) {
for (i = 0; i < images.length; i++) {
let l = document.createElement('link')
l.rel = 'preload'
l.as = 'image'
l.href = images[i]
document.head.appendChild(l);
}
}
function animate(e) {
var image = document.createElement('div');
image.classList.add('trail');
var sizew = 200;
var sizeh = 200;
image.style.transition = '3s ease';
image.style.position = 'fixed';
image.style.top = e.pageY - sizeh / 2 + 'px';
image.style.left = e.pageX - sizew / 2 + 'px';
image.style.width = sizew + 'px';
image.style.height = sizeh + 'px';
var random = Math.floor(Math.random() * (bgImages.length));
if (!usedImages[random]) {
image.style.backgroundImage = "url(" + bgImages[random] + ")";
usedImages[random] = true;
usedImagesCount++;
if (usedImagesCount === bgImages.length) {
usedImagesCount = 0;
usedImages = {};
}
} else {
animate(e);
}
console.log(usedImages);
console.log(usedImagesCount);
image.style.backgroundSize = 'cover';
image.style.pointerEvents = 'none';
image.style.zIndex = 1;
document.body.appendChild(image);
//opacity and blur animations
window.setTimeout(function() {
image.style.opacity = 0;
image.style.filter = 'blur(20px)';
}, 40);
window.setTimeout(function() {
document.body.removeChild(image);
}, 2100);
};
window.onload = function() {
preloadImages(bgImages);
var wait = false;
window.addEventListener('mousemove', function(e) {
if (!wait) {
wait = true;
setTimeout(() => {
wait = false
}, timesPerSecond * 800);
animate(e);
}
});
};
I have this inside index.html
<body>
<script>
window.onload=function() {
let videoDiv = createVideoDiv()
document.getElementById("contentVideo").appendChild(videoDiv);
document.addEventListener("keydown", function(inEvent){
controlVideo(inEvent.keyCode);
});
}
</script>
<div id="progressBarWrapper">
<div id="progressBar"></div>
</div>
<div id="contentVideo"></div>
</body>
and this css
#progressBarWrapper {
width: 100%;
height:15px;
background-color: black;
}
#progressBar {
width: 0%;
height: 15px;
background-color: green;
}
this is how the video div is created:
function createVideoDiv() {
var video = document.createElement("VIDEO");
video.setAttribute('controls', '');
//video.setAttribute('autoplay', '');
video.setAttribute('preload', 'auto');
video.setAttribute('width', larguraVideo);
video.setAttribute('id', 'video');
var source = document.createElement("SOURCE");
source.setAttribute('src', obterVideoClicado());
source.setAttribute('type', 'video/mp4');
video.addEventListener('progress', function() {
var range = 0;
var bf = this.buffered;
var time = this.currentTime;
while(!(bf.start(range) <= time && time <= bf.end(range))) {
range += 1;
}
var loadStartPercentage = bf.start(range) / this.duration;
var loadEndPercentage = bf.end(range) / this.duration;
var loadPercentage = loadEndPercentage - loadStartPercentage;
setTimeout(ajustarProgressBar, 40, loadPercentage * 100);
});
video.addEventListener('loadeddata', function() {
var myBar = document.getElementById("progressBarWrapper");
myBar.style = "display:none;";
video.play();
});
video.appendChild(source);
return video;
}
this is how the progress bar is adjusted
function ajustarProgressBar(valor) {
var progressBar = document.getElementById("progressBar");
progressBar.style.width = valor + "%";
}
Even the progress bar is being fired by
setTimeout(ajustarProgressBar, 40, loadPercentage * 100);
the progress bar is not updating and stays 0% all the time.
The progress bar is to be adjusted by the video download progress.
The video progress is working fine. I have printed that to console and the values are changing as the video download progresses.
You have to pass param to function:
var valor = loadPercentage * 100;
var delay = 100;
setTimeout(() => ajustarProgressBar(valor), delay);
--Edit
Your video progress event listener would now look like:
video.addEventListener('progress', function() {
var range = 0;
var bf = this.buffered;
var time = this.currentTime;
while(!(bf.start(range) <= time && time <= bf.end(range))) {
range += 1;
}
var loadStartPercentage = bf.start(range) / this.duration;
var loadEndPercentage = bf.end(range) / this.duration;
var loadPercentage = loadEndPercentage - loadStartPercentage;
var valor = loadPercentage * 100;
var delay = 100;
setTimeout(() => ajustarProgressBar(valor), delay);
});
The setTimeout function takes 2 parameters:
The function to call after the delay time
The delay time in milliseconds
So to call your function you must make a function that will call your function like this:
setTimeout(() => ajustarProgresBar(loadPercentage * 100), 40);
So in your code it might look like this:
var loadStartPercentage = bf.start(range) / this.duration;
var loadEndPercentage = bf.end(range) / this.duration;
var loadPercentage = loadEndPercentage - loadStartPercentage;
setTimeout(() => ajustarProgressBar(loadPercentage*100), 40);
I have a repeat function which runs on a button on-click event, however it's not working properly. Maybe because there are too many setIntervals running although I tried to clear them all. I also made sure to reset the variables used back to their initial values, however the moving circle keeps showing up faded when the shoot again button is pressed, so I'm assuming there's an issue with the setInterval, however, I don't know what it is.It's also not drawing the basketball again.
var level = prompt("Type 1 for hard, 2 for medium, and 3 for easy.")
var dt = level / 100;
var ctx = canvas.getContext("2d");
var intervalId2;
var intervalId1;
//Initializing Variables
var dt = level / 100;
const PI = 3.14;
var r = 20;
var x = r + 1;
var y = 500 / 1.2;
var a = 1;
var shift = 380;
var leftshift = 35;
var xc = 145;
var yc = 300;
var rc = 50;
var dxc = 95;
var dyc = 300;
var theta = 0;
var resetVars = function() {
dt = 0.01;
var x = r + 1;
var y = 500 / 1.2;
var xc = 145;
var yc = 300;
var dxc = 95;
var dyc = 300;
var theta = 0;
};
//resetVars();
var reset = function() {
ctx.clearRect(0, 0, 800, 800);
drawHoop()
};
//Interval Id to eventually clear it to stop this to shoot
var intervalID = setInterval(moveCirc, 10000 * dt);
var count = 0;
//shoot when spacebar is pressed
document.body.onkeyup = function(shoot1) {
if (dxc <= 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
make();
count = count + 1;
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
if (dxc > 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
miss();
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
};
var repeat = function() {
reset();
clearInterval(intervalID);
clearInterval(intervalId2);
clearInterval(intervalId1);
resetVars();
drawBasketball();
drawHoop();
moveCirc();
intervalID = setInterval(moveCirc, 10000 * dt);
document.body.onkeyup = function(shoot1) {
if (dxc <= 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
make();
count = count + 1;
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
if (dxc > 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
miss();
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
};
};
<html>
<canvas id="canvas" width="1000" height="500"> </canvas>
<body style="background-color:powderblue;">
<p id="count"></p>
<button id="again" onclick="repeat()"> Shoot Again </button>
</body>
This should make a stop button for a repeating function
<script>
var int=self.setInterval(function, 60000);
</script>
<!-- Stop Button -->
Stop
I am trying to make an audio player for my website that plays album playlist(m3u) and Individual mp3's on click. They're are going to be several playlist and mp3's so I need the song to auto go to the next song. And I need option to go to NEXT or PREVIOUS song
I do believe that I have started writing the code for the playLast and playNext but I dont know how to script the function in order for me to assign it a button
<script>
var player;
var intv;
var slider;
//Init
//
////////////////////////////
window.onload = function()
{
document.getElementById('btnlast').addEventListener('click',playLast, false);
document.getElementById('btnPlay').addEventListener('click', playMusic, false);
document.getElementById('btnPause').addEventListener('click', pauseMusic, false);
document.getElementById('btnStop').addEventListener('click', stopMusic, false);
document.getElementById('btnVolUp').addEventListener('click', volUp, false);
document.getElementById('btnVolDown').addEventListener('click', volDown, false);
player = document.getElementById('player');
slider = document.getElementById('sliderTime');
slider.addEventListener('change', reposition, false);
}
function reposition()
{
player.currentTime = slider.value;
}
//Volume Controls
//
// 0.0 Silent - 1.0 Full Volume
/////////////////////////////
function volUp()
{
if(player.volume < 1)
{
player.volume += 0.1;
console.log(player.volume);
} else
{
player.volume = 1;
}
}
function volDown()
{
if(player.volume > 0)
{
player.volume -= 0.1;
console.log(player.volume);
} else
{
player.volume = 0;
}
}
//Music Play Controls
//
///////////////////////////
function playMusic()
{
player.play();
intv = setInterval(update, 100);
slider.max = player.duration;
}
function update()
{
document.getElementById('songTime').innerHTML = millisToMins(player.currentTime);
slider.value = player.currentTime;
}
function millisToMins(seconds)
{
var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60;
if (numseconds >= 10)
{
return "Time Elapsed: " + numminutes + ":" + Math.round(numseconds);
} else
{
return "Time Elapsed: " + numminutes + ":0" + Math.round(numseconds);
}
}
function pauseMusic()
{
player.pause();
clearInterval(intv);
}
function stopMusic()
{
player.pause();
player.currentTime = 0;
clearInterval(intv);
}
The following code has me confused. My goal is to fade an HTML element from one opacity level to another, over a period of time. Below is my dimScreen() method, used to create a darkened overlay and fade it in.
var overlay;
function dimScreen()
{
if(!overlay)
{
overlay = document.createElement('div');
overlay.setAttribute('id', 'overlay');
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.zindex = '1000';
overlay.style.background = '#000013';
overlay.style.position = 'fixed';
overlay.style.left = '0';
overlay.style.top = '0';
overlay.style.opacity = '.0';
document.body.appendChild(overlay);
fade('overlay', 0, 75, 200);
}
}
Here is my working fade function:
function fade(eID, startOpacity, stopOpacity, duration)
{
var speed = Math.round(duration / 100);
var timer = 0;
if (startOpacity < stopOpacity)
{ // fade in
for (var i=startOpacity; i<=stopOpacity; i++)
{
setTimeout("setOpacity('"+eID+"',"+i+")", timer * speed);
timer++;
} return;
}
for (var i=startOpacity; i>=stopOpacity; i--)
{ // fade out
setTimeout("setOpacity('"+eID+"',"+i+")", timer * speed);
timer++;
}
}
And my working setOpacity:
function setOpacity(eID, opacityLevel)
{
var eStyle = document.getElementById(eID).style;
eStyle.opacity = opacityLevel / 100;
eStyle.filter = 'alpha(opacity='+opacityLevel+')';
}
I would like to, however, change my fade() function to user a closure in the form of:
setTimeout(function(){setOpacity(eID,i)}, timer * speed);
I could then pass in the actual overlay div, instead of the id 'overlay'. When I do this, however, rather than animating a gradual fade-in of the overlay div, it just goes right to the last opacity value with no transition. Why does this happen?
I have a feeling this is something simple that I am missing because I've been looking at it for so long. Any help would be appreciated!
It's too late and still too hot to think much here right now. (2.30am, 28°C)
Forgive me if my explanation falls short of expectations.
Basically, because you construct text strings to pass to setTimeout, each call gets the correct value for i. Since to pass an actual element, you can't use the string trick, you end up using the same value of i for each call to setOpacity.
As your question title indicates you understand, you need to use closures to get it to work right. I can't find(only followed 2 or 3 links) a good tute/S.O question that explains it in a way that seems relevant and clear.
Hope the code will be of use.
var overlay;
function dimScreen()
{
if(!overlay)
{
overlay = document.createElement('div');
overlay.setAttribute('id', 'overlay');
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.zindex = '1000';
overlay.style.background = '#000013';
overlay.style.position = 'fixed';
overlay.style.left = '0';
overlay.style.top = '0';
overlay.style.opacity = '.0';
document.body.appendChild(overlay);
myFade(overlay, 0, 75, 2000);
}
}
function myFade(element, startOpacity, stopOpacity, duration)
{
var speed = Math.round(duration / 100);
var timer = 0;
if (startOpacity < stopOpacity)
{ // fade in
for (var i=startOpacity; i<=stopOpacity; i++)
{
(
function()
{
var myI = i;
setTimeout(function(){mySetOpacity(element,myI)}, timer * speed);
}
)()
timer++;
}
}
else
for (var i=startOpacity; i>=stopOpacity; i--)
{ // fade out
for (var i=startOpacity; i<=stopOpacity; i++)
{
(
function()
{
var myI = i;
setTimeout(function(){mySetOpacity(element,myI)}, timer * speed);
}
)()
timer++;
}
}
}
function mySetOpacity(el, opacityLevel)
{
var eStyle = el.style;
eStyle.opacity = opacityLevel / 100;
eStyle.filter = 'alpha(opacity='+opacityLevel+')';
}