I would like to add and switch classed when clicking on some cells,Like calendar schedule.
I tried sample code below,but it didn't switch each class.
My desired result is switching like below by clicking.
null
→ classA
→ classB
→ classC
→ null
→ classA
→
my sample code is below
$("#our_calendar td")
.click(function() {
$(this).toggleClass('classA classB classC');
});
I would like to change cell's color by creating it's css.
.classA {
background-color: rgb(0,255,0);
}
.classB {
background: linear-gradient(to bottom, yellow 49%,yellow 1%, rgb(0, 255, 0) 1%,rgb(0, 255, 0) 50%);
}
.classC {
background: linear-gradient(to bottom, yellow 49%,yellow 1%, aqua 1%, aqua 50%);
}
If someone know this method,please let me know.
Thanks
You can try below logic. Create local variable of array of classes. Use data-class-index
attribute for td to be clicked for getting next class.
See below code
$(function(){ var classArray = ['classA','classB','classC']; var arrLen = classArray.length; $("#our_calendar td").click(function() { var classIndex = $(this).data('class-index'); $(this).removeClass(classArray[classIndex]); if(classIndex < (arrLen-1)) { classIndex++; } else { //reset class index classIndex = 0; } $(this).addClass(classArray[classIndex]); $(this).data('class-index',classIndex); }); });
.classA { background-color: rgb(0,255,0); } .classB { background: linear-gradient(to bottom, yellow 49%,yellow 1%, rgb(0, 255, 0) 1%,rgb(0, 255, 0) 50%); } .classC { background: linear-gradient(to bottom, yellow 49%,yellow 1%, aqua 1%, aqua 50%); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="our_calendar"> <tr><td class="classA" data-class-index="0">Date Value 1</td></tr> <tr><td class="classA" data-class-index="0">Date Value 2</td></tr> <tr><td class="classA" data-class-index="0">Date Value 3</td></tr> </table>
you have to call toggle for every class. Referred from ( Toggle multiple element classes with jQuery )
$("#our_calendar td")
.click(function() {
$(this).toggleClass("classA").toggleClass("classB").toggleClass("classC");
});
working fiddle :
You can modify your jQuery to something like below.
$("#our_calendar td").click(function() {
if ($(this).hasClass("classA")) {
$(this).toggleClass("classA classB");
} else if ($(this).hasClass("classB")) {
$(this).toggleClass("classB classC");
} else if ($(this).hasClass("classC")) {
$(this).toggleClass("classC");
}
});
If you are looking to circulate through the classes, You can use below one
$("#our_calendar td").click(function() {
if ($(this).hasClass("classA")) {
$(this).toggleClass("classA classB");
} else if ($(this).hasClass("classB")) {
$(this).toggleClass("classB classC");
} else if ($(this).hasClass("classC")) {
$(this).toggleClass("classC classA");
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.