In the code below, we have a function to draw a button, where the color of the button changes depending on the global state variable: buttonOn. This state variable has it's value changed in the mouseClicked function if the button was clicked. The button starts in the 'off' state, where buttonOn is set to false. Each time the mouse is clicked while it's within the button's boundary, the value of buttonOn is reversed, if it was true, then it's set to false. This creates a toggle button that changes between being on and off. Within the drawButton function, the fill color for the button is determined based on the state of this buttonOn variable. For this course, we'll treat state variables as global objects since we need to check the value within the mouseClicked() or mousePressed function.
varx=100;vary=100;varw=100;varh=50;varbuttonOn=false;//variable to track the button's statevardrawButton=function(x,y,w,h){fill(240,5,60);//red is offvarbtnText="OFF";if( buttonOn ===true){fill(14,201,98);//green btnText ="ON";}rect(x,y,w,h);//draw button rectanglefill(252,252,252);//fill for texttextAlign(CENTER);text(btnText, x +(w/2),y +(h/2)+5);};vardraw=function(){background(255);drawButton(x,y,w,h );};varmouseClicked=function(){if( mouseX > x && mouseX < x+w && mouseY > y && mouseY < y + h){ buttonOn =!buttonOn;//toggle button between on and off}};
Javascript Object Literals
Javascript has a convenient way to store a group of data that is all related to 1 object, object literal notation. For using Javascript object literals, you will a global variable with a code block that contains property name: attribute value pairs, these are separated by commas. Object literals allow us to treat the data associated with an object as one bundle of information.
In the code below we can see that we've created an object literal with the name: btn1