Using mousePressed on the same object twice?

118 Views Asked by At

I have a program where I want a circle to change color when it's pressed on and then if it's pressed again to change back to the original color.

I have managed to change it on the first click but don't know how to change it back when I click it again.

Do anyone have any tips on how I can change back the color or change to a different color when clicked the second time?

Current code:

// My function for changing the color when clicked.
function mousePressed () {
  for (var i = 0; i < 10; i++) {
    bubbles[i].interact();
  }
}

// function inside the class for the circle 
// to determine distance and what color.
interact () {
  let d = dist (this.x, this.y, mouseX, mouseY);
  if (d < this.r) {
    this.col = 0;
  }
}
1

There are 1 best solutions below

0
On

If you can reproduce your problem in a codepen or similar sandbox it would be easier for someone to help you solve it.

2 things spring to mind:

You could use element.classlist.toggle() to toggle a class on/off and style that class.

Or you could extend your code like so:

if (d < this.r) {
  if (this.col === 0) {
    this.col = 1;  // I'm guessing this is the correct value
  } else {
    this.col = 0;
  }
}