HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
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.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
If the stylesheet you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by Skypack, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ES6 import
usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
doctype html
// Point of entry for Vue
#app
.draggable(v-drag='{weight: 2, friction: 0.5}'): .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(average.y, average.x)
let speed = dist / weight
console.log(vectors)
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'
})
Also see: Tab Triggers