JSFiddle - React, Tailwind, and code Playground

by Tim Büthe

HTML

<br>
<table id="calendar"/>

CSS

#calendar {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

td {
  border: 1px solid #444;
  width: 50px;
  height: 25px;
  font-size: 8pt;  
  cursor: pointer;    
}

.over {
    background-color: #444;
}

.selected {
    background-color: blue;
}

JavaScript

function pad(x){
    return ('' + x).length === 1 ? '0' + x : '' + x;
}

function selectDaysBetween(date1, date2){
    console.debug('selectDaysBetween: ' + date1 + ' and ' + date2); 
    
    var from = date1 < date2 ? date1 : date2, 
        to   = date2 > date1 ? date2 : date1;
            
    $tds.each(function(){
       var d = $(this).data('date'); 
        if(d >= from && d <= to){
          $(this).addClass('selected');  
        }else{
          $(this).removeClass('selected');    
        }
    });
}

function createTable(){
    
    var $calendar = $('#calendar'),
        $row,
        monthDays = [null, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    
    for(var month=1; month <= 12; month++){
        $row = $('<tr/>').appendTo($calendar);
        for(var day=1; day <= monthDays[month]; day++){
            $('<td/>')
                .data('date', '2012-' + pad(month) + '-' + pad(day))
                .html('' + pad(day))
                .appendTo($row);
        }
    }
}

createTable();

var $calendar = $('#calendar'),
    $tds = $calendar.find('td'),    
    selecting,
    firstSelectedDate;
        
$calendar.on('mouseenter', 'td', function(){    
    if(selecting){
       selectDaysBetween(firstSelectedDate, $(this).data('date'));
    }
    
    $(this).addClass('over');        
});

$calendar.on('mouseleave', 'td', function(){
   $(this).removeClass('over');           
});

$calendar.on('mousedown', 'td', function(){
  selecting = true;
  $(this).addClass('selected'); 
  firstSelectedDate = $(this).data('date');
});

$(document).on('mouseup', function(){
    console.debug('mouseup (' + $tds.length + ')');
    selecting = false;
    $tds.removeClass('selected');
});