css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              doctype html

// Point of entry for Vue
#app
  .draggable(v-drag='{weight: 2}'): .span Drag Me
  .draggable.big(v-drag='{weight: 1.5, friction: 0.85}')
  .draggable(v-drag): .span Throw Me

// Profile link for self-shilling
a.shill(ref='shill' href='https://codepen.io/milesmanners' target='_blank' title='Made by Miles Manners')
            
          
!
            
              @include theme($bg-dark-blue, $blue);

html {
  touch-action: none;
  user-select: none;
}

#app {
  display: flex;
  width: 100%;
  height: 100%;
  align-items: center;
  justify-content: space-around;
}

.draggable {
  background: $primary;
  width: 100px;
  height: 100px;
  transition: background 200ms;
  cursor: grab;
  border-radius: 10px;
  box-shadow: 0 0 0 5px rgba($bg, 0.8);
  display: flex;
  flex-shrink: 0;
  
  * {
    margin: auto;
    pointer-events: none;
  }
  &.pressed { cursor: grabbing }
  &.dragging { background: $secondary }
  
  &.big {
    width: 200px;
    height: 200px;
  }
}
            
          
!
            
              /* jshint esversion: 6, asi: true, boss: true */

// Directive Definitions
Vue.directive('drag', (() => {
  // Debouncer to prevent tons of resize events
  function debounce (func, wait) {
    let timeout
    return function (...args) {
      clearTimeout(timeout)
      timeout = setTimeout(() => {
        timeout = null
        func.apply(this, args)
      }, wait)
    }
  }

  // Should probably be set by the binding
  // Need to disable the resize event if this is changed because it changes right and bottom
  let constraints = {
    top: 0,
    right: window.innerWidth,
    bottom: window.innerHeight,
    left: 0
  }

  // Keep track of the top left of the item
  let initialPos = { x: 0, y: 0 }

  // Helper functions to keep track of events
  function on (vnode, target, fn, ...args) {
    vnode.dragEvents.push({ context: this, target, fn, args })
    this.addEventListener(target, fn, ...args)
  }
  function off (vnode, target, fn, ...args) {
    vnode.dragEvents.filter(e => e.target !== target || e.fn !== fn)
    this.removeEventListener(target, fn, ...args)
  }
  
  // For physics
  let positions = []

  return {
    bind (el, binding, vnode) {
      vnode.animId = null
      vnode.dragEvents = []
      
      // Default options
      let weight = binding.value && binding.value.weight || 1
      let friction = binding.value && binding.value.friction || 0.9
      let minDistance = binding.value && binding.value.minDistance || 5

      vnode.dragResize = () => {
        let bounds = el.getBoundingClientRect()
        let matches = el.style.transform.match(/translate\((-?[\d\.]*)px, (-?[\d\.]*)/)
        let offX = matches && +matches[1] || 0
        let offY = matches && +matches[2] || 0
        vnode.dragInitialPos = { x: bounds.x - offX, y: bounds.y - offY }
        constraints.right = window.innerWidth
        constraints.bottom = window.innerHeight
      }

      window::on(vnode, 'resize', vnode.dragResize, { passive: true })

      // When Mouse pressed
      el::on(vnode, 'pointerdown', e => {
        if (vnode.animId !== null) {
          cancelAnimationFrame(vnode.animId)
          vnode.animId = null
        }
        el.classList.toggle('pressed', true)
        
        // Page position
        let start = { x: e.x, y: e.y }
        // Local position so the item can be dragged from any arbitrary point
        let offset = { x: e.offsetX, y: e.offsetY }

        // Handler to start the dragging
        let move = e => {
          // Waits until the item has been dragged the minimum defined distance
          // Helps with interactive items with inputs, buttons, etc. to prevent accidental dragging
          if (Math.hypot(e.x - start.x, e.y - start.y) > minDistance) {
            // Remove this event so it only occurs once
            document::off(vnode, 'pointermove', move, { passive: true })
            // Remove the old cancel event since we are already dragging
            document::off(vnode, 'pointerup', pointerup, { passive: true })

            let pos = { x: e.x, y: e.y }
            
            // Setup dragging
            el.classList.toggle('dragging', true)
            
            // Drag handler
            let drag = e => {
              vnode.context.$emit('drag', e)
              
              // Find the max right and bottom from where the element is being held
              let right = offset.x - el.offsetWidth
              let bottom = offset.y - el.offsetHeight

              // Clamp the position in the constraints
              pos.x = Math.min(Math.max(constraints.left + offset.x, e.x), constraints.right + right)
              pos.y = Math.min(Math.max(constraints.top + offset.y, e.y), constraints.bottom + bottom)
              
              // Remove positions from more than 75ms ago
              let index = positions.findIndex(p => e.timeStamp - p.timeStamp > 75)
              if (index >= 0) {
                positions.splice(index)
              }
              // Add current position at the beginning of the array
              positions.unshift({ x: pos.x, y: pos.y, timeStamp: e.timeStamp })
              
              // Set the transform to actually move the element
              el.style.transform = `translate(${pos.x - vnode.dragInitialPos.x - offset.x}px, ${pos.y - vnode.dragInitialPos.y - offset.y}px)`
            }

            let stopDrag = e => {
              // Remove events now that dragging is over
              document::off(vnode, 'pointermove', drag, { passive: true })
              document::off(vnode, 'pointerup', stopDrag, { passive: true })
          
              el.classList.toggle('pressed', false)
              el.classList.toggle('dragging', false)
              
              // Remove positions from more than 75ms ago
              let index = positions.findIndex(p => e.timeStamp - p.timeStamp > 75)
              if (index >= 0) {
                positions.splice(index)
              }
              
              // Do physics
              if (positions.length >= 2) {
                // Calculate vectors from points available
                let vectors = []
                for (let i = 0; i < positions.length - 1; i++) {
                  let p1 = positions[i]
                  let p2 = positions[i + 1]
                  vectors.push({
                    x: p1.x - p2.x,
                    y: p1.y - p2.y 
                  })
                }
                
                // Average vectors
                let average = {
                  x: vectors.reduce((a, b) => a + b.x, 0) / vectors.length,
                  y: vectors.reduce((a, b) => a + b.y, 0) / vectors.length
                }
                
                // Get average distance
                let dist = Math.hypot(average.x , average.y)
                let angle = Math.atan2(positions[0].y - positions[1].y, positions[0].x - positions[1].x)
                let speed = dist / weight
                
                let pos = positions[0]
                positions = []

                // Physics
                vnode.animId = requestAnimationFrame(function loop () {
                  let right = offset.x - el.offsetWidth
                  let bottom = offset.y - el.offsetHeight
                  
                  pos.x += speed * Math.cos(angle)
                  pos.y += speed * Math.sin(angle)

                  pos.x = Math.min(Math.max(constraints.left + offset.x, pos.x), constraints.right + right)
                  pos.y = Math.min(Math.max(constraints.top + offset.y, pos.y), constraints.bottom + bottom)
                  
                  el.style.transform = `translate(${pos.x - vnode.dragInitialPos.x - offset.x}px, ${pos.y - vnode.dragInitialPos.y - offset.y}px)`
                  
                  speed *= friction

                  if (speed > 0.1) {
                    vnode.animId = requestAnimationFrame(loop)
                  }
                })
              }
            }

            // Bind the drag events
            document::on(vnode, 'pointermove', drag, { passive: true })
            document::on(vnode, 'pointerup', stopDrag, { passive: true })
          }
        }

        // Handler to cancel the drag start
        let pointerup = e => {
          document::off(vnode, 'pointermove', move, { passive: true })
          document::off(vnode, 'pointerup', pointerup, { passive: true })
          
          el.classList.toggle('pressed', false)
        }

        // Bind the initial events
        document::on(vnode, 'pointermove', move, { passive: true })
        document::on(vnode, 'pointerup', pointerup, { passive: true })
      })
    },
    inserted (el, binding, vnode) {
      // Find the top left of the item once it is in the DOM
      let bounds = el.getBoundingClientRect()
      vnode.dragInitialPos = { x: bounds.left, y: bounds.top }
    },
    unbind (el, binding, vnode) {
      // Remove any remaining events in case it was removed while being dragged
      vnode.dragEvents.forEach(e => {
        e.context::off(vnode, e.target, e.fn, ...e.args)
      })
    }
  }
})())

// Point of entry
new Vue({
  el: '#app'
})
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console