Can someone tell me where I'm going wrong here? I want the functionality of the first piece of code to work with an "onclick" function call.
<html>
<body>
<h1>Global variables</h1>
<p id="before">Something should print here</p>
<p id="after">Something should print here</p>
<script>
x = 0;
document.getElementById("before").innerHTML = x;
day();
function day() {
x = 5;
}
document.getElementById("after").innerHTML = x;
</script>
</body>
</html>
I can't get this to work properly. According to w3schools: "If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable".
<html>
<body>
<h1>Global variables</h1>
<div id="buttons">
<button id="5" onclick=day(this.id)>Click me to find out the ID!</button>
</div>
<p id="test">Something should print here</p>
<script>
function day(id) {
x = id;
}
document.getElementById("test").innerHTML = x;
</script>
</body>
</html>
This modified w3schools code demonstrates my problem:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Scope</h2>
<p>carName within myFunction() and outside myFunction are distinct.</p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
carName = "Toyota";
myFunction();
function myFunction() {
var carName = "Volvo";
document.getElementById("demo1").innerHTML = "This variable - " + carName + " is defined within the function";
}
document.getElementById("demo2").innerHTML = "This variable - " + carName + " is defined outside the function";
</script>
</body>
</html>