Very new to the web development industry, and having some trouble figuring out what's wrong with my code. Trying to implement javascript onto a code snippet with Wordpress using Divi, but can't seem to understand what exactly is wrong. My intentions are to change the background & text color of the button on click. I'd appreciate the help!
<button onClick="firstFunc()";
class="butCol";
style="background-color: transparent;
border: none;
font-weight: bold;
border-radius: 25px;
padding: 2px 15px";>LATTES</button>
<script>
function firstFunc() {
var x = document.getElementByClass("butCol");
if (x.style.backgroundColor == "transparent";) {
x.style.backgroundColor = "#373975";
x.style.color = "white"};
else {
(x.style.backgroundColor = "transparent")
};
};
</script>
The issue is caused by a few typos. unfortunately to many and to long to list them in the comments. So if this solve the issue for you, remove your question voluntarily:
if (x.style.backgroundColor == "transparent";) {
-> remove the semicolon: if (x.style.backgroundColor == "transparent") {
x.style.color = "white"};
-> swap the semicolon and clamp: x.style.color = "white"; }
(x.style.backgroundColor = "transparent")
-> remove the clamps and finish with a semicolon: x.style.backgroundColor = "transparent";
getElementByClass
just getElementsByClassName
. However this would return an array. Just use querySelector
instead.function firstFunc() {
var x = document.querySelector(".butCol");
if (x.style.backgroundColor == "transparent") {
x.style.backgroundColor = "#373975";
x.style.color = "white";
} else {
x.style.backgroundColor = "transparent";
};
};
<button onClick="firstFunc()";
class="butCol";
style="background-color: transparent;
border: none;
font-weight: bold;
border-radius: 25px;
padding: 2px 15px";>LATTES</button>
However, smarter would be to use CSS to apply the changes and just using the .classList.toggle('class-name');
function:
function firstFunc() {
document.querySelector('.butCol').classList.toggle('clicked');
}
.butCol {
background-color: transparent;
border: none;
border-radius: 25px;
padding: 2px 15px;
font-weight: bold;
}
.clicked {
background-color: #373975;
color: white;
}
<button onClick="firstFunc()";
class="butCol";>LATTES</button>