RxJS drag capture drag complete

In this example below you will see how to do a RxJS drag capture drag complete with some HTML / CSS and Javascript

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

Technologies

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

<head>
  <meta charset="UTF-8">
  <title>RxJS drag capture drag complete</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <div id="draggable">
  Drag me!
</div>
  <script src='https://unpkg.com/@reactivex/rxjs@5.0.1/dist/global/Rx.js'></script>
<script src='https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js'></script>

  

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




</body>

</html>

/*Downloaded from https://www.codeseek.co/1kohei1/rxjs-drag-capture-drag-complete-KXXaxW */
#draggable {
  background-color: #ccc;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  position: relative;
}

/*Downloaded from https://www.codeseek.co/1kohei1/rxjs-drag-capture-drag-complete-KXXaxW */
const mouseDownStream = Rx.Observable.fromEvent(document.getElementById('draggable'), 'mousedown');
const mouseMoveStream = Rx.Observable.fromEvent(document, 'mousemove');
const mouseUpStream = Rx.Observable.fromEvent(document.getElementById('draggable'), 'mouseup');

let downX = 0;
let downY = 0;
let initialX = 0;
let initialY = 0;

mouseDownStream
  .subscribe(
  downEvent => {
    downX = downEvent.x;
    downY = downEvent.y;
    initialX = _.toNumber(draggable.style.left.split('px')[0]);
    initialY = _.toNumber(draggable.style.top.split('px')[0]);

    mouseMoveStream
      .takeUntil(mouseUpStream)
      .subscribe(
      event => {
        draggable.style.left = `${initialX + event.pageX - downX}px`;
        draggable.style.top = `${initialY + event.pageY - downY}px`;
      },
      err => {

      },
      () => {
        console.log('complete');
      }
    )
  }
)

Comments