writingdeveloper
writingdeveloper

Reputation: 1076

jQuery toggle background, every each clicks

I want to toggle background every each clicks. But I don't know why previous colors are remained. So When I click each row, previous table background should be reset(or white)..

And I already set variable color code with 'timelineColor'

enter image description here

My Code is like this.

// Single Click Select Event to Timeline
$(document).ready(function () {
    $('#subjectList tr').click(function () {

        // 현재 클릭된 Row(<tr>)
        let tr = $(this);
        let td = tr.children();
        let day = td.eq(4).text().substring(0, 3);
        let day1 = td.eq(4).text().substring(4, 7);
        let time = Number(td.eq(5).text().substring(0, 1));
        let time1 = Number(td.eq(5).text().substring(2, 3));
        console.log(day);
        console.log(day1);
        console.log(time);
        console.log(time1);
        let dayArray = [day, day1];
        let timeArray = [time, time1];

        let timelineColor = getRamdomColor();
        for (i = 0; i < dayArray.length; i++) {
            let day;
            switch (dayArray[i]) {
                case 'monday':
                    day = 'mon';
                    break;
                case 'tuesday':
                    day = 'tue';
                    break;
                case 'wednesday':
                    day = 'wed';
                    break;
                case 'thursday':
                    day = 'tur';
                    break;
                case 'friday':
                    day = 'fri';
                    break;
            }
            let clickDay = day + timeArray[i];
            let clickDay1 = day + (Number(timeArray[i]) + 1);
            $(`#${clickDay}`).css('background-color', timelineColor);
            $(`#${clickDay1}`).css('background-color', timelineColor);
        }
    })
})

Upvotes: 0

Views: 62

Answers (2)

Viking NM
Viking NM

Reputation: 402

So when you click a row the entire row should be reset to white and then that item gets a random color?

something like this should reset the row to white

tr.children().css('background-color', '#fff');

before your

$(`#${clickDay}`).css('background-color', timelineColor);

Upvotes: 1

Richard
Richard

Reputation: 1038

You have to reset your backgrounds first, like this

(first line of the click function)

$('myTable td').css('background','transparent');

replace myTable by the name of your table ofc (or class or id)

Upvotes: 1

Related Questions