4

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?

reggie
  • 3,523
  • 14
  • 62
  • 97
  • If you're removing the margin, doesn't it make sense that the width is less than it was originally? – Isaac Kleinman Aug 10 '15 at 14:16
  • `Math.round($(ui.helper).width());` use this – rrk Aug 10 '15 at 14:16
  • Isaac, that's what I thought, too. But the width is not reported correctly, even if I remove that line. Rejith: I am not looking to round the value. I want to get the precise floating-point width of the element when it is dragged.. But jQueryUI seems to round the width when the element is dragged. – reggie Aug 10 '15 at 14:33

1 Answers1

4

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.

Community
  • 1
  • 1
reggie
  • 3,523
  • 14
  • 62
  • 97