Coveo Date Slider - Fixing Some Unintuitive Default Behavior

There are times when you want to add a date range filter to your Coveo search page. For that, the Coveo Date Slider facet is very useful. On a recent project, however, I came across a pretty obvious limitation to this facet; I might even dare call it a design flaw.

In my application of this facet, I needed it to filter date ranges corresponding to years. These years ranged from about 1957 to the present year, with search results for almost every year. One unexpected behavior was when I slid the left (min) slider all the way to the right. The facet range would then display from 2019 to 2019, which a normal user would assume should show all results from the current year. However, the behavior of this facet when you slide the one slider onto the other is that both slider range values become identical. Instead of the range being from the beginning of 2019 to the end of 2019, the range becomes from the end of 2019 to the end of 2019, which ends up showing zero results.

So, to fix this issue in my application, we need to find a way to override the min slider value to be Jan. 1 of the selected year, and the max slider to be Dec. 31 of the selected year. Here's how I did it. You need a way to select the DOM element containing the Coveo facet with the date slider. I did it through the "title" data attribute, but you can do it through any other unique parts of the HTML container.

$('*[data-title="Publication Date"]').on(Coveo.SliderEvents.duringSlide, function () {
var publicationDateFacet = $('*[data-title="Publication Date"]');
var publicationDateValues = publicationDateFacet.coveo().getSelectedValues();
var setMinDate;
var setMaxDate;
if (publicationDateValues[0]) {
    //Gets the min date and sets it to Jan 1 of the year
    var minDate = new Date(publicationDateValues[0]);
    var jan1MinDate = new Date(minDate.getFullYear(), 0, 1);
    setMinDate = jan1MinDate.getTime();
}
if (publicationDateValues[1]) {
    //Gets the max date and sets it to Dec 31 of the year
    var maxDate = new Date(publicationDateValues[1]);
    var dec31MaxDate = new Date(maxDate.getFullYear(), 11, 31)
    setMaxDate = dec31MaxDate.getTime();
}
if (setMinDate && setMaxDate) {
    publicationDateFacet.coveo().setSelectedValues([setMinDate, setMaxDate]);
}
});

For your application, depending on how granular of a date range you have set up (whether you are using years, months, or even days), you can modify the code to assume the first of the selected month, or the first minute of the selected day, etc. The javascript Date object constructor has several overrides that would allow you to create a Date object to select any time you would want, down to the millisecond. 

I hope that helps!

Add comment