Search code examples
javascriptjquerydaterangepicker

To close daterangepicker on mouseleave event


I am using the daterangepicker library in my application. I want to trigger daterangepicker's internal method .hide() once use leaves daterangepicker container area. My code looks like this.

<body class="visual-sandbox">
   <div class="visual-rangepicker">
      <div id="reportrange" class="report-range">
          <div class="calendar-icon">
            <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>
          </div>&nbsp;
          <span></span> <b class="caret caret-dropdown"></b>
        </div>
   </div>
</body>

$("#reportrange").daterangepicker(
        {
          startDate: start,
          endDate: end,
          opens: 'left',
          ranges: {
            // new Date(2017, 11, 1)
            Today: [moment(new Date()), moment(new Date())],
            Yesterday: [
              moment(new Date()).subtract(1, "days"),
              moment(new Date()).subtract(1, "days")
            ],
            "Last 7 Days": [moment(new Date()).subtract(6, "days"), moment(new Date())],
            "Last 30 Days": [moment(new Date()).subtract(29, "days"), moment(new Date())],
            "This Month": [moment(new Date()).startOf("month"), moment(new Date()).endOf("month")],
            "Last Month": [
              moment(new Date())
                .subtract(1, "month")
                .startOf("month"),
              moment(new Date())
                .subtract(1, "month")
                .endOf("month")
            ],
            "Last Year": [
              moment(new Date())
                .subtract(1, "year")
                .startOf("year"),
              moment(new Date())
                .subtract(1, "year")
                .endOf("year"),
            ]
          }
        },
        cb
      ).on;
      cb(start, end);

Now let's say #reportrange containing area is body tag. I want to apply something like this function and close the current open daterangepicker.

$('body').on('mouseleave', function(){
      $('#reportrange').trigger('hide.daterangepicker'); //it doesn't work.
    });

A simple solution like.

$('body').on('mouseleave', function(){
      $('#reportrange').hide();
    });

works and hides that particular area but user have to click twice to open that daterangepicker again. As fist click is again closing picker ( toggle ) and second click is opening it.

To understand it properly, if you go to this JSFiddle https://jsfiddle.net/rg7fh1a8/ Now if the user hovers outside area of it, I want to close this daterangepicker.


Solution

  • I know there's already an accepted answer, but I think this could also be useful because it's using the daterangepicker's native hide function instead of simulating a click on cancel button:

    $(function(){
        $('.daterangepicker').mouseleave(function(){
            $('#reportrange').data('daterangepicker').hide();
        });
    });