1

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!!

2
  • Where are you calling changeColor(). I don't see it getting called anywhere. Commented Apr 1, 2014 at 1:11
  • Also, you can change your click function to just: function click(){ circle++; } Commented Apr 1, 2014 at 1:11

2 Answers 2

1

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) { ... }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks YOu so much, JS as a whole makes so much more sense now!!
1

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();
  }
}

1 Comment

Ya, I think it is calling window.click.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.