Help with adding variable to self and random number (javascript) - javascript

I am making a simple dice roller, which seems like a good first project to me, and may help others learn javascript as well, and when you roll a die (with a button), it is supposed to add to the total (there is a clear button), but it says NaN. Here is my code:
<html>
<body>
<script type="text/javascript">
function load()
{
document.getElementById("press").value=" "
var x=0
}
function d6()
{
var x=x+(Math.floor((Math.random() * 6) + 1));
document.getElementById("press").value=(x)
}
load()
</script>
<input type="button" value="Roll d6" onclick="d6()"/>
<input type="text" id="press"/>
</b>
<input type="button" value="Clear" onclick="load()"/>
</body>
</html>
Help would be greatly appriciated.
Thanks!

This is happenning because variable x is not initialised when you are using it in d6(). The scope of the 2 functions is different.
You need x to be a global variable. For that, use the following code structure:
x = 0
function load() { ... }
function d6() { ... }
Remember that when you declare a variable with the keyword 'var' preceding it, the variable is considered local. A variable without a 'var' is considered global.

Your x variables are local to the functions. change x to be a global variable:
var x;
function load() { ... }
function d6() { ... }

When using JavaScript it is important to consider the scope of names and values. Consider the difference between this:
var x = 2;
function assignX(v) {
x = v;
}
print(x); // 2
assignX(3);
print(x); // 3
and this:
function assignX(v) {
var x = v;
}
print(x); // undefined
assignX(3);
print(x); // undefined
In the first example x exists in the global scope which encloses all names and values. In the second example x only exists within the function assignX.

Related

Change javascript variable on others script outcome

I need a way where I can change the variable of a jave script function on the outcome of a different function which gets executed on a input click.
Example of the input:
<input type="image" value="74" onclick="WeaponType(this);GetDamage(74);return false;" class="CompactPistol" src=".\Weapons\Bornheim_No_3_Extended.png" alt="Bornheim No.3 Extended">
<span style="color:whitesmoke">Bornheim No. 3 Extended</span>
(I could also change the 'GetDamage' function input to 'this' instead of the value directly and then just change the function output to use the attribute 'value'. In my case it doesn't really matter as the value of one picture is set.)
My script that needs the variable currently looks like this:
<script id="ResultDamage">
function GetDamage(x) {
document.getElementById("DamageDealt").innerHTML = x;
}
</script>
This ofc only outputs the value of the function. But the value needs to be used in a more complicated calculation
What I f.e. also already tried was this:
<script id="ResultDamage">
function GetDamage(x) {
var z
z = x;
return z;
}
var d = z;
document.getElementById("DamageDealt").innerHTML = d;
</script>
and this:
<script id="ResultDamage">
function GetDamage(x) {
return x;
}
var d = GetDamage();
document.getElementById("DamageDealt").innerHTML = d;
</script>
Which gives me 'undefined'
Any help is appreciated.
As I am quite new to this keeping it simple would probably the best (if there is a simple solution)
Based on comments on the question above...
If you just need to store a value globally on the page then you can declare a variable outside of the function and set its value within any function. For example:
var a = 0;
var b = 0;
// etc.
function GetDamage(x) {
a = x;
// perform a calculation as needed
// write a result to the page as needed
}
In this case the values of a and b are stored at the page level and available to other functions, persist their values between function calls, etc. So you can have separate functions that also use those values for their own calculations.

Changing global Variable from within function

Here im having a bit of an issue with this very simple script Ive written up. The aim for this script is to simply reduce the given number by one each time the button is clicked. I cannot appear to do this.. My global variable being the Number=100 doesnt appear to change, or change more than once.. Apologies for not being able to explain this well.
Here is the part im working on..:
<script>
var Number = 100; // Number i want changed and to keep changing each button click
function outcome() { // Button calls this function
Number = Number - 1; // Tries to change Global Number.. :/
}
document.write(Number); // Has the Number written in the document
</script>
Yes, conceptually this is right. Only you are not calling the function, at least not before writing Number to the document.
Btw, Number is the global reference to the Number constructor so you should use another variable name, lowercase at best.
var num = 100;
function outcome() {
num--;
}
outcome();
document.write(num); // 99
or
<script>
var num = 100;
function outcome() {
num--;
alert(num);
}
</script>
<button onclick="outcome()">Decrease!</button>
(Demo at jsfiddle.net)
You have to call your function:
<script>
var Number=100
function outcome(){
Number=Number-1
}
outcome(); // call the function here
document.write(Number)
</script>
or don't use a function in the first place:
<script>
var Number=100
Number=Number-1
document.write(Number)
</script>

Javascript variable is undefined

<html>
<head>
<title>Array of images</title>
<script type="text/javascript">
var myPics = new Array[3];
myPics[0] = "./img/blue.png";
myPics[1] = "./img/red.png";
myPics[2] = "./img/yellow.png";
var counter = 0;
function preImg(){
alert(counter);
if(counter == 0)
counter = 4;
counter --;
alert(counter);
document.getElementById("coloredImg").src = myPics[counter];
}
function nextImg(){
if(counter == 3)
counter = -1;
counter ++;
document.getElementById("coloredImg").src = myPics[counter];
}
</script>
</head>
<body>
<img src="./img/blue.png" id="coloredImg" alt="Image not found"/>
<input type="button" onclick="preImg()" value="Previous"/>
<input type="button" onclick="nextImg()" value="Next"/>
</body>
</html>
The problem I encounter is that my counter variable is undefined inside the function. For example when I call the function preImg it alerts me with undefined (when it should be just 0) and the second alert show NaN when it should be a 3. Why my function doesnt recognize my "var counter" it is global isnt it? Do you think the same happens with the variable mypics. Thanks!
new Array[3];
should be
new Array(3);
But rather, use the square bracket notation to create an array (there's no need to specify the length either):
var myPics = [];
Why use this syntax you may ask? There are many reasons:
[] is a faster and shorter way of creating an array.
The Array constructor can be overridden while a syntactical construct like this cannot.
It's much easier to spot in code, making debugging easier.
It has the ability to take a single element (i.e [5]) and not interpret it as the length of the array, a common problem with the cumbersome Array constructor.
var myPics = new Array[3]; should be var myPics = new Array(3);
JsFiddle: http://jsfiddle.net/cbJAc/
Simple slideshow object using a closure over element, pics and counter:
function Slideshow(element, pics) {
var counter = 0;
this.nextImg = function () {
element.src = pics[counter];
counter = (counter + 1) % pics.length;
}
this.nextImg(); // init
}
usage:
var show = new Slideshow(
document.getElementById("coloredImg"),
["./img/blue.png", "./img/red.png", "./img/yellow.png"]
);
show.nextImg(); // red
show.nextImg(); // yellow
show.nextImg(); // blue
Closures make sure that every variable that's in scope when a function is defined will still be in scope when the function is called (or called again). This standard JavaScript technique elegantly solves your counter issue.
Using a modulus based calculation lets the counter repeat the sequence 0,1,2 (in this example).
Edit: Assume you would want to switch to a new image every three seconds:
setInterval(show.nextImg, 3000);

var x = x || "default val" not getting set properly if x is defined above it

HTML:
<script type="text/javascript">
var x = "overriden";
</script>
<script src="myjs.js"></script>
myjs.js:
$(document).ready(function(){
var x = x || "default val";
alert(x); // this alerts "default val" and not "overriden"
});
For some reason, x is ending up as "default val" and not "overriden", even tho initially I'm setting it to "overriden" before I even include the script reference to myjs.js.
Any idea as to why this is happening? I'm trying to enable the hosting page to set an override for a variable that's used in an included js file, otherwise use the default val.
What you have after variable declaration hoisting is applied:
var x;
x = 5;
$(document).ready(function(){
var x;
x = x || "default";
});
It looks at the closest x and sees it's value is undefined which is a falsy value, so x gets set to "default".
You would be fine if they were in the same scope, because the declarations are always hoisted above assignments so:
var x = 5;
var x = x || "default";
Is actually just
var x;
x = 5;
x = x || "default";
This was suggested which is completely pointless:
$(document).ready(function(){
x = x || "default";
});
It will throw a ReferenceError if x is not defined.
So either do the check in the same scope or do something like:
$(document).ready(function(){
var x = window.x || "default";
});
Invalid property reads don't cause a ReferenceError but just return undefined instead.
The var x in the function passed to $(document).ready() is hiding the global scope x variable.
If you just use x = x || "default val";, then the global variable is clobbered. However, it's really a bad idea to have global variables at all.
You are using the var keyword in both places. Try:
x = x || "default val";
https://developer.mozilla.org/en/JavaScript/Reference/Statements/var
From the above link:
The scope of a variable declared with var is the enclosing function
or, for variables declared outside a function, the global scope (which
is bound to the global object).
x is not defined in the scope of the document ready function.
var x is preparing the variable with the value undefined, so it won't get it from the window scope.
Try var x = x || window.x || "default val"; instead.
Since you have it stated with a var that does not get the globally defined object from the html. Try removing the var and see if you get a different result, or change the variable within the function to a different letter.
When you use var within a function the scope of that var is only to the function. Since you have defined the x variable twice when you are doing the comparison it is attempting to use the variable from within the function.
If you plan to keep the var statement you will need to change the variable name or how you are calling the global x to window.x. The other option is just to drop the var from the function.
The x created on this line:
var x = x || "default val";
...is local to the function it is defined in (i.e. it shadows the global x) .
Removing the preceding var will cause both x names to reference the same global variable, but this is generally a bad idea. From the previously-linked Wikipedia page:
This can lead to confusion, as it may be unclear which variable
subsequent uses of the shadowed variable name refer to.
Because you are again declaring a new var x inside document.ready() which is another scope than global. Try this
$(document).ready(function(){
x = x || "default val";
alert(x); // this will now alert "overriden"
});
You are declaring var x in your function which creates local storage for x and hides previous values.
Call it var y, or do as karim79 suggested.
Your var x in the second one is local to that function, and isn't the same as window.x (which is what you've defined in the former block).
the keyword var means that you've just created a local variable. So basically what is happening is that:
You declare (in your first block ) x as "overridden"
Memory:
x -> "overriden"
You set the callback to document.ready
Memory:
x -> "overriden"
(after the document is loaded) 3. you run your anonymous function, initialising x with var
Memory:
x->"overriden"
[IN SCOPE]
anonymous_function.x -> "default_value"
[/SCOPE]
"BUT WAIT", you might say, "the code I wrote is var x= x || "default var" so what should happen is local_x=global_x || "default value ,right?
Unfourtunately Javascript doesn't work like that. In javascript, we have function scope, instead of the more widely used block scope. So when you write:
f=function(){
var x=y || "default value";
var y=3;
alert(x);
}
what'll be interpreted in javascript is :
f=function(){
var x;
var y;
x=y || "default value";
y=3;
alert(x);
}
so running y=10; f(); will give you "default value" on the prompt.
So taking off your var will work to fix your problem here, but just remember in general that all your variable declarations are done "at the beginning" of a function, so scope is immediately changed when entering a function.

Using a global variable in JavaScript

How do I do this?
My code is something like this:
var number = null;
function playSong(artist, title, song, id)
{
alert('old number was: ' + [number] + '');
var number = '10';
alert('' + [number] + '');
}
The first alert always returns 'old number was: ' and not 10. Shouldn't it return 10 on both alerts on the second function call?
By using var when setting number = '10', you are declaring number as a local variable each time. Try this:
var number = null;
function playSong(artist, title, song, id)
{
alert('old number was: ' + [number] + '');
number = '10';
alert('' + [number] + '');
}
Remove the var in front of number in your function. You are creating a local variable by
var number = 10;
You just need
number = 10;
The problem is that you're declaring a new variable named number inside of the function. This new variable hides the global number variable, so the line number = 10 assigns only to this new local variable.
You need to remove the var keyword from var number = 10.
Like in C, you need to define your variable outside of the function/method to make it global.
var number = 0;
function playSong(artist,title,song,id)
{
alert('old number was: '+[number]+'');
number = '10';
alert(''+[number]+'');
}
Let me explain in detail. To declare global variables and local variables in JavaScript
var firstNumber = 5; // Local variable
secondNumber = 10; // Global variable or window object
When your program is like this
var number = 1;
function playSong() {
alert(number);
var number = 2;
alert(number);
}
As per the JavaScript compiler, all declarations/initializations of variables will move to the top. This concept is called hoisting.
As per the compiler, the program will execute like:
var number; // Declaration will move to top always in Javascript
number = 1;
function playSong() {
var number;
alert(number); // Output: undefined - This is a local variable inside the function
number = 2;
alert(number); // Output: 2
}
If you need to access the global variable inside the function, use window.number.
var number = 1;
function playSong() {
var number = 2;
alert(window.number); // Output: 1 - From a global variable
alert(number); // Output: 2 - From local variable
}
You can also access it in any function like window.number, after removing var inside the function.
I’ve come across this answer in 2020 and after searching some more online I have found that apparently in the JavaScript definitions if you place variables outside of functions or even create a file called globals.js and just put all your globally required variables in that file, make that file the first user .js file in your script tags after jQuery and any other plugins you need, globals will load before your other scripts and allow you to call variables from globals.js within any script on the page.
W3C JavaScript Scope
I have tested this theory within a PHP application that I am building and I have been able to call variables from the globals.js file within a page that is loaded via Ajax to a jconfirm dialog for a troubleshooting wizard to set up the return values for when the dialog is closed.

Categories

Resources