JavaScript How do i set my volumeSlider to the latest value? - javascript

JavaScript
var videoPlayer = document.getElementById('videoPlayer');
var volumeSlider = document.getElementById('volumeSlider');
mutePlayer.addEventListener('click', function() {
var mutePlayer = document.getElementById('mutePlayer');
var playMute = document.getElementById('playMute');
if(videoPlayer.muted) {
videoPlayer.muted = false;
playMute.src = "img/mute.png";
volumeSlider.value = 100; /** THIS IS THE PROBLEM RIGHT NOW I HAVE JUST SET IT TO 100 */
} else {
videoPlayer.muted = true;
playMute.src = "img/unmute.png";
volumeSlider.value = 0;
}
});
volumeSlider.addEventListener('change', function() {
videoPlayer.volume = volumeSlider.value / 100;
});
This code has to be the current value of the #volumeSlider
I have tried this but i cant access the variable volumeSlider since its scoped?
volumeSlider.addEventListener('click', function() {
var volumeSlider = volumeSlider.value;
return;
});
The HTML5
<video id='videoPlayer' class="videoPlayer" width="640px" height="360px">
<source id="Video" src="vid/bbb.mp4" type="video/mp4" height="360px" width="640px">
</video>
<button id='mutePlayer'class="center" >
<img id='playMute' src='img/mute.png'>
</button>
<input id='volumeSlider'class="center" type="range" min='0' value='100' step="1"></input>
Can someone help me crack this?

There's a couple of reasons why your code wont execute correctly. If you want to change a global variable in a scope, you don't want the var in front of the variable name.
What I've changed in the code is that the default value gets set to 100, but when I click on the slider sets inputs value to the value that's clicked on. The code will look like this:
var videoPlayer = document.getElementById('videoPlayer'),
mutePlayer = document.getElementById('mutePlayer'),
playMute = document.getElementById('playMute'),
volumeSlider = document.getElementById('volumeSlider'),
durationTimeText = document.getElementById('durationTimeText').innerHTML = "01:00",
videoPlayerVolume = 100;
volumeSlider.value = 100;
mutePlayer.addEventListener('click', function() {
if (videoPlayer.muted) {
volumeSlider.value = cachedVolume;
videoPlayer.muted = false;
playMute.src = "img/mute.png";
} else {
cachedVolume = volumeSlider.value;
videoPlayer.muted = true;
playMute.src = "img/unmute.png";
volumeSlider.value = 0;
}
});
volumeSlider.addEventListener('change', function() {
videoPlayerVolume = volumeSlider.setAttribute('value', this.value);
if (volumeSlider.value > 0) {
playMute.src = "img/mute.png";
}
});
I also added a small feature for you that sets the button image to the mute image, if the value of the input is over 0 which means that it's not muted.
If you're questioning the this keyword, it takes the element that gets clicked on and replaces it with itself. You can read more about the this keyword here.
I hope it helped.

Related

How to make clearInterval() work in JavaScript

I want to make an element (id=runner) move across the page by n pixels after a mouseover event, then stop at a certain position (left = 2000px), using setInterval() to repeatedly call move_left(), then clearInterval() when left == 200px. I can make the element move, but when I look in developer tools it never stops - left continues to increase. I am pretty new to JavaScript/HTML/CSS. How do I make it stop?
Relevant code:
<script>
function runner_go()
{
var load_time = performance.now();
const go = setInterval(move_left,20);
}
function move_left()
{
document.getElementById('runner').style.visibility = "visible";
var runner_position = getComputedStyle(document.getElementById('runner')).getPropertyValue('left');
document.getElementById('runner').style.left = parseInt(runner_position,10) + 17 + "px";
if (parseInt(runner_position,10) > 2000)
{
clearInterval(go);
}
}
</script>
</head>
<body style="background-color:gray;" onmouseover = "runner_go();">
<div>
<h1>Running!</h1>
</div>
<img src="images/runner_l.png" alt ="running man" style="position:relative; visibility:hidden;" id = "runner"/>
</body>
You need to create the var 'go' outside the method cause of the scope, also if you let on the 'body' the 'onmouseover' it will set the interval everytime.
Try this code to test:
<head>
<script>
let go = null;
function runner_go()
{
var load_time = performance.now();
go = setInterval(move_left,20);
}
function move_left()
{
document.getElementById('runner').style.visibility = "visible";
var runner_position = getComputedStyle(document.getElementById('runner')).getPropertyValue('left');
document.getElementById('runner').style.left = parseInt(runner_position,10) + 17 + "px";
if (parseInt(runner_position,10) > 2000)
{
clearInterval(go);
}
}
</script>
</head>
<body style="background-color:gray;" onclick = "runner_go();">
<div>
<h1>Running!</h1>
</div>
<img src="images/runner_l.png" alt ="running man" style="position:relative; visibility:hidden;" id = "runner"/> </body>
Problem -
You declared the interval variable as a constant within another function which is not accessible by the move_left function
So just move your interval variable to global scope (outside the function) and it should work
let go;
function runner_go() {
var load_time = performance.now();
go = setInterval(move_left, 20);
}
function move_left() {
document.getElementById('runner').style.visibility = "visible";
var runner_position = getComputedStyle(document.getElementById('runner')).getPropertyValue('left');
document.getElementById('runner').style.left = parseInt(runner_position, 10) + 17 + "px";
if (parseInt(runner_position, 10) > 2000) {
clearInterval(go);
}
}
sample on how intervals and clearIntervals work
let interval, i = 1;
function start() {
interval = setInterval(log, 1000);
}
function log() {
if (i >= 5) clearInterval(interval);
console.log(`Test ${i}`);
i++
}
start();

I need a timer to temporarily disable mouseover event

I'm looking for a simple way to temporarily disable a mouseover event, for literally 1000 miliseconds. All my attempts to do so, have so-far failed. I am trying to stop my images from flickering when the mouse enters several times as it hovers over the edge of the div. Here is my code:
var ranNum, result_10, resultFloor, piccy, audio;
function myFunction() {
ranNum = Math.random();
result_10 = (ranNum * 5) + 1;
resultFloor = Math.floor(result_10);
piccy = "<img src=\"random_images/" + resultFloor + ".gif\" />";
document.getElementById("demo").innerHTML = piccy;
audio = document.getElementById("audio");
audio.play();
}
<div id="container">
<div id="demo" onmouseenter="myFunction()">This</div>
<audio id="audio" src="pop.wav" ></audio>
</div>
This will stop the flicker:
var ranNum, result_10, resultFloor, piccy, audio;
var isPlaying = false;
var audio = document.getElementById("audio");
function myFunction() {
if (!isPlaying) {
isPlaying = true;
ranNum = Math.random();
result_10 = (ranNum * 5) + 1;
resultFloor = Math.floor(result_10);
piccy = "<img src=\"http://d2.alternativeto.net/dist/icons/cloudapp_2094.png?width=64&height=64&mode=crop&upscale=false\" />";
document.getElementById("demo").innerHTML = piccy;
// check every 1/2 second to see if the audio has ended
var t = setInterval(function() {
console.log(audio.ended);
if (audio.ended) {
isPlaying = false;
clearInterval(t);
}
}, 500);
audio.play();
}
}
<div id="container">
<div id="demo" onmouseenter="myFunction()">This</div>
<audio id="audio" src="http://freewavesamples.com/files/Casio-MT-45-Pops.wav" ></audio>
</div>
var myFunctionDisabled = null;
function disableMyFunction() {
clearTimeout(myFunctionDisabled);
myFunctionDisabled = setTimeout(function() { myFunctionDisabled = false; }, 1000);
}
function myFunction() {
if (myFunctionDisabled) return;
...
}
Here's a quick and dirty approach. Simply uses a variable referencing a function, and changes the reference to point to a function that does nothing, then back to the original function.
I agree with Kosch's suggestion of using the underscore/lodash debounce function if you're already using those libraries or if you see them helping you in more than just this one case.
var ranNum, result_10, resultFloor, piccy, audio;
function myFunction() {
disableMouseOverHandler();
ranNum = Math.random();
result_10 = (ranNum * 5) + 1;
resultFloor = Math.floor(result_10);
piccy = "<img src=\"random_images/" + resultFloor + ".gif\" />";
document.getElementById("demo").innerHTML = piccy;
audio = document.getElementById("audio");
audio.play();
}
function doNothing() {
}
var mouseOverHandler = myFunction;
function disableMouseOverHandler() {
mouseOverHandler = doNothing;
setTimeout(function(){ mouseOverHandler = myFunction; }, 3000);
//I used 3000ms (3 seconds) to make it more pronounced.
}
<div id="container">
<div id="demo" onmouseenter="mouseOverHandler()">This</div>
<audio id="audio" src="pop.wav" ></audio>
</div>

javascript not working on button as expected

I'm trying to connect previous and fwd buttons to a gallery and I want the previous button to be hidden on first image of the gallery but javascript doesn't seem to be working at all.
Javascript
var imageGallery = new Array();
imageGallery[0] = '1.png';
imageGallery[1] = '2.png';
imageGallery[2] = '3.png';
imageGallery[3] = '4.png';
imageGallery[4] = '5.png';
var imgCount = 0;
function next() {
imgCount++ ;
document.getElementById("gallery").src = imageGallery[imgCount] ;
}
function previous() {
imgCount--;
document.getElementById("gallery").src = imageGallery[imgCount] ;
}
if(document.getElementById("gallery").getAttribute("src") == "1.png")
{
document.getElementById("previous").style.visibility = 'hidden';
}
else
{
document.getElementById("previous").style.visibility = 'visible';
}
HTML
<div id="img">
<img id="gallery" src="1.png" style="height:420px; width:744px" >
<div id="imgNav">
<a id="previous" href onclick="previous(); return false;">previous</a>
<span style="color:#666; font-size:0.9em"> | </Span>
<a id="next" href onclick="next(); return false;">next</a>
</div>
</div>
Actually the logic is if 'src' attribute of id 'gallery' is '1.png' then 'visibility' of element with id 'previous' is 'hidden' else not but doesn't seem to be working. Can anyone help figuring it out.
You're probably trying to check on an image that's not totally loaded yet. Did you remember to place your code to run just when the page is fully loaded (in case it's placed in the page headers - you didn't mention whether it is or not)?
UPDATED
var imageGallery = new Array();
imageGallery[0] = '1.png';
imageGallery[1] = '2.png';
imageGallery[2] = '3.png';
imageGallery[3] = '4.png';
imageGallery[4] = '5.png';
var imgCount = 0;
function checkNav() {
var previousLnk = document.getElementById("previous");
var nextLnk = document.getElementById("next");
previousLnk.style.visibility = imgCount == 0 ? 'hidden' : 'visible';
nextLnk.style.visibility = imgCount >= (imageGallery.length - 1) ? 'hidden' : 'visible';
}
function setImg() {
var gallery = document.getElementById("gallery");
gallery.src = imageGallery[imgCount];
}
function next() {
imgCount++;
setImg();
checkNav();
}
function previous() {
imgCount--;
setImg();
checkNav();
}
window.onload = function () {
checkNav();
}
Demo: http://jsfiddle.net/N7V9E/

Display diffrent image depending on timer

I'm trying to display a different image depending on the timer's result and can't find a way through. So far I have a start and stop button, but when I click stop, I want to use the value the timer is on and display an image(on alertbox or the webpage itself) depending on that value.
if( timer =>60){
img.src("pizzaburnt.jpg");
}elseif (timer <=30){
img.src("pizzaraw.jpg");
}
else{
img.src("pizzaperfect.jpg
}
///Time
var check = null;
function printDuration() {
if (check == null) {
var cnt = 0;
check = setInterval(function () {
cnt += 1;
document.getElementById("para").innerHTML = cnt;
}, 1000);
}
}
//Time stop
function stop() {
clearInterval(check);
check = null;
document.getElementById("para").innerHTML = '0';
}
**HTML**
<td>
Timer :<p id="para">0</p>
</td>
Any advice or dicussion would be great, thanks.
Something like this would work better and it's more compact:
var img = document.getElementById("image");
var imageSrcs = ['pizzaRaw.jpg', 'pizzaPerfect.jpg', 'pizzaBurnt.jpg'];
var imageIndex = 0;
var interval = setInterval(animate, 30000); //change image every 30s
var animate = function() {
//change image here
//using jQuery:
img.src(imageSrcs[imageIndex]);
imageIndex++; //move index for next image
if (imageIndex == imageSrcs.length) {
clearInterval(interval); //stop the animation, the pizza is burnt
}
}
animate();
Reason you wouldn't want to use an increment variable and a 1 second timer is because your just conflating your logic, spinning a timer, and making a bit of a mess when all you really want is the image to change every 30 seconds or whenever.
Hope this helps.
You need an <img> tag in your HTML like this:
<html>
<body>
Timer: <p id="para">0</p>
Image: <img id="image" />
</body>
</html>
And the Javascript code will be like:
var handle;
var timerValue = 0;
var img = document.getElementById( "image" );
var para = document.getElementById("para");
function onTimer() {
timerValue++;
para.innerHTML = timerValue;
if ( timerValue >= 60 ) {
img.src( "pizzaburnt.jpg" );
}else if ( timer <= 30 ) {
img.src( "pizzaraw.jpg" );
} else {
img.src("pizzaperfect.jpg" );
}
}
function start () {
if ( handle ) {
stop();
}
timerValue = 0;
setInterval( onTimer, 1000 );
}
function stop () {
if ( handle ) {
clearInterval ( handle );
}
}
Please make sure that these 3 files are in the same directory as your HTML file:
pizzaburnt.jpg
pizzaraw.jpg
pizzaperfect.jpg

some errors with javascript objects

I am beginning to hate objects in javascript.
Every time I have error and I fix it, a new error appears, and so on.
Can you please take a look at the following code and tell me what's wrong ?
problem message:
"this.Images is undefined"
and more errors also
HTML File
<div id="SlideShow" >
<img id="img" src="images/img.jpg" alt="" /><span id="desc"></span>
</div>
<script type="text/javascript">
meToo.Images = ['images/img.jpg','images/img2.jpg','images/img3.jpg','images/img4.jpg','images/img5.jpg'];
meToo.Titles = ['Pic1','pic2','Pic3','Pic4','Pic5'];
meToo.Play('img');
</script>
Javascript Object
var meToo = {
Images: [],
Titles: [],
counter: 0,
Play: function(ElemID){
var element = document.getElementById(ElemID);
var ImgLen = this.Images.length;
if(this.counter < ImgLen){
this.counter++;
element.src = this.Images[this.counter];
element.nextSibling.innerHTML = this.Titles[this.counter];
}else{
this.counter = 0;
}
setTimeout(this.Play, 1000);
}
};
See the Example
See this question. Otherwise setTimeout sets this to the window object. Also, the counter should be incremented after setting the images or you will be reading outside the array bounds.
Finally, when resetting the counter to 0, there will be an additional one-second delay before the loop restarts, because the image is not being reset in that else block. You may wish to rewrite that part of the logic.
Updated Fiddle
if(this.counter < ImgLen){
element.src = this.Images[this.counter];
element.nextSibling.innerHTML = this.Titles[this.counter];
this.counter++;
}else{
this.counter = 0;
}
var _this = this;
setTimeout(function() { _this.Play('img') }, 1000);
This is what I would write to keep the loop going at one-second intervals:
Play: function(ElemID) {
var element = document.getElementById(ElemID);
var ImgLen = this.Images.length;
if (this.counter == ImgLen) {
this.counter = 0;
}
element.src = this.Images[this.counter];
element.nextSibling.innerHTML = this.Titles[this.counter];
this.counter++;
var _this = this;
setTimeout(function() {
_this.Play('img')
}, 1000);
}
if(this.counter < ImgLen)
is wrong.
What will happen here is that when you run
this.counter++;
the value of that variable will now be ImgLen.length
Arrays in javascript go from 0 to length -1.So now you'll be exceeding the array's length, when you run:
this.Images[this.counter];
and encounter an error.
The quick fix here is to change to
if(this.counter < ImgLen -1)
If you're encountering other problems, then post the exact error message. (Run in Chrome and press F12 (for example) to bring up the console so you can see the errors).
Here check this out.It should work perfectly for you.I have made it a singleton object and also I am doing a check if incase meToo.Play is called before the dom is loaded it will not crash.All the other mistakes that the guys above are pointing are also taken care of.
<script>
var meToo = function(){
var Images = ['http://www.image-upload.net/di/WMPI/img.jpg','http://www.image-upload.net/di/HPUQ/img2.jpg','http://www.image-upload.net/di/WQ9J/img3.jpg','http://www.image-upload.net/di/GIM6/img4.jpg','http://www.image-upload.net/di/0738/img5.jpg'];
var Titles = ['Pic1','pic2','Pic3','Pic4','Pic5'];
var counter = 0;
return {
Play: function(ElemID) {
var element = document.getElementById(ElemID);
if(element){
var ImgLen = Images.length;
if(counter < ImgLen) {
element.src = Images[counter];
element.nextSibling.innerHTML = Titles[this.counter];
counter++;
} else {
counter = 0;
}
}
setTimeout(callmeToo, 1000);
}
}
}();
function callmeToo(){
meToo.Play('img');
}
callmeToo();
</script>

Categories