Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptp5.js Element toggleClass() Method

p5.js Element toggleClass() Method

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments