Jethro Hazelhurst Jethro Hazelhurst - 2 months ago 8
CSS Question

Change class of div on click

Seemingly simple question which is confusing me... all answers seem to be for JQuery only.

I am generating a table calendar with PHP.

enter image description here

Each day on the calendar is a

tr > td > div
which looks like this at the moment:

{cal_cell_content}
<div class="" id="event" href="" onclick="this.className=\'selected\';return getDate({day});">
{day}
</div>
{/cal_cell_content}


When a user clicks on one of the divs I want the background of that div to change its css class to 'selected'.

Then, if the user clicks another div I want that class to change to selected and the previous class to be removed so that only one div at any time can be 'selected'.

At the moment I am using
this.className='selected
which works except multiple divs can be selected!

How do get behaviour so that I can select a single div and highlight it, then if I decide to click another div, the previous div becomes de-selected and the new div is 'selected'?

Answer

Add an event listener to the div class via a loop, and add another class "selected" to the div if it is clicked. Otherwise, remove the "selected" class. The "selected" class will contain your css stuff.

For instance,

var x = document.getElementsByClassName('yourClass')
for (var i = 0; i < x.length; i++) {
    x[i].addEventListener("click", function(){

    var selectedEl = document.querySelector(".selected");
    if(selectedEl){
        selectedEl.classList.remove("selected");
    }
    this.classList.add("selected");

    }, false);;
}