Bootstrap-datepicker: body margins affects positioning

Created on 8 Jul 2016  路  5Comments  路  Source: uxsolutions/bootstrap-datepicker

Expected behavior

To be displayed properly.

Actual behavior

The calendar is shown with its position affects by the margins of the body element.
I've added via DevTools margins to the body on the sandbox site and it manifested the same behavior.

Datepicker version used

1.6.1.

Example code

Add margin-top and margin left with positive and negative values and see.

Here's the fiddle :)

Most helpful comment

Created a quick patch for this issue. After including bootstrap-datepicker add this code:

<script>
    // This wrapper fixes wrong placement of picker when container has margins.
    var originaldatepicker = $.fn.datepicker;

    $.fn.datepicker = function () {
        var result = originaldatepicker.apply(this, arguments);

        this.on('show', function (e) {
            var $target = $(this),
                $picker = $target.data('datepicker').picker,
                top;

            if ($picker.hasClass('datepicker-orient-top')) {
                top = $target.offset().top - $picker.outerHeight() - parseInt($picker.css('marginTop'));
            } else {
                top = $target.offset().top + $target.outerHeight() + parseInt($picker.css('marginTop'));
            }

            $picker.offset({top: top});
        });

        return result;
    }
</script>

Generally it repositions picker whenever it is shown. Works for version 1.6.4.
Hope sb will find it useful, and the original code will be fixed soon!

All 5 comments

Created a quick patch for this issue. After including bootstrap-datepicker add this code:

<script>
    // This wrapper fixes wrong placement of picker when container has margins.
    var originaldatepicker = $.fn.datepicker;

    $.fn.datepicker = function () {
        var result = originaldatepicker.apply(this, arguments);

        this.on('show', function (e) {
            var $target = $(this),
                $picker = $target.data('datepicker').picker,
                top;

            if ($picker.hasClass('datepicker-orient-top')) {
                top = $target.offset().top - $picker.outerHeight() - parseInt($picker.css('marginTop'));
            } else {
                top = $target.offset().top + $target.outerHeight() + parseInt($picker.css('marginTop'));
            }

            $picker.offset({top: top});
        });

        return result;
    }
</script>

Generally it repositions picker whenever it is shown. Works for version 1.6.4.
Hope sb will find it useful, and the original code will be fixed soon!

this solved my problem, thanks!!

great solution, thanks!!

The patch by @imbrish still works as of now, tested with version 1.8.0

This issue still persists in version 1.9.0, but this solution still works for me. Thanks

Was this page helpful?
0 / 5 - 0 ratings