Search code examples
fullcalendarfullcalendar-4

How to use snapDuration in fullCalendar?


I am trying to require selectable events to be of fixed duration in fullCalendar (e.g., you can reserve a pickup truck in two-hour intervals), and can begin your selection every half-hour (e.g., you can reserve it from 10:00-12:00 or 10:30-12:30). I am trying to use snapDuration for the former and slotDuration for the latter.

I have tried setting the slotDuration and snapDuration properties for the calendar object, but whenever I select cells on the calendar, it uses the slotDuration. I have also looked for examples where this already works, but all working ones have been for older versions of fullCalendar.

I'm using the main.min.js files for core, interaction, daygrid, and timegrid for the code below. I also have a codepen set up at https://codepen.io/anon/pen/gJXXpw

document.addEventListener('DOMContentLoaded', function() {
  var calendarEl = document.getElementById('calendar');

  var calendar = new FullCalendar.Calendar(calendarEl, {
    plugins: [ 'interaction', 'dayGrid', 'timeGrid' ],
    defaultView: 'timeGridWeek',
    selectable:true,
    select:function(info){
      alert("I'm hoping that it will snap to two hours before I do other stuff inside this function.");
    },
    slotDuration: '00:30',
    snapDuration: '02:00',
    defaultDate: '2019-05-21',
    header: {
      left: 'prev,next today',
      center: 'title',
      right: 'dayGridMonth,timeGridWeek,timeGridDay'
    },
    events: [
      {
        title: 'Birthday Party',
        start: '2019-05-20T07:00:00'
      },
      {
        title: 'Click for Google',
        url: 'http://google.com/',
        start: '2019-05-22'
      }
    ]
  });

  calendar.render();
});

When selecting a time interval to add an event to the calendar, I expect it to "snap" to the snapDuration value (e.g., 2 hours) but it is only constrained by the slotDuration (e.g., 30 minutes). I can add some extra javascript to get the constraint I need, but I would prefer to handle this natively with fullcalendar if possible.


Solution

  • It's not explicitly stated in the documentation but it appears that snapDuration only comes into effect when its duration is smaller than the slotDuration value.

    For example, in your demo, if you change the slotDuration to 4 hours, now you can select the 2-hour intervals in between the marked times.

    slotDuration: '04:00',
    snapDuration: '02:00',
    

    Updated demo: https://codepen.io/anon/pen/EzojoE