Reputation: 11
I'm currently working on a project with p5.js and have come against a problem in javascript. I built buttons in javascript to help make certain functions work and I'm looking for a way to style the buttons. For the rest of the project I was using bootstrap so I'm trying to find a way to style it as similar as I can to the rest of the rest off the CSS if possible. The buttons code in javascript follows this.
button1 = createButton('start');
button2 = createButton('stop');
button3 = createButton('play');
button4 = createButton('save');
button1.mousePressed(start_);
button2.mousePressed(stop_);
button3.mousePressed(play_);
button4.mousePressed(save_);
Upvotes: 1
Views: 2254
Reputation: 57155
createButton
returns a p5.Element
object which has a .class()
method to set the class property on it. Classes can then be used for styling, either with bootstrap or custom CSS. For example:
let btn;
function setup() {
noCanvas();
const cls = "maroon-bg white-text";
btn = createButton("hello world");
btn.class(cls);
btn.mouseClicked(() => {
btn.class(btn.class() ? "" : cls);
});
}
.maroon-bg {
background-color: maroon;
}
.white-text {
color: white;
}
button {
padding: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>
I prefer separating CSS and JS because it promotes reuse and keeps your JS clean, but if you want to inline your styles, you can use .style()
:
let btn;
function setup() {
noCanvas();
btn = createButton("hello world");
btn.style("background-color", "maroon");
btn.style("color", "white");
btn.style("padding", "1em");
btn.mouseClicked(() => {
if (btn.style("color") === "rgb(0, 0, 0)") {
btn.style("color", "white");
btn.style("background-color", "maroon");
}
else {
btn.style("background-color", "");
btn.style("color", "");
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>
This is clearly awkward for this use case, but it can come in handy in other situations and is shown for completeness.
Upvotes: 1