Uncaught ReferenceError: variable is not defined? (no jQuery involved) - javascript

this is my first question on stackoverflow.
I am learning about javascript and decided to start a project.
I'm making a scoreboard to keep track of the score during table tennis. I managed to make this work and decided to add some features like a match history and show which player has to serve.
However, I'm stuck with the ReferenceError. In most other questions about this, people just forgot to add the variable or it had something to do with jquery. I don't think that's my problem.
In table tennis the player with serve changes every 2 points. I decided to add scorePlayer1 and scorePlayer2 to make a totalScore. When this is divided by 2, I can check if this is an integer, and if it is, the player with serve changes. However, whatever I try, the variable totalScore is not defined.
I learned HTML/CSS first at w3schools.com and later used it to learn javascript.
I have pasted the code into multiple syntax checkers, but got no errors.
The button is there to pick the serve player. Then, I want to swith the right to serve to the opposite player after 2 points are scored. I tried this with function changeServePlayer. However, when I try this in Chrome and type in the console: totalScore, it returns the Uncaught ReferenceError. Why does this happen or is there a better way to achieve the goal?
Here's code I used:
var currentScorePlayerOne = 0;
var currentScorePlayerTwo = 0;
var currentServePlayer;
var totalScore;
window.addEventListener("keyup", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode == "90" && currentScorePlayerOne != 0) { //Z
document.getElementById('scorePlayerOne').innerHTML = --currentScorePlayerOne;
changeServePlayer();
changeServeIcon();
}
if (key.keyCode == "88") { //X
document.getElementById('scorePlayerOne').innerHTML = ++currentScorePlayerOne;
changeServePlayer();
changeServeIcon();
}
if (key.keyCode == "78" && currentScorePlayerTwo != 0) { //N
document.getElementById('scorePlayerTwo').innerHTML = --currentScorePlayerTwo;
changeServePlayer();
changeServeIcon();
}
if (key.keyCode == "77") { //M
document.getElementById('scorePlayerTwo').innerHTML = ++currentScorePlayerTwo;
changeServePlayer();
changeServeIcon();
}
updateSet();
}
function updateSet() {
if (currentScorePlayerOne > 10 && currentScorePlayerOne > currentScorePlayerTwo + 1) {
resetScores();
}
if (currentScorePlayerTwo > 10 && currentScorePlayerTwo > currentScorePlayerOne + 1) {
resetScores();
}
}
function resetScores() {
currentScorePlayerOne = 0;
currentScorePlayerTwo = 0;
document.getElementById('scorePlayerOne').innerHTML = currentScorePlayerOne;
document.getElementById('scorePlayerTwo').innerHTML = currentScorePlayerTwo;
}
function changeServePlayer() {
totalScore = currentScorePlayerOne + currentScorePlayerTwo;
Number.isInteger(totalScore / 2);
if (Number.isInteger == true && totalScore != 0 && currentServePlayer == 1) {
currentServePlayer = 2;
}
if (Number.isInteger == true && totalScore != 0 && currentServePlayer == 2) {
currentServePlayer = 1;
}
}
function changeServeIcon() {
if (currentServePlayer == 1) {
document.getElementById('serveP1').style.opacity = "1";
document.getElementById('serveP2').style.opacity = "0.2";
} else {
document.getElementById('serveP2').style.opacity = "1";
document.getElementById('serveP1').style.opacity = "0.2";
}
}
<!DOCTYPE html>
<html>
<head>
<script src="Scoreboard1javascript.js"></script>
</head>
<body>
<button type="button" onclick="chooseServingPlayer()">
Serve
</button>
<script>
var randomServeNumber;
function chooseServingPlayer() {
if (currentScorePlayerOne == 0 && currentScorePlayerTwo == 0) {
document.getElementById('serveP1').style.opacity = "0.2";
document.getElementById('serveP2').style.opacity = "0.2";
randomServeNumber = Math.floor(Math.random() * 10);
if (randomServeNumber > 5) {
currentServePlayer = 1;
changeServeIcon();
} else {
currentServePlayer = 2;
changeServeIcon();
}
}
}
function changeServeIcon() {
if (currentServePlayer == 1) {
document.getElementById('serveP1').style.opacity = "1";
document.getElementById('serveP2').style.opacity = "0.2";
} else {
document.getElementById('serveP2').style.opacity = "1";
document.getElementById('serveP1').style.opacity = "0.2";
}
}
</script>
<nav>
<img src="tafeltennisbat.png" alt="serve" style="width: 50px; height: 50px; opacity: 0.2" id="serveP1"> Score P1
</nav>
<nav>
Score P2
<img src="tafeltennisbat.png" alt="serve" style="width: 50px; height: 50px; opacity: 0.2" id="serveP2">
</nav>
<nav id="scorePlayerOne" style="font-size: 50px">
0
</nav>
<nav id="scorePlayerTwo" style="font-size: 50px">
0
</nav>
</body>
</html>

I forgot to check which file I was referencing in my html script. I was referencing an old version of the javascript, which made every change I made in javascript useless.
It can be really that stupid sometimes...

Related

How i make an element to be shown or not?

anchorArrows is an element that if I click the checkbox it must be shown and if it's not checked it must be hidden. The classList hidden and show are CSS classes with opacity 0 and 1
let q = document.getElementById("Q").value;
let q2 = document.getElementById("q2").value;
const anchorArrows = document.getElementById("anchor");
if((chkQ.checked == true) && (chkQ2.checked == false)){
anchorArrows.classList.add("show");
anchorArrows.classList.remove("hidden");
if(q > 0){
flechas(0,"x");
}else{
flechas(180,"x");
}
}else{
anchorArrows.classList.remove("show");
anchorArrows.classList.add("hidden");
}
if((chkQ2.checked == true) && (chkQ.checked == false)){
anchorArrows.classList.add("show");
anchorArrows.classList.remove("hidden");
if(q > 0){
flechas(0,"y");
}else{
flechas(180,"y");
}
}else{
anchorArrows.classList.remove("show");
anchorArrows.classList.add("hidden");
}
CSS:
.hidden{
opacity: 0;
}
.show{
opacity: 1;
}
You need to use else if and one else. The issue you have is the first if can be true, but the second else will wipe away the class.
if (chkQ.checked && !chkQ2.checked) {
anchorArrows.classList.add("show");
anchorArrows.classList.remove("hidden");
if (q > 0) {
flechas(0, "x");
} else {
flechas(180, "x");
}
} else if (chkQ2.checked && !chkQ.checked) {
anchorArrows.classList.add("show");
anchorArrows.classList.remove("hidden");
if (q > 0) {
flechas(0, "y");
} else {
flechas(180, "y");
}
} else {
anchorArrows.classList.remove("show");
anchorArrows.classList.add("hidden");
}
And to get rid of repeated code
let isValid = false;
if ((!chkQ.checked && chkQ2.checked) || (chkQ.checked && !chkQ2.checked)) {
isValid = true;
const num = +q > 0 ? 0 : 180;
const code = chkQ.checked ? "x" : "y";
flechas(num, code);
}
anchorArrows.classList.toggle("show", isValid);
anchorArrows.classList.toggle("hidden", !isValid);
Personally, I wouldn't use classes to change opacity, as multiple variables can affect the outcome of it. Instead, I would put opacity in the original Id/Class in the CSS, and use .style.opacity to change it.
For Example:
CSS:
#box {
opacity:1;
}
HTML:
<div id="box"></div>
Javascript:
document.getElementById('box').style.opacity = .5;
In your code, it would be anchorArrows.style.opacity = 1; for show, and anchorArrows.style.opacity = 0; for hidden.

Im having trouble writing a variable to a modal window

So I'm totally not into javascript, sadly I need to use it for a small project. I'm making a checklist but I can't get a variable to write to a modal box. I left out the rest of the checklist because that would be a lot of unnecessary HTML.
What I want to achieve:
The if statement with the count is going to calculate how many points you got correct on the checklist. Then he will write this calculation to the modal box/window. But I can't manage to get the variable trough. Is it a scope problem perhaps?
My code
<a class="subbtn" href="#popup1" onclick="checkboxes()">Verstuur</a>
<script>
$(document).ready(function () {
$(".checklist").contents().find(":checkbox").bind('change', function () {
val = this.checked; //<---
$(this).parent().toggleClass('checked');
});
$(".checklist").contents().find(":checkbox").bind('focus', function () {
val = this.focused; //<---
$('.focus').removeClass('focus');
$(this).parent().addClass('focus');
});
});
</script>
<script>
function checkboxes(variable) {
var inputElems = document.getElementsByTagName("input")
, count = 0;
for (var i = 0; i < inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true) {
count++;
}
}
if (count == '0') {
document.getElementsByClassName('content').innerHTML = variable;
}
else if (count == '5') {
alert('Not good')
}
else if (count < 5) {
alert('decent')
}
else if (count > '5') {
alert('Better')
}
}
</script>
</section>
</div>
<div id="popup1" class="overlay">
<div class="popup">
<h2>Je scoort</h2> <a class="close" href="#">×</a>
<div class="content">
<script>variable</script>
</div>
</div>
The problem seems to be the fact that you get a list. You can use that to get a single element with the classname.
function checkboxes(variable) {
var variable = "mooi";
var inputElems = document.getElementsByTagName("input")
, count = 0;
for (var i = 0; i < inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true) {
count++;
}
}
if (count == '0') {
document.querySelector('.content').innerHTML = variable;
}
else if (count == '5') {
alert('bagger')
}
else if (count < 5) {
alert('Waardeloos')
}
else if (count > '5') {
alert('Beter')
}
}
This worked for me.
document.getElementsByClassName('content')[0].innerHTML = variable;
Also works.

Javascript Element.ClassName always returning true on mousewheel change

I have a scroll wheel function that changes the class of a div as you scroll down or up.
It is actually functioning really well in all modern browsers, the thing is, it is trying to change the class everytime it is executing, even though I have a validation that should stop this from happening.
The function asks that if the div already has that class active then it should not change, but if you look at the console it is trying to do it every time despite that validation.
I don't know why the className method always returns true.
I used jquery's hasClass function and had the same behavior.
Thank you so much for your help.
JAVASCRIPT CODE:
var sections = ['one', 'two', 'three', 'four', 'five'];
function changeSection(section) {
for (var x = 0; x < sections.length; x++) {
$('#bg-main').removeClass('bg-' + sections[x]);
if (sections[x] === section) {
if (document.getElementById('bg-main').className != ('bg-' + section)) {
$('#bg-main').addClass('bg-' + section);
console.log("Active: " + section);
} else {
console.log("Inactive: " + sections[x]);
}
}
}
}
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel"
if (document.attachEvent)
document.attachEvent("on" + mousewheelevt, displaywheel)
else if (document.addEventListener)
document.addEventListener(mousewheelevt, displaywheel, false)
var position = 0;
function displaywheel(e) {
var evt = window.event || e
var delta = evt.detail ? evt.detail : evt.wheelDelta
if (delta < 0) {
position = (mousewheelevt == 'DOMMouseScroll') ? position - 1 : position + 1;
} else {
position = (mousewheelevt == 'DOMMouseScroll') ? position + 1 : position - 1;
}
if (position < 0) position = 0;
if (position > 100) position = 100;
// Change sections on Scroll
if (position >= 0 && position <= 19) {
changeSection('one');
} else if (position >= 20 && position <= 39) {
changeSection('two');
} else if (position >= 40 && position <= 59) {
changeSection('three');
}
if (position >= 60 && position <= 79) {
changeSection('four');
} else if (position >= 80 && position <= 100) {
changeSection('five');
}
}
CSS CODE:
#bg-main {
width: 100%;
height: 300px;
}
.bg-one {
background-color: blue;
}
.bg-two {
background-color: red;
}
.bg-three {
background-color: green;
}
.bg-four {
background-color: yellow;
}
.bg-five {
background-color: purple;
}
HTML CODE:
<div id="bg-main" class="bg-one">SCROLL TO SEE THE CHANGE OF BACKGROUND</div>
Working fidddle:
https://jsfiddle.net/9vpuj582/
You are removing the class before you check to see if the element has the class that you passed into your function (so your if statement will never evaluate as false).
The placement of the following line of code in your changeSection function is your issue:
$('#bg-main').removeClass('bg-'+sections[x]);
You could simplify your current function quite a bit. First check if the element already has the class you want. Then, if not, remove all classes from the element (rather than looping through them and checking each one) and then add the new class. For example:
const bg = $('#bg-main');
function changeSection(section) {
if (!bg.hasClass('bg-' + section)) {
bg.removeClass();
bg.addClass('bg-' + section);
}
}

Exe program with javascript code

I need an executable program (and need it running all day) in which when you press certain key codes (like ctr+alt+C) in any moment and window, the program do something.
I have tried with jsc (compiling it from cmd) but im getting this:
accesos.js(8,26) : error JS1004: ';' was expected
accesos.js(3,1) : error JS1135: The variable 'document' it's not declared
And here is the code:
var ctrlmod = 0;
var shiftmod = 0;
document.addEventListener('keydown', function(eventK) {
if(eventK.keyCode == 17) {
ctrlmod = 1;
}
if(ctrlmod == 1){
if(eventK.keyCode == 16) {
shiftmod = 1;
}
if(shiftmod == 1){
if(eventK.keyCode == 67){
alert('c');
ctrlmod = 0;
shiftmod = 0;
}
}
}
if((ctrlmod == 1 || shiftmod == 1) && eventK.keyCode != 17 && eventK.keyCode != 16){
ctrlmod = 0;
shiftmod = 0;
}
});
Is there anything I can do to make this work?
Thanks
Well, I tried with AHK (AutoHotKey) and it solved my problem, I hope it work for anyone interested.

HTML file won't show my javascript variable

I've written a javascript function with some variables, i've tried to test it to see if variables would show in my HTML document but they wont and i have no idea why. Specifically, i'm trying to insert variable currentScore which is set to 0 at the beginning, so it should show 0 in a textbox, but it doesnt appear there.
Here is my javascript :
var who = 0;
var decision = 0;
var diceOne = 0;
var diceTwo = 0;
var currentScore = 0;
player playerAI = new player;
player playerOne = new player;
document.getElementById('currentScore').value = currentScore;
function rollDice() {
diceOne = Math.round(6 * Math.Random() + 1);
diceTwo = Math.round(6 * Math.Random() + 1);
}
function mainFunction() {
playerAI.playing = true;
playerOne.playing = true;
while (playerAI.playing == true && playerOne.playing == true) {
makeMove();
}
}
function makeMove() {
if (who == 0) {
aiStrat();
game();
}
else {
game();
}
}
function game() {
if (decision == 1) {
rollDice();
if (diceOne != 1 && diceTwo != 1){
currentScore += diceOne + diceTwo;
decision = 0;
makeMove();
}
if (diceOne == 1 || diceTwo == 1){
currentScore = 0;
decision = 0;
who = 1 - who;
makeMove();
}
if (diceOne == 1 && diceTwo == 1) {
currentScore = 0;
if (who == 0) {
playerAI.totalScore = 0;
}
else {
playerOne.totalScore = 0;
}
decision = 0;
who = 1 - who;
makeMove();
}
}
if(decision == -1) {
if (who == 0){
playerAI.totalScore += currentScore;
playerAI.checkScore();
}
else {
playerOne.totalScore += currentScore;
playerOne.checkScore();
}
currentScore = 0;
decision = 0;
who = 1 - who;
}
}
function aiStrat() {
if (playerAI.totalScore < 60) {
if (currentScore < 30) {
decision = 1;
}
else {
decision = -1;
}
}
if (playerAI.totalScore >= 60 && playerAI.totalScore < 80) {
if (currentScore < 20){
decision = 1;
}
else {
decision = -1;
}
}
if (playerAI.totalScore >= 80){
if (currentScore < 10) {
decision = 1;
}
else {
decision = -1;
}
}
}
var player {
var totalScore = 0;
var playing = true;
function checkScore() {
if (totalScore >= 100) {
playing = false;
}
};
};
And my HTML document is this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="BigPig.css">
<script type="text/javascript" src="VorgurakendusedKD1\Vorgurakendused.js" ></script>
</head>
<body onload="javascript:mainFunction()">
<div class="centered" type="text/javascript">
<h1>BIG PIG</h1>
<button><input type="button" value="START FROM BEGINNING" onclick="mainFunction();">
<span></span></button>
<br>
<button><span>GREEN BUTTON</span></button>
<br>
<button><span>RED BUTTON</span></button>
<br>
<output class="textbox" type="text/javascript" id="currentScore">CURRENTSCORE:
</output>
<br>
<output class="textbox" type="text">CPU SCORE: </output>
<br>
<output class="textbox" type="text">PLAYER SCORE: </output>
<br>
<p>Player versus computer</p>
<br>
<p id="currentScore"></p>
</div>
</body>
</html>
Here: document.getElementById('currentScore').value = currentScore;you try to find an element before it has loaded, and that's why you can't assign a value to it.
Try putting document.getElementById('currentScore').value = currentScore; inside your onload-function, mainFunction()

Categories