The other answers have told you what to do, but they haven't told you why this is happening.
Here's my understanding:
Calling the alert()
function blocks the rest of your code's execution. The code will stop executing, and any interaction will be disabled- you won't be able to click on links or buttons, for example.
In P5.js, this means that mouse events (even simple events like updating mouseX
and mouseY
) will also be blocked.
Here's what your code does:
- Shows an alert dialog, which blocks all events.
- The user moves the mouse, but at this point P5.js can't "see" that they've moved the mouse off the button, because they're doing it when the alert dialog is displayed.
- Then the user clicks the OK button. This unpauses your code, which in your case just fires the
draw()
function again. Keep in mind that mouseX
and mouseY
have not been updated yet, so P5.js still thinks you're on the button so it shows the alert dialog again.
As other answers have suggested, you can use the mouseClicked()
or mousePressed()
functions instead of checking mouseIsPressed
.
function setup() {
createCanvas(600, 800);
}
function draw() {
background(170)
fill(0, 0, 255)
if (mouseX > 200 && mouseX < 260 && mouseY > 200 && mouseY < 225) {
fill(0, 0, 155)
}
rect(200, 200, 60, 25, 10)
}
function mousePressed() {
if (mouseX > 200 && mouseX < 260 && mouseY > 200 && mouseY < 225) {
alert("You have pressed a button!")
}
}
Now when the user closes the dialog, the draw()
function continues as normal and events can be processed.
When you run this code, note that the button stays "pressed" even after the user closes the dialog, until they move the mouse. This is caused by the same event cancellation mentioned above.
Also note that alert dialogs are pretty annoying (and come with annoying side effects like we're talking about here), so you might be better off using a <div>
that shows your message or showing your message in the sketch itself.