Duc Doan
Duc Doan

Reputation: 415

jQuery UI Datepicker - Highlight days in between depart/arrive date

I'm trying to highlight days between depart/arrive date. I have found an example that is matched what I wish but it's only working with jQuery 1.7. I'm using jQuery 2.x and live function is not supported in this version, I have tried to use on instead of live but it's not working. Here is my Fiddle. You can see it works with jQuery 1.7.

    $("#depart, #arrive").datepicker({      
        beforeShow: customRange,
    });

    function customRange(input) {
        if (input.id == "arrive") {

            $("#ui-datepicker-div td").live({
                mouseenter: function() {
                    $(this).parent().addClass("finalRow");
                    $(".finalRow").prevAll().find("td:not(.ui-datepicker-unselectable)").addClass("highlight");
                    $(this).prevAll("td:not(.ui-datepicker-unselectable)").addClass("highlight");
               },
                mouseleave: function() {
                    $(this).parent().removeClass("finalRow");
                    $("#ui-datepicker-div td").removeClass("highlight");
                }
            });
        }
    }
.highlight {background-color: #b0d7ed !important;}
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
Depart: <input type="text" id="depart"> <br>
Arrive: <input type="text" id="arrive">

Upvotes: 1

Views: 252

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

Here is your function "adapted" from the deprecated .live() method.
I tested it with jquery 2.2.0, 2.2.4 and 3.1.1 (latest).

It looks like behaving the same as your fiddle in this CodePen.

A small 50ms delay seems necessary for Datepicker to draw the table (calendar), even if not yet visible, before trying to find the td collection (dates).

$("#depart, #arrive").datepicker({      
    beforeShow: function(){
        customRange( $(this).attr("id") );
    }
});

function customRange(input) {

    if (input == "arrive") {

        setTimeout(function(){
            var calendarTD = $("#ui-datepicker-div").find("td");

            calendarTD.on("mouseenter", function(){
                $(this).parent().addClass("finalRow");
                $(".finalRow").prevAll().find("td:not(.ui-datepicker-unselectable)").addClass("highlight");
                $(this).prevAll("td:not(.ui-datepicker-unselectable)").addClass("highlight");
            });
            calendarTD.on("mouseleave",function() {
                $(this).parent().removeClass("finalRow");
                $("#ui-datepicker-div td").removeClass("highlight");
            });
        },50);
    }
}

Upvotes: 2

Related Questions