Audio up and down and .currentTime HTML5 / Javascript - javascript

Have an issue with some code.. I can't find anything wrong with it and appears to be identical with my other code that does work. Just the volume up and volume down and the goToChorus that i'm having trouble. Any help is appreciated!
<!DOCTYPE html>
<html>
<head>
<title>Slider + Play/Pause</title>
<script>
"use strict";
/*function playMusic() {
document.getElementById("mediaClip").play();
}*/
var mediaClip = document.getElementbyId("mediaClip");
var volume1 = document.getElementbyId("volume1").value;
function playPause() {
var mediaClip = document.getElementById("mediaClip");
if (mediaClip.paused) {
mediaClip.play();
} else {
mediaClip.pause();
}
}
function change() {
var button1 = document.getElementById("button1");
if (button1.value==="Play") button1.value = "Pause";
else button1.value = "Play";
}
function setVolume() {
var mediaClip = document.getElementById("mediaClip");
mediaClip.volume = document.getElementById("volume1").value;
}
function backStart() {
document.getElementById("mediaClip").currentTime = 0;
}
function upVolume() {
if (mediaClip.volume < 1)
{
mediaClip.volume += 0.1;
}
}
function downVolume() {
if (mediaClip.volume > 0)
{
mediaClip.volume -= 0.1;
}
}
function goToChorus() {
mediaClip.currenTime = 55;
}
</script>
</head>
<body onload="init()">
<audio id="mediaClip" src="takeMeToChurchHozier.mp3" controls>
<p>Your browser does not support the audio element</p>
</audio>
<br/>
<input onclick="change();playPause()" type="button" value="Play" id="button1">
<input type="range" onchange="setVolume()" id='volume1' min=0 max=1 step=0.01 value='1'/>
<br/>
<button onclick ="backStart()">Reset</button>
<br/>
<button onclick="upVolume()">Volume up 10%</button>
<button onclick="downVolume()">Volume down 10%</button>
<br/>
<input type="button" value="Click for chorus" onclick="goToChorus()">
</body>
</html>

Okay, first things first. Take your JavaScript code and get it out of the <head> element. This breaks things like
var mediaClip = document.getElementbyId("mediaClip");
because it tries to look for the element "mediaClip" before the browser has even gotten down to that line of code and created that DOM element. Having the JavaScript AFTER the HTML code will allow the DOM elements to be created by the browser, then your code will run.
Second, you have a few typos in your JavaScript. Twice you try to use the method getElementbyId (notice the lower-case b). Changing these to getElementById should fix it.
Okay, so now your code will run after DOM load, and will find the elements properly. This should allow the rest of your functions to run, since they all rely on the variable mediaClip being set properly at the beginning.
One more thing: you need to add something inside of upVolume() and downVolume() to change the value of the slider volume1. Right now, when you click the up/down buttons the volume will update, but the slider doesn't move.
Here's a JSFiddle of your code that I got to work after the above modifications: http://jsfiddle.net/vcxsn6q7/

Related

How to reset an HTML range slider to default position and default playbackRate value with a single button press

I’m a total newbiew here, but trying my best to figure this out.
I can specify the video playback speed with a range slider no problem, but after changing the speed on the slider, instead of manually pushing it back to it’s original value I’d like to be able to push a “Reset speed” button and have the slider automatically reset both to it’s original position and original speed value of “1”. I’ve managed to get the slider to reset to it’s starting position but it still retains the altered playback speed value. Below is the code I came up with. Can anyone help me with this? Thank you!
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function () {
var v = document.getElementById("myVideo");
var p = document.getElementById("pbr");
var c = document.getElementById("currentPbr");
p.addEventListener('input',function(){
c.innerHTML = p.value;
v.playbackRate = p.value;
},false);
};
</script>
<script>
function myFunction(){
document.getElementById("myForm").reset();
}
function setPlaySpeednormal(){
vid.playbackRate = 1;
}
</script>
<style>
.holder {
width:640px;
height:360;
margin: 0 auto;
margin-bottom:14em;
}
#pbr {
width:50%;
}
</style>
</head>
<body>
<div class="holder">
<video id="myVideo" controls>
<source src="https://www.dropbox.com/s/5rjbtmantuow8vw/testvideo_hfd.mp4?raw=1"
type='video/mp4'/>
</video>
<form id= "myForm">
<input id="pbr" type="range" value="1"
min="0.5" max="1.5" step="0.05" >
<p>Playback Rate <span id="currentPbr">1</span></p>
<input type="button" value="Reset speed" onclick="myFunction();setPlaySpeednormal();"/>
</form>
</div>
</body>
</html>
In the window.onload function, you've declared a variable with scope of only that function. You can't access it outside when you need it in the setPlaySpeednormal function. So, move the variable v outside:
var v;
window.onload = function () {
v = document.getElementById("myVideo");
var p = document.getElementById("pbr");
var c = document.getElementById("currentPbr");
p.addEventListener('input',function(){
c.innerHTML = p.value;
v.playbackRate = p.value;
},false);
};
Also, in your setPlaySpeednormal function, you are using a variable named vid. Even though the variable you are using for video element is named v
function setPlaySpeednormal(){
v.playbackRate = 1; // change vid to v
}

Cycling images with javascript

Why doesn't the second (hawk) image appear when the button is clicked? It goes straight to the else statement showing the ant image.
<!DOCTYPE html>
<html>
<body>
<script>
function changeImg() {
if (document.getElementById("cycle").src == "fox.jpg") {
document.getElementById("cycle").src = "hawk.jpg";
} else {
document.getElementById("cycle").src = "ant.jpg";
}
}
</script>
<button onclick = "changeImg()">change image</button>
<img id ="cycle" src ="fox.jpg"/>
</body>
</html>
Please add your script tags at the end of the body to make sure that your dom is rendered before accessing any elements. (like in my example)
The problem with your code is, that you need to add a new if for every new image you add. As you noticed yourself, it becomes hard to understand and debug.
For something like cycling, use an array and modulo operation on the index of that array.
With this solution, you can add as many images to the images array as you like, without touching the code/logic;
<!DOCTYPE html>
<html>
<body>
<button onclick="changeImg()">change image</button>
<img id="cycle" />
<script>
var imageElement = document.getElementById("cycle");
var images = ["fox.jpg", "hawk.jpg", "ant.jpg"]; // add as many images as you want
var counter = 0;
imageElement.src = images[counter] // set the initial image
function changeImg() {
counter = (counter + 1) % images.length;
imageElement.src = images[counter];
}
</script>
</body>
</html>
document.getElementById("cycle").src always has full url of image (example:https://example.loc/example/fox.jpg) and this is not similar from fox.jpg.
You need try another solution.Try use
cycle.getAttribute('src')
Example code:
function changeImg() {
let cycle = document.getElementById("cycle");
console.log(cycle.src,cycle.getAttribute('src')); // show real value and taribute
if (cycle.getAttribute('src') == "fox.jpg") {
cycle.src = "hawk.jpg";
} else {cycle.src = "ant.jpg";
}
}
Use getAttribute('src') if you want to access the actual contents of the attribute. Otherwise you get the resolved URL.
var cycle = document.getElementById("cycle");
if (cycle.getAttribute('src') == "fox.jpg") {
cycle.src = "hawk.jpg";
} else {
cycle.src = "ant.jpg";
}

How to add a timer for images in JavaScript?

I've been working on this code which displays the next traffic light when a button is pressed. Now I am trying to diplay the images in the array every 3 seconds. I have tried using setTimeOut in my code but my code juts stays on the first traffic light.
code:
EDIT(FIXED)
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Code</h1>
<p>Traffic Light</p>
<img id="traffic" src="only red1.jpg">
<button type="button" onclick="ChangeLight()">Change Light</button>
<script>
var list = ["only red1.jpg","red-yellow 2.jpg", "green3.jpg","yellowonly4.jpg"];
var nextlight = 0;
var timer;
function ChangeLight() {
nextlight = nextlight + 1;
if (nextlight == list.length)
nextlight = 0;
var firstlight = document.getElementById('traffic');
firstlight.src = list[nextlight];
}
timer = setInterval(ChangeLight, 3000);
</script>
</body>
</html>
Solution:
timer = setInterval("ChangeLight", 3000);
Put it out of the function ^^
2 things:
It's supposed to be setInterval(ChangeLight, 3000);
timer is inside the ChangeLight function. You should move it outside.
You may want to change timer = setTimeout("ChangeLight", 3000); into timer = setTimeout(ChangeLight, 3000);.

Image will not switch between hidden and show

I cannot get an image to switch back and forth between 'hidden' and 'show'
I'm using ideas from
How to create a hidden <img> in JavaScript?
I have two different buttons, trying one using html and the other to use javascript - If I comment out one line, the light bulb photo is displayed
//document.getElementById("light").style.visibility = "hidden";
That line of code is in my 'init' function
If I do not comment the line, the light stays 'hidden', no matter which of the buttons I click
I don't see any errors in the Web Console Log in Safari
<!DOCTYPE html>
<html>
<body>
<h1>Switch on the Light</h1>
<img id="light" src="WebVuCoolOldBulb-2.jpg" style="width:100px" >
<button type = button
onclick="document.getElementById('light').src.show ='WebVuCoolOldBulb-2.jpg'" >Switch On the Light
</button>
<input type="button" id="onButton" value="ON" />
</body>
<script>
//document.images['light'].style.visibility = hidden;
function init() {
//document.getElementById("light").style.visibility = "hidden";
var onButton = document.getElementById("onButton");
onButton.onclick = function() {
demoVisibility() ;
}
}
function demoVisibility() {
document.getElementById("light").style.visibility = "show";
}
document.addEventListener('readystatechange', function() {
// Seems like a GOOD PRACTICE - keeps me from getting type error I was getting
// https://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object
if (document.readyState === "complete") {
init();
}
});
</script>
</html>
The visibility style property has values of visible and hidden.
There is no show value.
function init() {
document.getElementById("light").style.visibility = "hidden";
var onButton = document.getElementById("onButton");
onButton.onclick = function() {
demoVisibility();
}
}
function demoVisibility() {
document.getElementById("light").style.visibility = "visible";
}

How can I make something move in javascript?

I made a div and a button. Made a function on button's click that set div's margin (i.e move it). But how can I make it move on every click. Whenever I hit the button it do moves, (without refreshing the page) when I press that button again it don't work? How to make it move on every click of button! Here's my code:-
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
<style>
body
{
font-family:ebrima;
}
</style>
</head>
<body onload="" id="demo">
<div name="player" style="float:right; height:32px; width:32px; background:green;" id="myDiv"></div>
<form name="myForm" method="post">
<button value="MOVE" type="button" name="moveButton" onClick="move()">MOVE</button>
</form>
<script>
function move()
{
document.getElementById("myDiv").style.margin="0px 10px 0px 0px";
}
</script>
</body>
</html>
Use a variable to set the new margin each time. After using it, change the variable's value so that next time, it will move somewhere else.
var x = 10;
function move() {
document.getElementById("myDiv").style.margin="0px "+x+"px 0px 0px";
x = x+10;
}
First, don't use inline js (like onclick). Read some of these results: *Why is inline js bad?*
Instead, attach your event listener with javascript:
var myBtn = document.getElementById('my-btn');
myBtn.addEventListener('click', move);
Your code would be more readable/efficient and easier to debug like this:
//cache element reference in advance
var document.getElementById("myDiv")
function move() {
//just target the property you want to change.
myDiv.style.marginLeft = x+'px';
x = x+10;
}
Here's a little demo (click) I put together you may enjoy.
var myDiv = document.getElementById('my-div');
var myBtn = document.getElementById('my-btn');
myBtn.addEventListener('click', move);
function move(e) {
var v = r()+'px '+r()+'px '+r()+'px '+r()+'px';
myDiv.style.margin = v;
}
function r() {
return getRandomInt(0, 20);
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
And here's a more fun one using mousemove rather than click. Demo here.
I would advise using jQuery, which makes a lot of javascript quite simple.
Here's a sample jQuery animation for you:
<script>
function move() {
$("#myDiv").animate({left:'+=250px'});
}
</script>
This will shift the button over by 250px every time you trigger the function.
Note that you'll need to add jQuery to your project (which is trivial). The jQuery website has some well organized tutorials that should help you find your way around JavaScript and jQuery - happy coding!
Like this:
function move() {
var elt = document.getElementById("myDiv"),
currentMargin = parseInt(elt.style.marginRight, 10);
elt.style.marginRight = currentMargin + 10 + 'px';
}

Categories