Skip to content
Related Articles

Related Articles

p5.js Element toggleClass() Method
  • Last Updated : 20 Nov, 2020

The toggleClass() of p5.Element in p5.js is used to toggle the specified class in the element. The toggling of a class means that it would be added or removed depending on the current state.

Syntax:

toggleClass(class)

Parameters: This function accepts a single parameter as mentioned above and described below:

  • class: It is a string that denotes the class to be toggled.

The example below illustrates the toggleClass() method in p5.js.

Example: The following HTML code shows the CSS styles that have to be added for the classes to show their effect. The p5.js elements can now use these classes.



HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
  
    <script src="sketch.js"></script>
  
    <style>
        .red {
            background-color: red;
        }
  
        .border {
            border: 10px dashed;
        }
    </style>
</head>
  
<body></body>
  
</html>

JavaScript code: The “sketch.js” file contains the p5.js code that demonstrates this method.

Javascript




function setup() {
  canv = createCanvas(550, 300);
  textSize(18);
  
  text("Click on the buttons to toggle the " +
       "given class of the canvas", 20, 30);
  
  setBtn = createButton("Toggle Color");
  setBtn.position(30, 60);
  setBtn.mouseClicked(toggleColor);
  
  setBtn = createButton("Toggle Border");
  setBtn.position(160, 60);
  setBtn.mouseClicked(toggleBorder);
  
  canv.addClass("red");
  canv.addClass("border");
}
  
function toggleColor() {
  clear();
  
  // Toggle the given class
  canv.toggleClass("red");
  text("The color class has been toggled", 30, 120);
  text("Click on the buttons to toggle the " +
       "given class of the canvas", 20, 30);
}
  
function toggleBorder() {
  clear();
  
  // Toggle the given class
  canv.toggleClass("border");
  text("The border class has been toggled", 30, 120);
  
  text("Click on the buttons to toggle the " +
       "given class of the canvas", 20, 30);
}

Output:

Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5.Element/toggleClass

My Personal Notes arrow_drop_up
Recommended Articles
Page :