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.
Related
I have a game with a character that goes to a random position whenever you click on it. Also, I made it so the game automatically goes into full-screen. However, sometimes, the character goes way off-screen and (because there are no scroll bars in full-screen) you cant get to it. The code is below.
<!doctype html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Alfa Slab One' rel='stylesheet'> <!-- add the font used -->
<script type="text/javascript">
function move() { //move the bird
const height = screen.height; //set the screen params
const width = screen.width;
const box = document.getElementById("bird"); //search for the bird
let randY = Math.floor((Math.random() * height) + 1); //randomise the coords
let randX = Math.floor((Math.random() * width) + 1);
box.style.transform = `translate(${randX}px, ${randY}px)`; //move the bird
addScore(); //add the score
}
</script>
<script type="text/javascript">
function getreqfullscreen(){ //full screen it. I cant really understand how it works
var root = document.documentElement
return root.requestFullscreen || root.webkitRequestFullscreen || root.mozRequestFullScreen || root.msRequestFullscreen
}
function startFullScreen() {
var pagebody = document.getElementById("main");
var globalreqfullscreen = getreqfullscreen();
document.addEventListener('click', function(e){
var target = e.target
globalreqfullscreen.call(pagebody)
}, false)
}
</script>
<script type="text/javascript">
var points = 0;
function addScore() { //add the score
var pointcount = document.getElementById("scoreCount"); //get the score counter
//var points = 45; --used for testing
points = points + 1; //increment the points
pointcount.innerText = "score: " + points;
//pointCounter.removeChild(pointCounter.childNodes[0]); --used for an older prototype
}
/**************************************/
function startCountdown() { //initiate the timer - starts when the <body> loads
startFullScreen(); //make it full screen
var time = 9999999999999999999999; //would be 60, but I made it infinite
setInterval(function() { //decrease every second
var timer = document.getElementById("Timer"); //get the timer
time = time - 1; //decrement the timer
timer.innerText = "time: " + time;
if(time == 0) { //if you finished
var continuE = prompt("Would you like to restart? (type Y for yes and N for no (case sensitive)).");
if(continuE == "Y") {
window.location.reload();
} else {
history.go(-1);
}
}
},1000);
}
</script>
<style>
html {
cursor: crosshair;
background-color: #00b0e6;
user-select: none;
}
#bird {
position: absolute;
background-color: #ffffff;
cursor: crosshair;
transition: all 1s ease-in-out;
}
#bird:hover {
invert: 0 0 12px #ff0000;
}
/*
span {
height:10px;ss
width:200px;
border:5px double red;
color:#ff00ff;
background-color:#00ffff;
}
*/
p {
color: #ff00ff;
background-color: #000000;
border: 5px double red;
height: 60px;
width: 85px;
margin: 10px;
font-family: "Times New Roman";
}
.restartButton {
border-radius: 999px;
background-color: #ff00ff;
color: #00fffff;
border: 10px double blue;
transition: all 1s ease-out;
margin-left: 50%;
margin-right: 50%;
position: relative;
cursor: help;
}
.restartButton:hover {
border-radius: 999px;
background-color: #ffffff;
color: #4500fff;
border: 10px solid red;
}
#scoreCount {
color: #aff823;
position: fixed;
top: 0;
width: 10px;
height: 10px;
}
#Timer {
color: #aff823;
position: fixed;
top: 0;
left: 200px;
width: 10px;
height: 10px;
}
span {
font-family: Alfa Slab One;
}
#main {
background-color: #00b0e6;
}
</style>
</head>
<body onload="startCountdown()" id="body">
<div id="main">
<div id="pointCounter"><span id="scoreCount"></span><span id="Timer"></span></div>
<input type="button" value="RESTART" onclick="window.location.reload();" class="restartButton"/>
<img src="https://art.pixilart.com/81a784782ea5697.png" alt="" height="50px" width="50px" id="bird" onclick="move();">
</div>
<noscript>
YOU DO NOT HAVE JAVASCRIPT ENABLED. PLEASE ENABLE JAVASCRIPT ELSE THIS WEB PAGE WILL NOT WORK.
</noscript>
</body>
</html>
Because of how stack overflow works, it doesn't go into full-screen.
P.S. I have made it infinite time, it's meant to only be 60 seconds.
I want to do a simple timer who can run from 25 to 0 and reset whenever we want to.
For this I've made a clickable div, and I want one click to start the timer and another one to reset it to 25 and stop the timer, is this possible ?
A toggable start/reset timer?
This is what I came up with so far :
HTML
<div id="result" onclick="playReset"><p id="output"></p> </div>
CSS
#result {
background: pink;
height: 200px;
width: 200px;
border-radius: 50%;
margin-left: 400px;
margin-top: 200px;
}
#result:hover {
border: black solid;
}
#output{
margin-left: 70px;
position: fixed;
font-size: 60px;
}
And the most important the JS :
var duree=25;
var toggle = true;
function playReset () {
if(toggle == true) {
var time = setInterval(function(){
duree--;
document.getElementById('output').innerHTML = duree;
}, 1000);
toggle = false
}
else if (toggle == false) {
clearInterval(time);
duree = 25;
toggle = true;
}
}
document.getElementById('output').innerHTML = duree;
Thank's if someone can give me a hand, I have SO MUCH trouble understanding setInterval/timeout, clearInterval/timeout ...
I simplified that code a little, where you can use the actual time variable to check whether it is running or not.
Stack snippet
var duree = 2;
var time;
function playReset() {
if (time) {
clearInterval(time);
time = null;
duree = 25;
document.getElementById('output').innerHTML = duree;
} else {
time = setInterval(function() {
duree--;
document.getElementById('output').innerHTML = duree;
if (duree == 0) {
clearInterval(time);
}
}, 1000);
}
}
document.getElementById('output').innerHTML = duree;
#result {
background: pink;
height: 200px;
width: 200px;
border-radius: 50%;
margin-left: 40px;
margin-top: 20px;
border: transparent solid;
}
#result:hover {
border: black solid;
}
#output {
margin-left: 70px;
position: fixed;
font-size: 60px;
}
<div id="result" onclick="playReset();">
<p id="output"></p>
</div>
When you later on have increased your skills, you likely want these stuff and their variable hidden from the global environment.
With closure one can do something like this, where only the function name is public.
Stack snippet
(function (output,duree,time) { //declared as static variables
this.init_time = duree;
this.playReset = function() {
if (time) {
clearInterval(time);
time = null;
output.innerHTML = duree = init_time; // set init value
} else {
time = setInterval(function() {
output.innerHTML = --duree;
if (duree == 0) {
clearInterval(time);
}
}, 1000);
}
}
window.playReset = this.playReset; //make it public
output.innerHTML = duree; // set init value
})(document.getElementById('output'),25); // pass in the output element and default time
#result {
background: pink;
height: 200px;
width: 200px;
border-radius: 50%;
margin-left: 40px;
margin-top: 20px;
border: transparent solid;
}
#result:hover {
border: black solid;
}
#output {
margin-left: 70px;
position: fixed;
font-size: 60px;
}
<div id="result" onclick="playReset();">
<p id="output"></p>
</div>
Here is same solution, but with the event listener and I check the count to know if a reset is to be done. You can try this here:
https://jsfiddle.net/0bej5tyn/
html
<div id="timer">
25
</div>
css
#timer{
width:150px;
height:100px;
line-height:100px;
border-radius:100px;
border:5px solid #444;
background:#555;
font-size:50px;
text-align:center;
color:#fff;
font-family:arial;
}
#timer:hover{
border:5px solid #333;
}
js
var timerButton = document.getElementById("timer");
var countStart = timerButton.innerHTML
var count = countStart;
var timer;
timerButton.addEventListener('click',function(){
if (count == countStart){
timer = setInterval(function(){
count--;
timerButton.innerHTML = count;
if (count == 0){
clearInterval(timer);
}
},1000);
}
else{
/* Reset here */
clearInterval(timer);
count = countStart;
timerButton.innerHTML = count;
}
});
I am attempting to make a simon game. I'm trying to use the glowInOrder() function to make the divs glow in the order of the array. Unfortunately only the first div in the array glows, not the others that follow. (When I say 'glow', I simply mean add effect that looks like glow using CSS.) I suspect the issue is in the glowInOrder() function, but i am unable to find the issue.
Here's my code (also on CodePen):
var colorArray = ["red", "blue", "green", "yellow", "pink"];
var player = [];
var computer = [];
var round = 0;
var randomOrder;
var myColor;
var chosenColor;
//--------------------------------------------------------//
function makeGlow(yolo) {
$(yolo).addClass('hover');
setTimeout(function() {
$(yolo).removeClass('hover');
}, 300);
}
//--------------------------------------------------------//
function makeGlowTwo(yolo) {
setTimeout(function() {
$(yolo).addClass('hover');
}, 500);
setTimeout(function() {
$(yolo).removeClass('hover');
}, 800);
}
//--------------------------------------------------------//
function newGame() {
player = [];
computer = [];
round = 0;
}
//---------------------------------------------------------//
function playerChoice() {
$('.all').on('click', function(e) {
player.push(e.target.id);
makeGlow(this);
});
};
//---------------------------------------------------------//
function computerChoice() {
randomOrder = Math.floor(Math.random() * colorArray.length);
myColor = colorArray[randomOrder];
computer.push(myColor);
chosenColor = "#" + myColor;
makeGlowTwo(chosenColor);
}
//--------------------------------------------------------//
function newRound() {
round++;
glowInOrder();
}
//---------------------------------------------------------//
function glowInOrder() {
//computerChoice();//this may not work take out if you find it doesn't
var i = 1;
var moves = setInterval(function() {
makeGlowTwo(computer[i]);
i++;
if (i >= computer.length) {
clearInterval(moves);
}
}, 400)
}
//---------------------------------------------------------//
function arraysEqual(arr1, arr2) {
if (arr1.length !== arr2.length)
return false;
for (var i = arr1.length; i--;) {
if (arr1[i] !== arr2[i])
return false;
}
return true;
}
//---------------------------------------------------------//
$(document).ready(function() {
newGame();
playerChoice();
computerChoice();
$('.all').on('click', function() {
if (arraysEqual(computer, player)) {
alert('yes');
glowInOrder();
}
});
});
* {
margin: 0;
padding: 0;
}
body {
background-color: black;
}
.all {
border-radius: 50%;
height: 100px;
width: 100px;
}
#red {
border: 5px solid red;
display: table;
margin-left: auto;
margin-right: auto;
}
#blue {
border: 5px solid blue;
border-radius: 50%;
float: right;
display: inline;
}
#green {
border: 5px solid green;
border-radius: 50%;
display: inline-block;
}
#yellow {
border: 5px solid yellow;
border-radius: 50%;
display: inline-block;
margin-left: 40px;
}
#pink {
border: 5px solid pink;
border-radius: 50%;
float: right;
display: inline;
margin-right: 40px;
}
.middleRow {
margin-top: 70px;
margin-bottom: 110px;
}
.gameContainer {
height: 500px;
width: 500px;
margin-left: 25%;
margin-top: 10%;
}
.hover {
background-color: white;
}
<div class="container">
<div class="gameContainer">
<div class="topRow">
<div id="red" class="all"></div>
</div>
<div class="middleRow">
<div id="green" class="all"></div>
<div id="blue" class="all"></div>
</div>
<div class="bottomRow">
<div id="yellow" class="all"></div>
<div id="pink" class="all"></div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Two issues that jump out:
You're only calling computerChoice once, and it adds only one entry to the array. So you have only one entry in computer at index 0.
Your glowInOrder function starts with i set to 1, which doesn't match any entry in your array. And naturally stops when you do the i >= computer.length check.
You need to ensure that computer has the correct number of entries (I'm guessing 5), and you need to start with i = 0 to start with the first one in your glowInOrder.
There are probably other logic issues in the code, but that's what's going on in relation to what you asked about. If you work through it in a debugger (there's one built into your browser) you'll be able to sort the other issues out.
I have a broadcast site, and i need hide menu when mouse not move, and show it, when mouse move.
It works almost perfect, except one bug - menu hides only on second time if i hover it.
var timedelay = 1;
var _delay = setInterval(delayCheck, 500);
$('.parent').on('mousemove', showAllEvent);
function delayCheck() {
if (timedelay == 3) {
$('.hide').fadeOut();
timedelay = 1;
}
timedelay = timedelay + 1;
}
function showAllEvent() {
$('.hide').fadeIn();
timedelay = 1;
clearInterval(_delay);
_delay = setInterval(delayCheck, 500);
}
.hide {
height: 100px;
width: 100px;
border: 1px solid red;
color: black;
}
.parent {
width: 100%;
height: 100vh;
border: 1px solid red;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div class='parent'>
if you hover me ".hide" is disappearing
<div class='hide'>if you hover me i'm hide on second time</div>
</div>
So this is a kind of solution that feels like a hack that I implemented with the concept of pointer-events:none as you need to click the menu when it's displayed. So on mousemove you add a class show which enables the click and sets the opacity of the menu div to 1 and when mouse is still the div's opacity is set to 0 and pointer events are set to none.
I used transition property of css instead of jquery's fadeIn and fadeOut methods.
var timedelay = 1;
var _delay = setInterval(delayCheck, 500);
$('.parent').on('mousemove', showAllEvent);
function delayCheck() {
if (timedelay == 3) {
$('.hide').removeClass('show');
timedelay = 1;
}
timedelay = timedelay + 1;
}
function showAllEvent() {
$('.hide').addClass('show');
timedelay = 1;
clearInterval(_delay);
_delay = setInterval(delayCheck, 500);
}
.hide {
height: 100px;
width: 100px;
border: 1px solid red;
color: black;
pointer-events: none;
opacity: 0;
transition: opacity 1.5s ease-in-out;
}
.parent {
width: 100%;
height: 100vh;
border: 1px solid red;
text-align: center;
}
.show {
opacity: 1;
pointer-events: all;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div class='parent'>
if you hover me ".hide" is disappearing
<div class='hide'>if you hover me i'm hide on second time</div>
</div>
Just set interval to 1 instead of 500, which in miliseconds, and use show() and hide() methods instead of fadeIn() and fadeOut() because they are animating in 400 miliseconds by default.
I also added display:none to .hide CSS class, now it's hidden at initial.
Now, the inner div is only visible when mouse moves on the upper div.
var timedelay = 1;
var _delay = setInterval(delayCheck, 1);
$('.parent').on('mousemove', showAllEvent);
function delayCheck() {
if (timedelay == 3) {
$('.hide').hide();
timedelay = 1;
}
timedelay = timedelay + 1;
}
function showAllEvent() {
$('.hide').show();
timedelay = 1;
clearInterval(_delay);
_delay = setInterval(delayCheck, 1);
}
.hide {
height: 100px;
width: 100px;
border: 1px solid red;
color: black;
display:none;
}
.parent {
width: 100%;
height: 100vh;
border: 1px solid red;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div class='parent'>
if you hover me ".hide" is disappearing
<div class='hide'>if you hover me i'm hide on second time</div>
</div>
The code you provided is not complete. I fixed that (I hope). The main issue is in your defining the event handler for mousemove. See working example below:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript">
</script>
<script type="text/javascript">
var timedelay = 1;
var _delay = setInterval(delayCheck, 500);
$(document).on('mousemove','.parent',function(e){
$("span").text(event.pageX + ", " + event.pageY);
clearInterval(_delay);
$('.hide').fadeIn();
timedelay = 1;
_delay = setInterval(delayCheck, 500);
});
function delayCheck() {
if (timedelay == 3) {
$('.hide').fadeOut();
timedelay = 1;
}
timedelay = timedelay + 1;
}
</script>
<style type="text/css">
.hide {
height: 100px;
width: 100px;
border: 1px solid red;
color: black;
}
.parent {
width: 100%;
height: 100vh;
border: 1px solid red;
text-align: center;
}
</style>
</head>
<body>
<span></span>
<div class='parent'>
if you hover me ".hide" is disappearing
<div class='hide'>if you hover me i'm hide on second time</div>
</div>
</body>
</html>
You can see it run here: https://jsfiddle.net/oeu77wgv/
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.