Reputation: 5
I want to change the value of the variable circle
by pressing on the button. The click
function adds one to the value of circle
. When circle
is equal to 1
, my if statement should run the changeColor
function that alters the right position of a div
.
Here is my HTML code, the click
function should run when pressed...
<div id="div"></div> <button onclick="click()">Click me</button>
I can add my css but it would just take up too much space and I doubt it would make a difference.
Here is my JS code...
var circle = 0;
function click(){ circle = circle++; }
function changeColor(){
document.getElementById("div").style.right="-500px"; }
if (circle == 1){ changeColor(); }
Before I uploaded this question, I made sure that the changeColor
function worked, by just changing circle
's value.
Thanks for the help!!
Upvotes: 1
Views: 141
Reputation: 86
click() is a pre-existing method, so HTML doesn't know you're talking about a function that you made. Also note that the if statement you use to check circle will only execute once, and before anyone ever has a chance to click the button; It needs to be inside the click function. And you don't need to redefine a variable after incrementing it, the increment alone will work.
function clicked(){
circle++;
console.log(circle,"it works!");
if (circle == 1){
changeColor();
}
}
Upvotes: 1
Reputation: 2276
Your line of code that would supposedly call changeColor()
, does not do so. When you load your page, that JavaScript is executed only once. Basically, your browser thinks like this...
var circle = 0
// functions...
if(circle == 1) { ... }
"Nope, circle = 0
right now, and 0 != 1
.
If you want to have the browser continually "listen" for the value of circle
and run if(circle == 1)
when value of circle
is changed, the easiest way is to roll that if
statement into your click()
function:
function click() {
circle++; // use this instead of circle = circle++;
if(circle == 1) { ... }
}
Upvotes: 1