JSFiddle - React, Tailwind, and code Playground
by gweax
HTML
<label for="uhhuhinput">Say something:</label>
<input type="text" id="uhhuhinput">
<span id="uhhuhwarn"></span>
<div id="drag">Drag me</div>
CSS
body {
padding: 10px;
}
label, span, div {
font-family: sans-serif;
}
.dragged {
box-shadow: 4px 4px 4px rgba(0, 0, 0, 0.3);
}
#drag {
width: 60px;
height: 60px;
background-color: #bada55;
position: absolute;
top : 100px;
left: 100px;
cursor: move;
padding: 3px;
}
.ok {
color: #bada55;
}
.warn {
color: #d00d1e;
}
JavaScript
var delayTimeout, throttleTimeout;
/* Check */
function check() {
var input, warn;
input = document.getElementById("uhhuhinput");
warn = document.getElementById("uhhuhwarn");
if (input.value.indexOf("uh huh") === -1) {
warn.innerHTML = "you did not say 'uh huh' :-(";
warn.className = "warn";
}
else {
warn.innerHTML = "thank you for saying 'uh huh'";
warn.className = "ok";
}
}
function delayCheck() {
window.clearTimeout(delayTimeout);
delayTimeout = window.setTimeout(check, 400);
}
$("input").bind("keyup", delayCheck);
/* drag */
var offsetX, offsetY;
function drag(event) {
var dragElem = $("#drag");
$("#drag").css({
"top": Math.max(0, event.pageY - offsetY),
"left": Math.max(0, event.pageX - offsetX)
});
}
function endDrag() {
$(document).unbind({
"mousemove": throttleDrag,
"mouseup": endDrag
});
$("#drag").removeClass("dragged");
}
function throttleDrag(event) {
if (throttleTimeout) {
return;
}
throttleTimeout = window.setTimeout(function() {
throttleTimeout = null;
drag(event);
}, 50);
}
$("#drag").bind({
"mousedown": function(event) {
var dragElem, offset;
dragElem = $(this);
dragElem.addClass("dragged");
offset = dragElem.offset();
offsetX = event.pageX - offset.left;
offsetY = event.pageY - offset.top;
$(document).bind({
"mousemove": throttleDrag,
"mouseup": endDrag
});
event.preventDefault();
}
});