Javascript variable declared in if statement wont change the global variable - javascript

I'm currently working on my html works, where I try to change the video source using Javascript.
Here is my video element.
<div>
<video id="songVid" onmouseover="controlsVid()">
<source src="../front-end/assets/media/video/vidio.mp4.mp4" >
<track default src="../front-end/assets/media/subtitle/New folder/sub.vtt">
</video>
</div>
And here is the javascript code.
var x = 1;
var nextVid = document.getElementById("nextVid");
nextVid.onclick = function() {
if (x === 1) {
opVid.src = "../front-end/assets/media/video/Moon Halo Honkai Impact 3rd Valkyrie Theme_480p.mp4";
opVid.play();
var x = x + 1;
}
else if (x === 2) {
opVid.src = "../front-end/assets/media/video/Honkai Impact 3rd Valkyrie Theme Rubia Performed by Zhou Shen Honkai Impact 3rd_480p.mp4";
opVid.play();
}
else {
alert("Something went wrong");
}
}
var backVid = document.getElementById("backVid");
backVid.onclick = function() {
if (x === 0) {
alert("End of the playlist");
}
else if (x === 2) {
opVid.src = "../front-end/assets/media/video/Moon Halo Honkai Impact 3rd Valkyrie Theme_480p.mp4";
opVid.play();
x = x - 1;
}
else if (x === 1) {
opVid.src = "../front-end/assets/media/video/COVER Tak Ingin Usai Mythia Batford _480p.mp4";
opVid.play();
x = x - 1;
}
}
So, the script will run when these button clicked.
<div class="css-button-center">
<button class="css-button" id="backVid"><i class="gg-play-slow-o flip"></i></button>
<!-- <button class="css-button" id="slowVid"><i class="gg-play-backwards"></i></button> -->
<button onclick="playVid()" class="css-button"><i class="gg-play-play-o"></i></button>
<button onclick="pauseVid()" class="css-button"><i class="gg-play-pause-o"></i></button>
<button onclick="stopVid()" class="css-button"><i class="gg-play-stop-o"></i></button>
<!-- <button class="css-button" id="fastVid"><i class="gg-play-forwards"></i></button> -->
<button class="css-button" id="nextVid"><i class="gg-play-fast-o"></i></button>
</div>
The script has a variable x where it's value will increase by 1 everytime the button with id next/back vid clicked. But, on these script, the value of x wont increase. Everytime the button clicked, it still uses the var x = 1; rather than the x value inside the if function. so it'll only change the source with the 2nd source and wont continue to the next src. Is there any solution for the javascript? because i think the problem is only on var x inside the Javascript.

In your next function you have declared a new variable which happens to be called 'x'. By using the var keyword you opened a new spot in memory and this variable is scoped to the function nextVid.onClick().
If you use VisualStudio code or webstorm to write your code you will probably get a little warning that it hides the global member.
Looking at your logic, is it correct that you want to show different videos when x == 2 based on clicking the next or previous button? If not and that is a mistake i would refactor the repeated structure to something like this
var x = 1;
var nextVid = document.getElementById("nextVid");
// better yet make this a named function
nextVid.onclick = function() {
videoToPlay();
x += 1;
}
var backVid = document.getElementById("backVid");
// better yet make this a named function
backVid.onclick = function() {
videoToPlay();
x -= 1;
}
function videoToPlay() {
// better yet pass in your video object instead of looking for it from a higher scope
// better yet you could have an array of your videos and then just look up the index based on the value of 'x'
switch (x) {
case x === 0:
alert("start of play list");
break;
case x === 1:
opVid.src = "../front-end/assets/media/video/Moon Halo Honkai Impact 3rd Valkyrie Theme_480p.mp4";
break;
case x === 2:
opVid.src = "../front-end/assets/media/video/Honkai Impact 3rd Valkyrie Theme Rubia Performed by Zhou Shen Honkai Impact 3rd_480p.mp4";
break;
case x === 3:
opVid.src = "../front-end/assets/media/video/COVER Tak Ingin Usai Mythia Batford _480p.mp4";
break;
default:
alert("something went wrong");
}
opVid.play();
}

Related

Adding a reset button to a Javascript HTML game?

I am second semester, taking a class in Javascript. Basically, we were given the HTML and CSS for a website, and it is supposed to do the following:
It's a number game. The computer generates a number, and you have ten tries to guess this number. If you get to zero, the computer wins, and there is a reset button which should reset all the variables and start again. Only problem is, I cannot for the life of me figure out how to reset the countDown variable after the score reaches 0. Please help. Also we are using only pure Javascript for this course for now. I don't want to cheat, I am more trying to figure out what the issue is that's holding me back.
var countDown = 10;
var computerNumber = Math.floor((Math.random() * 501) + 1);
function generate() {
playerNumber = document.getElementById("guess").value;
if (computerNumber == playerNumber && countDown > 0) {
alert("Congratulations! You've won!");
} else if (playerNumber < computerNumber && countDown > 0) {
countDown--;
document.getElementById("guesses").value = countDown;
document.getElementById("result").value = "Too Low";
} else if (playerNumber > computerNumber && countDown > 0) {
countDown--;
document.getElementById("guesses").value = countDown;
document.getElementById("result").value = "Too High";
} else if (countDown == 0) {
alert("Game Over. The Number Was " + computerNumber);
}
}
function reset() {
countDown = 10;
computerNumber = Math.floor((Math.random() * 501) + 1);
}
In the reset function, you would need to update the element that displays the countDown in the HTML
Here you need to add the reset button in the html:
<input type="button" class="reset-button" value="Reset Count">
Then grab that button in your JS below the reset function and attach an eventListener that fires the reset function when clicked:
const resetBtn = document.querySelector('.reset-button')
resetBtn.addEventListener('click', reset )
And that's it.
You would probably want the count displayed on the page, too. You could add a line in the reset function that pushes the new value of countDown into the html (with element.textContent = countDown.toString(), for example)
If you take a JS class in 2021 you should definitely use const and let instead of var, and let your teacher know why. Using var works, though, but will show a future employer that you're out of touch with what's going on in the JS world.

pausing and resuming a setTimeout program

Before yesterday I literally have never written anything with Javascript. I am brand new at this. I have written macros in excel but I am very familiar with computers. I am trying to write a program so I can have an HTML file open in my browser that will have a button. When I press the button I want it to count down from a random number, and then when the count down is over it will play a beep and randomly pick a text from a list of items.
I have most of this down and working (remember this is my first ever program) but I want to incorporate a feature that allows me to pause the timer so I can resume it later. I have included some numbers here that work but this is just testing.
I have been looking online at other "pause and resume" style questions but I'm a little confused. This is super new to me.
Here is my program so far....
<html>
<body>
<h2>Javascript CART breakdown calculator</h2>
<p id="demo"></p>
<p id="breakdown_item"></p>
<button onclick="setTimeout(myFunction, my_random_number*1000);">start timer</button>
<script>
var my_random_number, low, high;
low = 1;
high = 5;
my_random_number = Math.floor(Math.random() * high) + low;
document.getElementById("demo").innerHTML = my_random_number;
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
function myFunction(frequency, duration, callback) {
duration = 10000 / 1000; // the 10000 used to be 'duration'
// create Oscillator node
var oscillator = audioCtx.createOscillator();
oscillator.type = 'square';
oscillator.frequency.value = 500; // value in hertz
oscillator.connect(audioCtx.destination);
oscillator.onended = callback;
oscillator.start(0);
oscillator.stop(audioCtx.currentTime + duration);
var random_breakdown_event, low_event, high_event;
low_event = 1
high_event = 9
random_breakdown_event = Math.floor(Math.random() * high_event) + low_event;
var text
if (random_breakdown_event == 1) text = "blown engine";
if (random_breakdown_event == 2) text = "broken transmission";
if (random_breakdown_event == 3) text = "broken suspension";
if (random_breakdown_event == 4) text = "broken halfshaft";
if (random_breakdown_event == 5) text = "broken cv joint";
if (random_breakdown_event == 6) text = "broken wings";
if (random_breakdown_event == 7) text = "electrical misfire";
if (random_breakdown_event == 8) text = "broken fuel pump";
if (random_breakdown_event == 9) text = "change battery";
document.getElementById("breakdown_item").innerHTML = text
}
</script>
</body>
</html>
I would like to incorporate a way to make this timer pause and resume.
A couple of comments in regards your code.
1) Button event management (valid for all event management)
Try to manage your events unobstrusively (although there's a new tendency to do it inline, for instance with React Components). What unobstrusively means? It means you define your code events outside of the HTML, within the javascript block.
For instance, if you assign the id="button-timer" to your button you can do something like this:
<script>
var button = document.getElementById('button-timer');
button.addEventListener('click', myFunction);
</script>
Then inside your myFunction you can specify the setTimeout. The setTimeout function returns a value you can later use to pause/remove the timeout with a function named clearTimeout(<timer-reference>). So this gives you a hint on how to pause/control the timeouts.
2) Instead of so many if's() just use a Switch statement.
So you would do something like:
switch(random_breakdown_event){
case 1 : // some code;
break;
case 3 : // some code
break;
default: // default case action
}
So hinting you on how to manage a pause/stop process,
<button id="button-timer">Start timer</button>
<script>
var timer=null;
function myFunction(){
// Your function does stuff
}
function buttonEventHandler(){
timer = setTimeout('myFunction', <some-random-time>);
}
function pauseStop(){
clearInterval(timer);
}
var button = document.getElementById('button-timer');
button.addEventListener('click', buttonEventHandler);
</script>
This would be a general schema on how your'd control a timer pause action in js code.

JavaScript Choose your own adventure game random number function in loop problem

I'm writing a choose your own adventure program where If a specific option is chosen (example to wait) the user gets a random number between 1-10 to do push ups(the push-ups would be the user clicking on the prompt "ok" button however many times the random number is equal to) here's my code so far but I keep getting errors. I'm a complete noob so go easy on me.
var count = Math.floor((Math.random() * 10) + 1);
var setsOf10 = false;
function pushUps() {
alert("Nice! Lets see you crank out " + pushUps + "!");
}
if (setsOf10 == pushUp) {
alert("Nice! Lets see you crank out " + pushUp + "!");
setsOf10 = true;
}
for (var i=0; i<count; i++){
pushUps();
}
else {
alert("Really, thats it? Try again");
}
while ( setsOf10 == false);
}
After playing with this some more I can tell i'm close but still don't have it. and again, I'M NOT ASKING YOU TO SOLVE THIS FOR ME JUST NEED POINTERS AS TO WHAT IM DOING WRONG OR MISSING. Here's what I have, Its giving me my random number I just need it to allow me to click the "ok" button however many times the random number has assigned me.
var pushUpSets = Math.floor((Math.random() * 10) + 1);
function pushUps(){
alert(pushUpSets);
if (pushUpSets < 3){
var weak = "Thats it? Weak sauce!";
alert(weak);
}
else{
alert("Sweet lets get some reps in!");
}
for (i=0; i>3; i++){
pushUps(pushUpSets);
}
}
Here, the make a choice button is just dummy to allow us to go to do push ups. Each click decrements our count.
// This is important, we use this event to wait and let the HTML (DOM) load
// before we go ahead and code.
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#choice').addEventListener('click', makeChoice);
});
function makeChoice() {
// Call a method to set random pushups and setup the click event
setUpPushUp();
// Here we change the display style of the push up section so that it shows to the player.
document.querySelector('.activity').style.display = 'block';
}
// The pushups variable is declared at the document level
// This way our setUpPushUp and doPushUp functions have easy access.
let pushUps = 0;
function setUpPushUp() {
// Create a random number of pushups, in sets of 10.
// We add an extra 1 so we can call the doPushUp method to initialize.
pushUps = (Math.floor((Math.random() * 10)+1)*10)+1 ;
// Add a click event to the push up button and call our doPushUp method on each click.
document.querySelector('#push').addEventListener('click', doPushUp);
// This is just an init call, it will use the extra 1 we added and place test in our P tag.
doPushUp();
}
function doPushUp() {
// Get a reference to our output element, we will put text to player here.
let result = document.querySelector('p');
// They have clicked, so remove a push up.
pushUps--;
// See if the player has done all the required push ups (i.e. pushUps is 0 or less.)
if (pushUps > 0) {
result.innerText = `You need to crank out ${pushUps} pushUps`;
} else {
result.innerText = 'Nice work!';
}
}
.activity {
display: none;
}
<button id="choice">Make a choice !</button>
<div class="activity">
<p></p>
<button id="push">Push</button>
</div>

JavaScript to toggle relay through website

I apologize I am new to javascript. I am trying to toggle a relay from a website using setInterval. The relay is a Sainsmart with 16 channels and it is connected to an arduino controlled by a raspberry pi. The goal is to eventually have three independent relays toggling at particular intervals. However, every attempt to get the first one working fails. In addition, every time I add a setInterval within a function or global, freezes the live streaming video from my ip camera. I am using a sandbox key through ably.
The html code and script work to toggle the relay on, and then a second button will toggle it off, but I need a single button to accomplish it.
The button initiates the sequence with a counter dictating whether the relay toggles on or off. It is set up to toggle on with an even number and off with an odd number. Any help would be greatly appreciated.
Here is the updated code I am trying to work with.
<div class="grid-item"><button id="37" onclick="startOnOff()">Start</button>
</div>
<script src="http://cdn.ably.io/lib/ably.min-1.js"></script>
<script>
var count = 0;
function startOnOff() {
var on = "37" + "on";
var off = "37" + "off";
if (counter % 2 == 0) {
toggleRelay(on);
count += 1;
} else if (count % 2 == 1) {
toggleRelay(off);
}
setInterval(startOnOff, 2000);
}
You have count in a few places and counter in one place where it should be count.
Assuming toggleRelay() is defined somewhere else in your code, try this:
var count = 0;
var on = "37" + "on";
var off = "37" + "off";
function startOnOff() {
if (count % 2 == 0) {
toggleRelay(on);
} else {
toggleRelay(off);
}
count += 1;
setTimeout(startOnOff, 2000);
}
count += 1; should be outside of the if conditional statement,
and use setTimeout() when calling startOnOff() recursively.

How do I hide a div or image after 20 seconds of flashing in Javascript?

I am busy making a memory game, where an image is to be displayed to the user, and after some 10 seconds of the image flashing, it should hide and four options are to be shown for the user to choose either the correct or incorrect answer.
So far, all I have accomplished is to load the images and cycle through all the puzzles that my code can find.
What I'm trying to do now is to make the image flash and hide after some time, while also just refreshing that section of the page, and not the entire page.
I am using C# and a user control on my page.
What I have tried so far is only
<script>
var x;
function BlinkImage() {
x = 1;
setInterval(change, 2000);
}
function change() {
if (x === 1) {
var image = document.getElementById('<%=imgMain.ClientID %>');
image.visible = false;
x = 2;
}
else {
var image = document.getElementById('<%=imgMain.ClientID %>');
image.visible = true;
x = 1;
}
}
</script>
And on loading my puzzle for that instance (in code behind)
Page.ClientScript.RegisterStartupScript(typeof(game), "Start", "<script language=javascript> BlinkImage(); </script>");
Which does fire, as I can step through the code in debugging on Firefox. But my image does not flash or blink. I understand I am just using visiblity as my "blinker". I don't know what else to use exactly.
What can I do to make the image flash or blink for, say 20 seconds, then hide the image after that time has passed? Then repeat the process once the user has made a choice.
You can try the following (comments in code):
var blinkInterval = setInterval(change, 2000), // set the interval into a variable
image = document.getElementById('test'), // replace test with your client id: <%=imgMain.ClientID %>
x = 1;
function change() {
if (x % 2 === 1) { // see if it is odd or even by modding by 2 and getting remainder
image.style.display = 'none';
} else {
image.style.display = 'block';
}
x++; // increment x
if (x === 10) { // should have happened 10 times (which is 20 seconds with your intervals being at 2 seconds)
clearInterval(blinkInterval); // clear the interval (should end hidden as odd is display none and we clear beforethe 20th is run)
}
}
<div id="test">test</div>
After the code has finished, wherever the user is making their selection, you just need to reset the blinkInterval variable:
blinkInterval = setInterval(change, 2000); // notice no need for the var declaration when you reset this
Use style attribute and change if visible/hidden
function change() {
var image = document.getElementById('<%=imgMain.ClientID %>');
//check if visible
if (image.style.visibility=="visible") {
image.style.visibility="hidden";
}
else {
image.style.visibility="visible";
}
}
;
Try this:
function flashAndHide(img_id){
var img = $("#"+img_id);
var x = 0;
var inter = setInterval(function(){
if(x % 2 == 0){
img.hide();
}else{
img.show();
}
x += 1;
}
},1000);
if(x === 20){
img.hide();
clearInterval(inter);
}
}
Haven't tested this, but it should work,

Categories