I have a question about changing variables.
I'm making a scoreboard for table tennis. I'm trying to show the players who has to serve. Everytime the x-key gets pressed (/when a point is scored), I check if the right to serve has to change. For this example I removed that bit.
What I'm trying to do:
Everytime an input is detected (keyboard event), the opacity of the first variable is changed to be the opposite from what is was, as well as the second variable.
Perhaps, you could think of it like a railroad crossing.
What is happening:
Only the opacity of the first variable is 1. This is due to the code running from top to bottom. It sees that the currentActionPlayer1 variable is 0, so it makes it 1. But when it reaches the if statement 'currentActionPlayer2 == 0', that is true. So the currentActionPlayer1 variable becomes 0, and cAP2 becomes 1 again.
I don't really know how to explain it any better.
var currentActionPlayer1 = 1;
var currentActionPlayer2 = 0;
window.addEventListener("keyup", checkKeyUp);
function checkKeyUp(keyUp) {
if (keyUp.keyCode == "88") { //X
changeActionPlayer();
}
}
function changeActionPlayer() {
if (currentActionPlayer1 == 1) {
currentActionPlayer1 = 0;
currentActionPlayer2 = 1;
changeActionIcon();
}
if (currentActionPlayer2 == 1) {
currentActionPlayer1 = 0;
currentActionPlayer1 = 1;
changeActionIcon();
}
}
function changeActionIcon() {
if (currentActionPlayer1 == 1) {
document.getElementById('actionP1').style.opacity = "1";
document.getElementById('actionP2').style.opacity = "0.2";
}
if (currentActionPlayer2 == 1) {
document.getElementById('actionP1').style.opacity = "0.2";
document.getElementById('actionP2').style.opacity = "1";
}
}
<html>
<head>
</head>
<body>
<p id='actionP1' style='opacity: 0.2'>action</p>
<p id='actionP2' style='opacity: 0.2'>action</p>
</body>
</html>
If I right understand, you need something like this one?
var currentActionPlayer1 = 1;
var currentActionPlayer2 = 0;
window.addEventListener("keyup", checkKeyUp);
function checkKeyUp(keyUp) {
if (keyUp.code == "KeyX") { //X
changeActionPlayer();
}
}
function changeActionPlayer() {
if (currentActionPlayer1 == 1) {
currentActionPlayer1 = 0;
currentActionPlayer2 = 1;
changeActionIcon();
} else if (currentActionPlayer2 == 1) {
currentActionPlayer2 = 0;
currentActionPlayer1 = 1;
changeActionIcon();
}
}
function changeActionIcon() {
if (currentActionPlayer1 == 1) {
document.getElementById('actionP1').style.opacity = "1";
document.getElementById('actionP2').style.opacity = "0.2";
}
if (currentActionPlayer2 == 1) {
document.getElementById('actionP1').style.opacity = "0.2";
document.getElementById('actionP2').style.opacity = "1";
}
}
<html>
<head>
</head>
<body>
<p id='actionP1' style='opacity: 0.2'>action</p>
<p id='actionP2' style='opacity: 0.2'>action</p>
</body>
</html>
Related
I have a project that needs darkmode & lightmode, so I made a btn that when onclick it calls a function named swipe12;
and I have a var name swipe = 1;
only all the elements set dark but they never become white;
I think I can use doWhile but idk how.
var swipe = 1; // 0 => lightmode & 1 => DarkMode
function swipe12(swip = swipe) {
if (swip === 0) {
console.log(swip);
const swipeLight = document.getElementsByClassName('swipeLight');
for (let x = 0; x < swipeLight.length; x++) {
console.log('white')
swipeLight[x].style.backgroundColor = 'white';
}
var swip = 1;
// return true;
}
if (swip === 1) {
console.log(swip);
const swipeLight = document.getElementsByClassName('swipeLight');
for (let i = 0; i < swipeLight.length; i++) {
console.log('black')
swipeLight[i].style.backgroundColor = 'black';
}
var swip = 0;
// return true;
}
}
This is a possible solution for your problem,
by using the logical not operation (!) you can turn the swipe variable from 0 to 1 and vise versa, this transformation should be done whenever you call your function in my case am using a button to demonstrate
ignore the css part its just for demonstration
let swipe = 0; // 0 => lightmode & 1 => DarkMode
const swipeLight = document.querySelectorAll('.swipeLight');
const btn = document.querySelector('#changeTheme');
// Call your function like this
btn.addEventListener('click', () => {
// 0 will turn to 1 and vise versa
swipe = !swipe;
swipe12(swipe)
});
function swipe12(mode){
swipeLight.forEach(element => {
// if swipe = 1 // if swipe = 0
swipe ? element.style.backgroundColor = 'black' : element.style.backgroundColor = 'white';
});
}
div {
height: 30px;
width: 100px;
}
<div class="swipeLight"></div>
<br>
<div class="swipeLight"></div>
<br>
<div class="swipeLight"></div>
<button id="changeTheme">Change theme</button>
You are trying to swicth the value of swip which is local variable. Change it to swipe. also remove var. re-declaring makes the variable local
var swipe = 1;
function swipe12(swip = swipe){
if(swip === 0){
const swipeLight = document.getElementsByClassName('swipeLight');
for(let x = 0; x < swipeLight.length; x++) {
console.log('white')
swipeLight[x].style.backgroundColor = 'white';
}
// remove var and change to swipe
swipe = 1;
}
if(swip === 1){
console.log(swip);
const swipeLight = document.getElementsByClassName('swipeLight');
for(let i = 0; i < swipeLight.length; i++) {
console.log('black')
swipeLight[i].style.backgroundColor = 'black';
}
// remove var and change to swipe
swipe = 0;
}
}
I refactored the code a little bit, hope this helps. Feel free to ask any questions
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript">
// 0 for light, 1 for dark
var darkMode = 0;
const elements = document.getElementsByClassName("swipeLight");
function swipe() {
darkMode = !darkMode;
for (let i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = darkMode ? "black" : "red";
}
}
</script>
</head>
<body>
<button onclick="swipe()">Switch theme</button>
<div class="swipeLight">Text</div>
</body>
</html>
I have written in HTML and Javascript a webpage that cycles through an image of a lion and a frog. I have set 2 buttons to start and stop the images from cycling every 500ms. My problem is I am unsure how to go around creating a score function that counts the number of times a specific image is clicked. For example, if the frog image is clicked I want the score to +1 and if the lion image is clicked I want the score to -1.
Here is my code.
<html>
<head>
<title>Question 2</title>
<script>
var images = ["frog.jpg", "lion.jpg"] //I Created an array with both images inside
var imgInterval;
var imgi = 'empty';
var score = document.getElementById('score');
function start(){
imgInterval = setInterval(displayImage, 500); //Sets an interval for the func displayImage and for it to loop ever 500ms
}
function displayImage() {
if (imgi == 'empty') { //If the index is empty set the interval to 0 or frog.jpg
imgi = 0;
} else if (imgi == 0) { // If the index is set to 0 set it to 1 or lion.jpg
imgi = 1;
} else if (imgi == 1) { // If the idex is set to 1 set it back to 0, this creates a loop that will be run every 500ms
imgi = 0;
}
document.getElementById('image').src = images[imgi];
}
function stop(){
clearInterval(imgInterval);
}
function scoreNumb() { //This is where i think i am having issues and am unsure what to do.
if (imgi.onclick == 0) {
score + 1;
}
}
</script>
</head>
<body>
<button onclick=start()>Start Animation</button>
<button onclick=stop()>Stop Animation</button>
<br/> <br/>
<span>
<img id="image" onclick=scoreNumb() width="250px" />
</span>
<br/>
<span id="score">0</span>
</body>
</html>
replace your function scoreNumb with mine
<script>
...
var score = document.getElementById('score');
var valueScore = 0; /*created this*/
...
function scoreNumb() { //This is where i think i am having issues and am unsure what to do.
/*if (imgi.onclick == 0) {
score + 1;
}*/
/*0 = frog AND 1 = lion*/
if (imgi == 0){/*+1*/
valueScore++;
}else {
valueScore--;
}
console.log("click", valueScore);
document.getElementById('score').textContent = valueScore;
}
You are nearly there. You just need to check which image was clicked by checking the img src
If the image src is lion then you can increase the totalScore count variable update the count as well using textContent method.
function scoreNumb(e) {
if (e.getAttribute('src') == 'https://via.placeholder.com/150') {
totalScore++
} else {
totalScore--
}
score.textContent = totalScore
}
Working Demo:
var images = ["https://via.placeholder.com/150", "https://via.placeholder.com/200"] //I Created an array with both images inside
var imgInterval;
var imgi = 'empty';
var score = document.getElementById('score');
var totalScore = 0
function start() {
imgInterval = setInterval(displayImage, 1000); //Sets an interval for the func displayImage and for it to loop ever 500ms
}
function displayImage() {
if (imgi == 'empty') { //If the index is empty set the interval to 0 or frog.jpg
imgi = 0;
} else if (imgi == 0) { // If the index is set to 0 set it to 1 or lion.jpg
imgi = 1;
} else if (imgi == 1) { // If the idex is set to 1 set it back to 0, this creates a loop that will be run every 500ms
imgi = 0;
}
document.getElementById('image').src = images[imgi];
}
function stop() {
clearInterval(imgInterval);
}
function scoreNumb(e) { //This is where i think i am having issues and am unsure what to do.
if (e.getAttribute('src') == 'https://via.placeholder.com/150') {
totalScore++
} else {
totalScore--
}
score.textContent = totalScore
}
<html>
<head>
<title>Question 2</title>
<script>
</script>
</head>
<body>
<button onclick=start()>Start Animation</button>
<button onclick=stop()>Stop Animation</button>
<br /> <br />
<span>
<img id="image" onclick=scoreNumb(this) width="250px" />
</span>
<br />
<span id="score">0</span>
</body>
</html>
Change this variable declaration from:
let score = document.getElementById('score');
to this:
let score = 0;
then in the function named scoreNumb() change the following :
if (imgi.onclick == 0) {
score + 1;
}
to this :
if (imgi === 0) {
score += 1;
}
else{
score -= 1;
}
// Here you can update your html code with getElementById.
console.log(score)
I am very new to web development so I'm sorry if I sound stupid.
I am trying to make variable change after a certain amount of time with HTML 5/JavaScript.
This is the code i was using
var myVar = setInterval(OnScreenVariables, 100);
var myVar = setInterval(Interval, 1000);
function Interval() {
if (x == 1) {
i++;
if (i > 3) {
var i = 1;
var x = 0;
}
}
}
function OnScreenVariables() {
document.getElementById("i").innerHTML = i;
document.getElementById("x").innerHTML = x;
}
<p id="x">hi</p>
<p id="i">hi</p>
<div style="backgound-color:blue;" onclick="x=1;">press me</div>
But it is not working. Could you tell me why it's not working and if there is a better way to do this.
Several problems.
https://www.w3schools.com/js/js_hoisting.asp
https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
var i and var x are being hoisted, so this:
function Interval() {
if (x == 1) {
i++;
if (i > 3) {
var i = 1;
var x = 0;
}
}
}
behaves like
function Interval() {
var i;
var x; // x is always undefined
if (x == 1) {
i++; // undefined++ = NaN
if (i > 3) {
i = 1;
x = 0;
}
}
}
And after fixing that, i and x are not declared when the script is run, so they are instead using the DOM elements with id i and x. DOMElement++ = NaN, and DOMElement.toString() is equal to a string representing the DOM element's internal name.
I would recommend using let and const (which have better scoping and less chances for unexpected behavior, and can be scoped inside for loop closures for example) instead of var, and getting in the habit of making sure you use var, let, const and plan to keep your variables deliberately scoped and declared wherever you use them.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<p id="x">hi</p>
<p id="i">hi</p>
<div style="backgound-color:blue;" onclick="x=1;">press me</div>
<script>
var myVar = setInterval(OnScreenVariables, 100);
var myVar = setInterval(Interval, 1000);
var i = 1, x = 0;
function Interval() {
console.log(i,x)
if (x == 1) {
i++;
if (i > 3) {
i = 1;
x = 0;
}
}
}
function OnScreenVariables() {
document.getElementById("i").innerHTML = i;
document.getElementById("x").innerHTML = x;
}
</script>
</body>
</html>
The script must have to print 'Hello', then 'Good bye', because of the entries on function call. But only prints once. Why?
What's wrong here bellow.
PD: Now it doesn't work. It does if i comment the recursion call line
<html>
<head>
</head>
<body>
<script type="text/javascript">
function writing(i,first,second) {
len=arguments.length;
if (i<=len) {
current=arguments[i];
c=0;
inter=setInterval(function() {
if (c>=current.length) {
clearInterval(inter);
} else {
field=document.getElementById('div1');
field.innerHTML+=current[c];
c+=1;
}
},200);
}
i<len?writing(i+1,first,second):writing(i=0,first,second);
}
writing(1,'Hello','Good bye');
</script>
<div id="div1"></div>
</body>
There are so many problems with the code , first was it was infinite loop (never ending) , second was variable declaration , and others...
Here I have attached the snippet , please run and check, if its that you are looking for.
I have to add setTimeout for fullfill your requirement.
var interval_counter = 0;
function writing(i, first, second) {
var len = arguments.length;
if (i != 0 && i <= len) {
var current = arguments[i];
var c = 0;
setTimeout(function() {
var inter = setInterval(function() {
if (c >= current.length) {
clearInterval(inter);
} else {
field = document.getElementById('div1');
field.innerHTML += current[c];
c += 1;
}
}, 200);
}, 200 * interval_counter);
interval_counter = interval_counter + current.length;
i < (len - 1) ? writing(i + 1, first, second) : writing(i = 0, first, second);
} else {
return false;
}
}
writing(1, 'Hello', 'Good bye');
<div id="div1"></div>
I have created a script, which holds a div-container. The moment i move the mouse quickly left and right on the container, it does not work anymore. Google Chrome does not process it properly either, why?
<html>
<head>
<title>move container</title>
<script type="text/javascript">
var position=0;
var interval;
var isRunning = false;
function moveRight0()
{
if (position => 20){
position = 19;
}
if (isRunning==true){
isRunning = false;
return;
}
if (isRunning==false) {
isRunning = true
document.getElementById("container0").style.left = position+"px";
position++;
if(position==20)
{
clearInterval(interval);
interval=0;
}
}
}
function moveLeft0()
{
if (position < 1){
position = 0;
}
if (isRunning==true){
isRunning = false;
return;
}
if (isRunning==false) {
isRunning = true
document.getElementById("container0").style.left = position+"px";
position--;
if(position<1)
{
clearInterval(interval);
interval = 0;
}
}
}
function al(){
alert(interval);
}
function setIntervalLeft0()
{
interval = setInterval(moveLeft0,10);
}
function setIntervalRight0()
{
interval = setInterval(moveRight0,10);
}
</script>
</head>
<body>
<div onmouseover="setIntervalRight0()" onmouseout="setIntervalLeft0()" id="container0" style="width:50px; height:20px; position:absolute; z-index:1; top:0px; left:0px">text</div><br><br>
<input type="button" onclick="al()" name="zeige">
</body>
</html>
Thank you for your response!
Im dont really understand what your code is supposed to do, but i made a few minor changes and it works on chrome.
Note: you have an error in your code
if (position => 20){
//=> is invalid, use >= instead
http://jsfiddle.net/2r9usf4h/