You're close. Start out with a CSS class that is applied to all the div
elements by default to make then initially gray. Then, when clicked, toggle another class that will override the gray and make them blue.
And, rather than setting inline styles (with element.style.backgroundColor
), use the element.classList
API, which is simple to use and allows you to set up CSS classes ahead of time that just need to be added, removed or toggled.
But also, you should not use HTML event handling attributes, such as onchange
. This is a 20+ year old technique that, unfortunately, is so prolific, it still gets used although there are many reasons to abandon this technique. Instead, do all your JavaScript in a separate script
.
Lastly, unless there is some specific reason you are using p
elements inside each div
element, you can get rid of either the div
or the p
elements as they both signify a new section to your code.
Take note of how much cleaner the HTML is in the following:
// Get all the p elements that need to be able to be colored into an array
var pars = Array.prototype.slice.call(document.querySelectorAll("p.sidebar2"));
// Loop over the array elements and assign a click event handler each p
pars.forEach(function(p){
p.addEventListener("click", function() {
p.classList.toggle("blue"); // Toggle the use of the .blue class
});
});
.sidebar2 { background: #e0e0e0; } /* Applied by default */
p.blue { background: lightblue; } /* Toggled on/off when div is clicked */
<!-- The HTML can be much more simplified -->
<p class="sidebar2">11</p>
<p class="sidebar2">10</p>
<p class="sidebar2">9</p>
<p class="sidebar2">8</p>