javascriptrubyfullcalendarturbolinksfullcalendar-3

fullcalendar dynamically change default view based on screen width


I'm using fullcalendar and the below code works for me to render fullcalendar while also using turbolinks.

function eventCalendar() {
  return $('#event_calendar').fullCalendar({
    defaultView: 'agendaWeek',
    header: {
        left: 'prev,today,next',
        center: 'title',
        right: 'agendaDay,agendaWeek'
    },    
  });
};
function clearCalendar() {
  $('#event_calendar').fullCalendar('delete'); // In case delete doesn't work.
  $('#event_calendar').html('');
};
$(document).on('turbolinks:load', eventCalendar);
$(document).on('turbolinks:before-cache', clearCalendar)

However I want to dynamically changeView the defaultView based on screenWidth. Something like this, but it's not working for some reason:

if (window.innerWidth < 800) {
            $('#event_calendar').fullCalendar('changeView', 'agendaDay');
        }

or

if(window.innerWidth < 800){
    $('#event_calendar').fullCalendar('changeView', 'agendaDay');
}else{
    $('#event_calendar').fullCalendar('changeView', 'agendaWeek');
}

How can I adapt it to my calendar? Please help!


Solution

  • If by "dynamically change" you mean you want to change it when the user resizes their browser, then you need to listen for window resize.

    $(window).resize(function() {
      if(window.innerWidth < 800){
        $('#event_calendar').fullCalendar('changeView', 'agendaDay');
      } else {
        $('#event_calendar').fullCalendar('changeView', 'agendaWeek');
      }
    });
    

    But also check your browser console for errors. It looks like as of version 4.0+ those views have been renamed see changelog so you may need to pass different view names like this:

    $(window).resize(function() {
      if(window.innerWidth < 800){
        $('#event_calendar').fullCalendar('changeView', 'timeGridDay');
      } else {
        $('#event_calendar').fullCalendar('changeView', 'timeGridWeek');
      }
    });