Draggable elements with AngularJS directives

In this example below you will see how to do a Draggable elements with AngularJS directives with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by 01abhishekjain, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright 01abhishekjain ©

Technologies

  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Draggable elements with AngularJS directives</title>
  
  
  
  
  
</head>

<body>

  <body ng-app="app">
  <div draggable>Drag me</div>
</body>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.6/angular.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/01abhishekjain/draggable-elements-with-angularjs-directives-ypGpEJ */
var app = angular.module("app", []);

app.directive("draggable", function($document) {
  return {
    restrict: "A",
    link: function(scope, element, attr) {
      var startX = 0,
        startY = 0,
        x = 0, 
        y = 0;
      element.css({
        left: "0px",
        top: "0px",
        position: "relative",
        cursor: "pointer"
      });
      element.on("mousedown", function(event) {
        startX = event.pageX - x;
        startY = event.pageY - y; 
        $document.on("mousemove", mousemove);
        $document.on("mouseup", mouseup);
      });

      function mousemove(event) {
        x = event.pageX - startX;
        y = event.pageY - startY;
        element.css({
          left: x + "px",
          top: y + "px"
        });
      }

      function mouseup() {
        $document.off("mousemove", mousemove);
        $document.off("mouseup", mouseup);
      }
    }
  };
});

Comments