jQuery UI draggable With CSS3 Transformations

jQuery UI is ok… decent for quick stuff, but I’m not a huge fan. I had to use it for work the other day and encountered something (which I had seen at least once before). The draggable widget works nice on desktop, but can be choppy on mobile since it just alters css left/top properties.

Anyway, if you do some CSS3 transformations on an element thats a jQuery UI draggable widget the element will jump around because jQuery UI doesn’t properly calculate its offsets in relation to the mouse.

Here is some code that fixes this problem:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title></title>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="http://code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
    <script>
      $(function(){
 
        var transformFix = function(el, e) {
          var offset = el.offset(),
              x = e.pageX - offset.left,
              y = e.pageY - offset.top,
              transform = el.css('transform'),
              dx, dy;
 
          el.css('transform', '');
          offset = el.offset();
          dx = e.pageX - offset.left - x;
          dy = e.pageY - offset.top - y;
          el.css('transform', transform);
 
          return {
            left : x + dx,
            top : y + dy
          };
        };
 
        $('.el').css({
          transform : 'scale(2,2) rotate(35deg)'
        }).draggable()
          .mousedown(function(e) {
            var el = $(this);
            el.draggable('option', { 
              cursorAt: transformFix(el, e)
            });
          });
 
      });
    </script>
    <style>
      .el {
        position : absolute;
        cursor : pointer;
        background : red;
        width : 100px;
        height : 100px;
        left : 200px;
        top : 200px;
      }
    </style>
  </head>
  <body>
    <div class="el"></div>
  </body>
</html>


 
 
 

Leave a Reply

Spam protection by WP Captcha-Free