Change class of div on click

Question!

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'?



Answers

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);;
}
By : codemax


In Standard javascript:

document.getElementById('foo').className += ' selected'

or in JQuery:

$('#foo').addClass('selected');


Your divs have same ID, which is wrong, do it like this

{cal_cell_content}
    <div class="event" href="">
        {day}
    </div>
{/cal_cell_content}


$('.event').click(function(){
   $('.event').removeClass('selected');
   $(this).addClass('selected');
});

with javascript:

{cal_cell_content}
    <div class="event" href="" onclick="selectMe(this);">
        {day}
    </div>
{/cal_cell_content}

function selectMe(obj){
    var divs = document.getElementsByClassName("event");
    for(var i = 0; i < divs.length; i++)
    {
       divs[i].className = "event";
    }
    obj.className = "event selected"
}


This video can help you solving your question :)
By: admin