reggie
reggie

Reputation: 3674

jQuery UI rounding width of element when dragging

When I inspect an element on the page, I see that its width is 83.2 pixels.

I make it "draggable" with jQuery UI:

$el.draggable({
    start: function (event, ui) {
        //$(ui.helper).css('margin', 0); //prevent jumping
        console.log('width:', $(ui.helper).css('width'));
        //console.log('width:', $(ui.helper).width());
        //console.log('width:', $(event.target).css('width'));
    }
});

The output to the console after dragging the element is width: 83px. This is causing a line-break in the elements text later on.

Is the jQuery UI rounding the width and height? How do I get the more accurate value?

Upvotes: 4

Views: 968

Answers (1)

reggie
reggie

Reputation: 3674

I found the answer in this question: https://stackoverflow.com/a/16072668/426266

jQueryUI seems to set the width of the element to an integer value when the element is dragged. Also, $(element).width() will always return a rounded integer value.

I solved the problem like this:

$el.draggable({
    start: function (event, ui) {

        var width = event.target.getBoundingClientRect().width;

        $(ui.helper).css({
            'width': Math.ceil(width)
        });
    }
});

Now there is no longer a line-break in the element when it's dragged.

Upvotes: 4

Related Questions