Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change background color of selected date in FullCalendar

I am trying to change the background color of the selected date in my calendar. In my below code, it highlights all the clicked date, how can I only highlight the last clicked date?

dayClick: function (day){
  var mydate = new Date(this[0].getAttribute("data-date"));
  var dateArray = mydate.toDateString().split(" ");
  document.querySelectorAll(".calendar-mobile p")[0].innerHTML = j_monthNames[mydate.getMonth()] + " " + mydate.getDate() + "日" + "(" + j_dayNames[dateArray[0].toLocaleLowerCase()] + ")";
  document.body.classList.remove("calendar-open");

  $month = '' + (mydate.getMonth() + 1);
  $day = '' + mydate.getDate();
  $year = mydate.getFullYear();

  if ($month.length < 2) $month = '0' + $month;
  if ($day.length < 2) $day = '0' + $day;
  $dates = [$year, $month, $day].join('-');
  $('[data-date='+$dates+']').css({"color": "red", "backgroundColor": "yellow",});
},
like image 854
Eem Jee Avatar asked Mar 24 '19 11:03

Eem Jee


2 Answers

I have finally solved it this way:

$(document).ready(function() {
  $('#calendars').fullCalendar({
    header: {
      left: 'prev',
      center: 'title',
      right: 'next'
    },
    selectable: true,
  });
});
.fc-highlight {
  background: green !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.0.1/fullcalendar.min.css" defer/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.0.1/fullcalendar.min.js" defer></script>
<div id="calendars"></div>

Just triggered the .fc-highlight class and it does the trick.

like image 186
Eem Jee Avatar answered Sep 22 '22 09:09

Eem Jee


You've made this way more complicated than it needs to be.

Simply define a CSS class which will set the colours as you wish them to be when added to a day's HTML element.

Then, in the dayClick function, first find all elements which have that class, and remove the class from them. That will stop it showing on previously clicked days.

Next, add the class to the current element (represented by this). Simple!

JS:

dayClick: function (day){
  $(".day-highlight").removeClass("day-highlight");
  $(this).addClass("day-highlight");
}

CSS:

.day-highlight {
  background-color: yellow !important;
  color: red !important;
}

(!important is necessary to override the colour highlight on the current date which is set by fullCalendar automatically.)

Live demo: http://jsfiddle.net/zs9g5a8k/

like image 45
ADyson Avatar answered Sep 25 '22 09:09

ADyson