Drag and Drop using Reactive Extensions for Javascript

You can become a serverless blackbelt. Enrol to my 4-week online workshop Production-Ready Serverless and gain hands-on experience building something from scratch using serverless technologies. At the end of the workshop, you should have a broader view of the challenges you will face as your serverless architecture matures and expands. You should also have a firm grasp on when serverless is a good fit for your system as well as common pitfalls you need to avoid. Sign up now and get 15% discount with the code yanprs15!

Been a while since I’ve been meaning to check out Reactive Extensions for Javascript, I have been using the .Net version for a while now and blogged about some of the cool things you can do with the .Net version.

Although there are many sources where you can learn about it from they don’t have a structured guide to help you get started and some of the info/demo I found were pretty out-dated and not in line with the latest API. Among the articles I’ve read so far I found the series of articles by Matthew Podwysocki on codebetter.com to be most useful and definitely worth reading through if you want get up to speed with RXJS.

Anyways, back to the point of the post, I just wanted to show you how to achieve a simple drag and drop effect using RX, with support for clipping so you can’t drag the outside the parent container.

Here’s the basic HTML for the demo and with some simple CSS how it looks:

   1: <body>

   2:     <div id="wrapper">

   3:         <div id="draggable"></div>

   4:     </div>

   5: </body>

image

The javascript code for the demo is simple:

   1: <script type="text/javascript" src="js/jquery/jquery-1.4.4.min.js"></script>

   2: <script type="text/javascript" src="js/rxjs/rx.js"></script>

   3: <script type="text/javascript" src="js/rxjs/rx.jQuery.js"></script>

   4:

   5: <script type="text/javascript">

   6:     $(function () {

   7:         var _doc = $(document), _draggable = $("#draggable"), _wrapper = $("#wrapper");

   8:

   9:         // boundary so that the draggable content can't move outside of the its container

  10:         var _parent = _draggable.parent(),

  11:             _parentOffset = _parent.offset(),

  12:             _minLeft = _parentOffset.left,

  13:             _minTop = _parentOffset.top,

  14:             _maxLeft = _minLeft + _parent.width() - _draggable.outerWidth(),

  15:             _maxTop = _minTop + _parent.height() - _draggable.outerHeight();

  16:

  17:         // get the stream of events from the mousedown, mousemove and mouseup events

  18:         var mouseDown = _draggable.toObservable("mousedown"),

  19:             mouseMove = _doc.toObservable("mousemove"),

  20:             mouseUp = _doc.toObservable("mouseup");

  21:

  22:         // get the changes in the X and Y direction as the mouse moves

  23:         var mouseMoves = mouseMove.Skip(1).Zip(mouseMove, function (left, right) {

  24:             return {

  25:                 xChange: left.clientX - right.clientX,

  26:                 yChange: left.clientY - right.clientY

  27:             };

  28:         });

  29:

  30:         // for each mouse down event, get all the subsequent changes in the clientX and

  31:         // clientY values resulting from the mouse move events until mouse up event occurs

  32:         var mouseDrags = mouseDown.SelectMany(function (md) {

  33:             return mouseMoves.TakeUntil(mouseUp);

  34:         });

  35:

  36:         mouseDrags.Subscribe(function (mouseEvent) {

  37:             var oldOffset = _draggable.offset();

  38:

  39:             // change the left and top

  40:             _draggable.css({

  41:                 left: Math.min(Math.max(oldOffset.left + mouseEvent.xChange, _minLeft), _maxLeft),

  42:                 top: Math.min(Math.max(oldOffset.top + mouseEvent.yChange, _minTop), _maxTop)

  43:             });

  44:         });

  45:     });

  46: </script>

As you can see, this example uses jQuery and included in the RXJS package is a rx.jQuery.js file which contains a number of extension methods to use with jQuery such as the toObservable function which returns a stream of observable values. If this sounds unfamiliar to you I strongly recommend you to read through the first couple of articles by Matthew Podwysocki I linked above.

On line 23, I’m created a composite event stream by pairing mouse move events with their subsequent mouse move event to work out the change in the X and Y direction. To visualise the two event streams and the resultant mouseMoves stream:

image

Then on line 36, I’ve subscribed an event handler for values pushed down to us through the mouseMoves stream. This event handler applies the X and Y changes to the <div> element’s left and top offset but caps them so that it can only be moved inside its container.

Demo

Parting thoughts

I used jQuery to demonstrate RXJS’s extension functions for jQuery but you don’t need jQuery in order to use RXJS, in the rx.html.js script file there is a very useful Rx.Observable.FromHTMLEvent function which lets you get an observable stream of events from any HTML events including IE-specific events such as ‘oncut‘.

Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my newsletter


Hi, I’m Yan. I’m an AWS Serverless Hero and I help companies go faster for less by adopting serverless technologies successfully.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.


Skill up your serverless game with this hands-on workshop.

My 4-week Production-Ready Serverless online workshop is back!

This course takes you through building a production-ready serverless web application from testing, deployment, security, all the way through to observability. The motivation for this course is to give you hands-on experience building something with serverless technologies while giving you a broader view of the challenges you will face as the architecture matures and expands.

We will start at the basics and give you a firm introduction to Lambda and all the relevant concepts and service features (including the latest announcements in 2020). And then gradually ramping up and cover a wide array of topics such as API security, testing strategies, CI/CD, secret management, and operational best practices for monitoring and troubleshooting.

If you enrol now you can also get 15% OFF with the promo code “yanprs15”.

Enrol now and SAVE 15%.


Check out my new podcast Real-World Serverless where I talk with engineers who are building amazing things with serverless technologies and discuss the real-world use cases and challenges they face. If you’re interested in what people are actually doing with serverless and what it’s really like to be working with serverless day-to-day, then this is the podcast for you.


Check out my video course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. There is something for everyone from beginners to more advanced users looking for design patterns and best practices. Enrol now and start learning!


Check out my video course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. There is something for everyone from beginners to more advanced users looking for design patterns and best practices. Enrol now and start learning!