Hi I would like to create one very simple meme creator tool. Here is the code to Image and Text. I have drag text on image. could you help ?
<html>
<body>
<div id="draggable-element">Drag me!</div>
<style>
body {padding:10px}
#draggable-element {
width:100px;
height:10px;
background-color:#fff;
color:black;
padding:10px 12px;
cursor:move;
position:relative; /* important (all position that's not `static`) */
}
</style>
<Script>
var selected = null, // Object of the element to be moved
x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element
// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
selected = elem;
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}
// Will be called when user dragging an element
function _move_elem(e) {
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
}
// Destroy the object when we are done
function _destroy() {
selected = null;
}
// Bind the functions...
document.getElementById('draggable-element').onmousedown = function () {
_drag_init(this);
return false;
};
document.onmousemove = _move_elem;
document.onmouseup = _destroy;
</script>
</body>
</html>
This is code for drag text. But I need to drag this on image. How to do this in easy way.
Just use position: absolute; instead of relative.
var selected = null, // Object of the element to be moved
x_pos = 0,
y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0,
y_elem = 0; // Stores top, left values (edge) of the element
// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
selected = elem;
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}
// Will be called when user dragging an element
function _move_elem(e) {
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
}
// Destroy the object when we are done
function _destroy() {
selected = null;
}
// Bind the functions...
document.getElementById('draggable-element').onmousedown = function() {
_drag_init(this);
return false;
};
document.onmousemove = _move_elem;
document.onmouseup = _destroy;
body {
padding: 10px
}
#draggable-element {
width: 100px;
height: 10px;
background-color: #fff;
color: black;
padding: 10px 12px;
cursor: move;
position: absolute;
/* important (all position that's not `static`) */
}
<div id="draggable-element">Drag me!</div>
<img src="https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/>
Related
I'm looking to change opacity and then completely hide div on swipe up on certain threshold, like in the video below or in Photoswipe:
https://www.loom.com/share/29741bdadc7846bfbc747d3870815340
Unfortunately most off libraries only allow to register actual event start end, but not the amount of swiped pixels. How would I get the actual swiped distance and connect it to the swipe event?
Note: You can apply the animations used in this example on other elements like an overlay instead. The technique is the same.
Here is some code to move up an element, fade it out and remove it from display. Note that I only implemented the PointerEvent-api. You should also implement a fallback.
A summary about what is going on:
Detect a pointerdown on the element and allow the pointer to be used outside the element with setPointerCapture().
Detect a pointermove on the element. If the mouse/touch is moved up, also move up the element. ( I also restricted movement to the left, right, bottom, but you don't have to)
Detect a pointerup. After releasePointerCapture() the pointer will once more only be available in the default element and not outside it. Depending on the amount the element has moved up, the element is returned to its original position or animated out.
class SwipeOutBehaviour {
constructor(element) {
this.element = element;
this.dy = null;
this.initial_y = null;
this.animation_frame_state = 'completed';
if( window.PointerEvent ) {
this.element.addEventListener('pointerdown', this.start_drag.bind(this), true);
this.element.addEventListener('pointermove', this.drag.bind(this), true);
this.element.addEventListener('pointerup', this.drag_end.bind(this), true);
} else {
//should use composition instead if you re serious, for this example I only implemented PointerEvent some browsers will use Tpuchevent and MouseEvent
}
}
start_drag( event ){
event.preventDefault();
// only respond to a single touch
if( event.touches && event.touches.length > 1 ) return;
// allow pointerevents outside the target
event.target.setPointerCapture(event.pointerId);
// set initial pos
this.initial_y = ( event.targetTouches ) ? event.targetTouches[0].clientY : event.clientY;
}
drag( event ){
event.preventDefault();
if( this.initial_y === null ) return;
if( this.animation_frame_state === 'pending' ) return;
this.dy = ( event.targetTouches ) ? Math.floor( event.targetTouches[0].clientY - this.initial_y ) : Math.floor( event.clientY - this.initial_y );
if( this.dy > 0 ) return;
this.animation_frame_state = 'pending'
window.requestAnimationFrame( () => {
this.element.style.transform = `translateY(${this.dy}px)`
this.animation_frame_state = 'completed';
});
}
drag_end(event) {
event.preventDefault();
if(event.touches && event.touches.length > 0) return;
event.target.releasePointerCapture(event.pointerId);
if( this.dy < -100 ) {
window.requestAnimationFrame( () => {
this.element.style.transition = 'opacity 500ms, translateY 200ms';
this.element.style.transform = `translateY(-175px)`;
this.element.style.opacity = `0`;
this.animation_frame_state = 'completed';
window.setTimeout( () => {
// set display to none, you could remove it from the DOM instead
this.element.style.display = 'none';
}, 500)
});
} else {
window.requestAnimationFrame( () => {
this.element.style.transform = `translateY(0px)`
this.animation_frame_state = 'completed';
});
}
this.initial_y = null;
}
}
let element = document.getElementById('container');
new SwipeOutBehaviour( element );
#container {
margin: auto;
width: 150px;
height: 150px;
border: 1px solid black;
}
#box-of-doom {
margin: auto;
width: 200px;
height: 200px;
border: 1px solid red;
background: orange;
}
p {
text-align: center;
}
<p>Drag the item in the box of doom<p>
<div id='box-of-doom'>
<p>The box of doom<p>
</div>
<div id='container'>
<img alt='a placeholder' src='https://via.placeholder.com/150' />
</div>
Note: This answer is inspired by this documentation/article from Google about touch events, so you may want to read more there.
With a lot of event listeners and computed properties; I made a quick code pen using W3's draggable function, but added the opacity change myself:
// Make the DIV element draggable:
dragElement(document.getElementById("mydiv"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
// if present, the header is where you move the DIV from:
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
// otherwise, move the DIV from anywhere inside the DIV:
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
//change background opacity:
const background = document.getElementById("background");
const bgHeight = background.offsetHeight;
const elmntHeight = elmnt.offsetHeight;
const adjustedBottom = bgHeight - elmntHeight;
const percentage = 1 - elmnt.offsetTop / adjustedBottom;
console.log(percentage)
background.style.opacity = percentage;
}
function closeDragElement() {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
}
}
body {
margin: 0;
}
#background {
background: black;
width: 100vw;
height: 100vh;
position: absolute;
}
#mydiv {
position: absolute;
z-index: 9;
background-color: #f1f1f1;
border: 1px solid #d3d3d3;
text-align: center;
}
#mydivheader {
padding: 10px;
cursor: move;
z-index: 10;
background-color: #2196F3;
color: #fff;
}
<div id="background"></div>
<!-- Draggable DIV -->
<div id="mydiv">
<!-- Include a header DIV with the same name as the draggable DIV, followed by "header" -->
<div id="mydivheader">Click here to move</div>
<p>Move</p>
<p>this</p>
<p>DIV</p>
</div>
</div>
Far from perfect, but hopefully demonstrates an idea to expand on.
Good day,
Learning Javascript and trying to make draggable elements inside a container.
How to set the draggable border so that elements won't be able to move outside it ?
Right now i have a problem when you drag something to the bottom or right border the element moves outside the container.
fiddle
my HTML looks like this :
<div id="container">
<div id="comboCon1"></div>
<div id="comboCon2"></div>
</div>
Here is the function where i get all positions and call the onmousemove Event :
function OnMouseClickDown(event) {
var target; // -> Element that triggered the event
if (event.target != null) { // -> If Browser is IE than use 'srcElement'
target = event.target;
} else {
target = event.srcElement;
}
// Check which button was clicked and if element has class 'draggable'
if ((event.button == 1 || event.button == 0) && target.className == "draggable") {
// Current Mouse position
startX = event.clientX;
startY = event.clientY;
// Current Element position
offsetX = ExtractNumber(target.style.left); // -> Convert to INT
offsetY = ExtractNumber(target.style.top);
// Border ( Div Container )
minBoundX = target.parentNode.offsetLeft; // Minimal -> Top Position.
minBoundY = target.parentNode.offsetTop;
maxBoundX = minBoundX + target.parentNode.offsetWidth - target.offsetWidth; // Maximal.
maxBoundY = minBoundY + target.parentNode.offsetHeight - target.offsetHeight;
oldZIndex = target.style.zIndex;
target.style.zIndex = 10; // -> Move element infront of others
dragElement = target; // -> Pass to onMouseMove
document.onmousemove = OnMouseMove; // -> Begin drag.
document.body.focus() // -> Cancel selections
document.onselectstart = function () { return false }; // -> Cancel selection in IE.
}
}
And here is onmousemove Event :
function OnMouseMove(event) {
dragElement.style.left = Math.max(minBoundX, Math.min(offsetX + event.clientX - startX, maxBoundX)) + "px";
dragElement.style.top = Math.max(minBoundY, Math.min(offsetY + event.clientY - startY, maxBoundY)) + "px";
}
there is a little change in css for solve this problem, because you are usingf position "relative" the offset of container is given to the child is draged
so in my demo put drag element in position absolute, and change offsetWidth for clientWidth and seems works ( horizontal):
// Draggable Div 1
document.getElementById("comboCon1").style.position = "relative"; // -> Add position relative
document.getElementById("comboCon1").style.width = "151px";
document.getElementById("comboCon1").style.height = "10px";
document.getElementById("comboCon1").setAttribute("class", "draggable");
document.getElementById("comboCon1").style.border = "1px solid black";
document.getElementById("comboCon1").style.padding = "0px";
// Draggable Div 2
document.getElementById("comboCon2").style.position = "relative";
document.getElementById("comboCon2").style.width = "151px";
document.getElementById("comboCon2").setAttribute("class", "draggable");
document.getElementById("comboCon2").style.border = "1px solid black";
document.getElementById("comboCon2").style.padding = "10px";
// Container
document.getElementById("container").style.border = "1px solid black";
document.getElementById("container").style.width = "500px";
document.getElementById("container").style.height = "500px";
//////////////////////
// Begin Drag events
//////////////////////
var startX = 0; //-> Mouse position.
var startY = 0;
var offsetX = 0; // -> Element position
var offsetY = 0;
var minBoundX = 0; // -> Top Drag Position ( Minimum )
var minBoundY = 0;
var maxBoundX = 0; // -> Bottom Drag Position ( Maximum )
var maxBoundY = 0;
var dragElement; // -> Pass the target to OnMouseMove Event
var oldZIndex = 0; // -> Increase Z-Index while drag
// 1)
initDragDrop(); // -> initialize 2 Events.
function initDragDrop() {
document.onmousedown = OnMouseClickDown;
document.onmouseup = OnMouseClickUp;
}
// 2) Click on Element
function OnMouseClickDown(event) {
var target; // -> Element that triggered the event
if (event.target != null) { // -> If Browser is IE than use 'srcElement'
target = event.target;
} else {
target = event.srcElement;
}
// Check which button was clicked and if element has class 'draggable'
if ((event.button == 1 || event.button == 0) && target.className == "draggable") {
// Current Mouse position
startX = event.clientX;
startY = event.clientY;
// Current Element position
offsetX = ExtractNumber(target.style.left); // -> Convert to INT
offsetY = ExtractNumber(target.style.top);
// Border ( Div Container )
minBoundX = target.parentNode.offsetLeft; // Minimal -> Top Position.
console.log(target.parentNode.getBoundingClientRect(), target)
minBoundY = target.parentNode.offsetTop;
maxBoundX = minBoundX + target.parentNode.clientWidth - target.clientWidth; // Maximal.
console.log(maxBoundX, target.parentNode.clientWidth, target.clientWidth);
maxBoundY = minBoundY + target.parentNode.offsetHeight - target.offsetHeight;
oldZIndex = target.style.zIndex;
target.style.zIndex = 10; // -> Move element infront of others
target.style.position = 'absolute'
dragElement = target; // -> Pass to onMouseMove
document.onmousemove = OnMouseMove; // -> Begin drag.
document.body.focus() // -> Cancel selections
document.onselectstart = function () { return false }; // -> Cancel selection in IE.
}
}
// 3) Convert current Element position in INT
function ExtractNumber(value) {
var number = parseInt(value);
if (number == null || isNaN(number)) {
return 0;
}
else {
return number;
}
}
// 4) Drag
function OnMouseMove(event) {
dragElement.style.left = Math.max(minBoundX, Math.min(offsetX + event.clientX - startX, maxBoundX)) + "px";
dragElement.style.top = Math.max(minBoundY, Math.min(offsetY + event.clientY - startY, maxBoundY)) + "px";
}
// 5) Drop
function OnMouseClickUp(event) {
if (dragElement != null) {
dragElement.style.zIndex = oldZIndex; // -> set Z-index 0.
document.onmousemove = null;
document.onselectstart = null;
dragElement = null; // -> No more element to drag.
}
}
I'm making a gadget system in javascript like Win7 Sidebar, but I can use only one element. If I use two, all elements can have the same position or don't work. I need can use more than one elements and drag each one separately (each one with his particular positions).
I have only one element. How can I turn this to work with more than one?
var selected = null, // Object of the element to be moved
x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element
// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
selected = elem;
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}
// Will be called when user dragging an element
function _move_elem(e) {
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
}
// Destroy the object when we are done
function _destroy() {
selected = null;
}
// Bind the functions...
document.getElementById('draggable-element').onmousedown = function () {
_drag_init(this);
return false;
};
document.onmousemove = _move_elem;
document.onmouseup = _destroy;
body {padding:10px}
#draggable-element {
width:125px;
height:125px;
background-color:#666;
color:white;
padding:10px 12px;
cursor:move;
position:relative; /* important (all position that's not `static`) */
}
<div id="draggable-element">Gadget!<div style="width:20px;height:100%;background:#000;position:absolute;top:0;right:-25px"></div></div>
fiddle
Two things to note:
If you want to do something on multiple elements you need to either use class's or tags.
In your _drag_init() function, you set the x_elem and y_elem equal to x_pos and y_pos which are changed in you _move_elem() function. So it add's in the current positioning to the elements offset. So just get rid of the selected.Offset
However, there are still some other calculation issues that you need to work out
var selected = null, // Object of the element to be moved
x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element
// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
selected = elem;
x_elem = x_pos ;
y_elem = y_pos;
}
// Will be called when user dragging an element
function _move_elem(e) {
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
}
// Destroy the object when we are done
function _destroy() {
selected = null;
}
// Bind the functions...
var draggables = document.getElementsByClassName('draggable-element');
for(var i = 0; i < draggables.length; i++){
draggables[i].onmousedown = function () {
_drag_init(this);
return false;
};
}
document.onmousemove = _move_elem;
document.onmouseup = _destroy;
body {padding:10px}
.draggable-element {
width:125px;
height:125px;
background-color:#666;
color:white;
padding:10px 12px;
cursor:move;
position:relative; /* important (all position that's not `static`) */
}
<div class="draggable-element">Gadget!<div style="width:20px;height:100%;background:#000;position:absolute;top:0;right:-25px"></div></div>
<div class="draggable-element">Gadget!<div style="width:20px;height:100%;background:#000;position:absolute;top:0;right:-25px"></div></div>
<div class="draggable-element">Gadget!<div style="width:20px;height:100%;background:#000;position:absolute;top:0;right:-25px"></div></div>
<div class="draggable-element">Gadget!<div style="width:20px;height:100%;background:#000;position:absolute;top:0;right:-25px"></div></div>
<div class="draggable-element">Gadget!<div style="width:20px;height:100%;background:#000;position:absolute;top:0;right:-25px"></div></div>
<div class="draggable-element">Gadget!<div style="width:20px;height:100%;background:#000;position:absolute;top:0;right:-25px"></div></div>
I'm trying to create my own click and drag function in JavaScript without the use of jquery. I know that jquery is easy to implement, but I prefer my own code. What I have, as i click the div, then move the mouse, the div moves to the same spot and doesn't implement a "dragging" look to it. I'm not sure why this is. I want my outcome to be able to move the div over the image that way I can "crop" the image based on the div, etc. My code is:
index.js
function _(element) {
return document.getElementById(element);
}
index.css
body {
background-color: rgb(33, 66, 99);
margin: 0px;
padding: 0px;
}
img {
position:absolute;
}
.selection {
width: 200px;
height: 200px;
background-color: rgb(255,255,255);
position: absolute;
}
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8"/>
<title>Image Cropping</title>
<link rel = "stylesheet" href = "index.css"/>
<script src = "index.js"></script>
</head>
<body>
<div class = "image">
<img src = "model.jpg" alt = "Model" id = "theImage"/>
<div class = "selection" id = "selection"/>
</div>
<script>
_("theImage").ondragstart = function() { return false; };
var m = _("selection");
m.addEventListener("mousedown", mouseDown, false);
window.addEventListener("mouseup", mouseUp, false);
function mouseUp() {
window.removeEventListener("mousemove", move, true);
}
function mouseDown(e) {
window.addEventListener("mousemove", move, true);
}
function move(e) {
var x = m.style.left;
var y = m.style.top;
var mouseX = e.clientX;
var mouseY = e.clientY;
m.style.top += (mouseX - x) + "px";
m.style.left += (mouseY - y) + "px";
// Also tried: m.style.top = (mouseX - x) + "px";
// And : m.style.left = (mouseY - y) + "px";
}
</script>
</body>
</html>
To add the "dragging look to it", you can:
change the cursor (cursor: move;)
keep the cursor's offset relative to the mouse
For the second one, I reused a function I created for one of my projects, for which I implemented drag and drop for mobile, not wanting to use a big library:
/*
* Returns the given element's offset relative to the document.
*/
function realOffset(elem) {
var top = 0, left = 0;
while (elem) {
top = top + parseInt(elem.offsetTop, 10);
left = left + parseInt(elem.offsetLeft, 10);
elem = elem.offsetParent;
}
return { top: top, left: left };
}
Using this function, the math becomes simple:
m.style.left = (mouseX - offset.left) + "px";
m.style.top = (mouseY - offset.top) + "px";
Full demo
_("theImage").ondragstart = function () { return false; };
var m = _("selection"), offset;
m.addEventListener("mousedown", mouseDown, false);
window.addEventListener("mouseup", mouseUp, false);
function mouseUp() { window.removeEventListener("mousemove", move, true); }
function mouseDown(e) {
// SAVE THE OFFSET HERE
offset = {
left: e.pageX - realOffset(m).left,
top: e.pageY - realOffset(m).top
};
window.addEventListener("mousemove", move, true);
}
function move(e) {
// REUSE THE OFFSET HERE
m.style.left = (e.pageX - offset.left) + "px";
m.style.top = (e.pageY - offset.top) + "px";
}
/*
* Returns the given element's offset relative to the document.
*/
function realOffset(elem) {
var top = 0, left = 0;
while (elem) {
top = top + parseInt(elem.offsetTop, 10);
left = left + parseInt(elem.offsetLeft, 10);
elem = elem.offsetParent;
}
return { top: top, left: left };
}
function _(element) { return document.getElementById(element); }
body {
background-color: rgb(33, 66, 99);
margin: 0px;
padding: 0px;
}
img {
position:absolute;
}
.selection {
width: 200px;
height: 200px;
background-color: rgba(255,255,255,.5);
position: absolute;
cursor: move;
}
<div class="image">
<img src="http://i.imgur.com/vxkljMP.jpg" alt="Model" id="theImage" />
<div class="selection" id="selection"></div>
</div>
I have this jsfiddle : http://jsfiddle.net/seekpunk/JDU9f/1/
what I want is when the user do a selection the selected part is zoomed in .Is there anyway to achieve this ?
this is the code so far :
var canvas = document.getElementById("MyCanvas");
var ctx = canvas.getContext('2d'),
w = canvas.width,
h = canvas.height,
x1,
y1,
isDown = false;
var img = new Image();
img.src = "http://www.stockfreeimages.com/static/homepage/female-chaffinch-free-stock-photo-106202.jpg";
canvas.onmousedown = function (e) {
var rect = canvas.getBoundingClientRect();
x1 = e.clientX - rect.left;
y1 = e.clientY - rect.top;
isDown = true;
}
canvas.onmouseup = function () {
isDown = false;
}
canvas.onmousemove = function (e) {
if (!isDown) return;
var rect = canvas.getBoundingClientRect(),
x2 = e.clientX - rect.left,
y2 = e.clientY - rect.top;
ctx.clearRect(0, 0, w, h);
ctx.drawImage(img, 0, 0, w, h);
ctx.strokeRect(x1, y1, x2 - x1, y2 - y1);
}
img.onload = function () {
ctx.drawImage(img, 0, 0, w, h);
};
I can make the selection but how can i zoom the selected part only ? like this example : http://canvasjs.com/docs/charts/basics-of-creating-html5-chart/zooming-panning/
For those looking for zooming functionality without the use of a canvas, here's a pretty foolproof solution using a simple <img />:
$(window).on("load",function() {
//VARS===================================================
var zoom = {
zoomboxLeft:null, zoomboxTop:null, //zoombox
cursorStartX:null, cursorStartY:null, //cursor
imgStartLeft:null, imgStartTop:null, //image
minDragLeft:null,maxDragLeft:null, minDragTop:null,maxDragTop:null
};
//KEY-HANDLERS===========================================
$(document).keydown(function(e) {
if (e.which==32) {e.preventDefault(); if (!$(".zoombox img").hasClass("moving")) {$(".zoombox img").addClass("drag");}} //SPACE
});
$(document).keyup(function(e) {
if (e.which==32) {if (!$(".zoombox img").hasClass("moving")) {$(".zoombox img").removeClass("drag");}} //SPACE
});
//RESET IMAGE SIZE=======================================
$(".reset").on("click",function() {
var zoombox = "#"+$(this).parent().attr("id")+" .zoombox";
$(zoombox+" img").css({"left":0, "top":0, "width":$(zoombox).width(), "height":$(zoombox).height()});
}).click();
//ZOOM&DRAG-EVENTS=======================================
//MOUSEDOWN----------------------------------------------
$(".zoombox img").mousedown(function(e) {
e.preventDefault();
$(".zoombox img").addClass("moving");
var selector = $(this).next();
var zoombox = $(this).parent();
$(zoombox).addClass("active");
//store zoombox left&top
zoom.zoomboxLeft = $(zoombox).offset().left + parseInt($(zoombox).css("border-left-width").replace(/\D+/,""));
zoom.zoomboxTop = $(zoombox).offset().top + parseInt($(zoombox).css("border-top-width").replace(/\D+/,""));
//store starting positions of cursor (relative to zoombox)
zoom.cursorStartX = e.pageX - zoom.zoomboxLeft;
zoom.cursorStartY = e.pageY - zoom.zoomboxTop;
if ($(".zoombox img").hasClass("drag")) {
//store starting positions of image (relative to zoombox)
zoom.imgStartLeft = $(this).position().left;
zoom.imgStartTop = $(this).position().top;
//set drag boundaries (relative to zoombox)
zoom.minDragLeft = $(zoombox).width() - $(this).width();
zoom.maxDragLeft = 0;
zoom.minDragTop = $(zoombox).height() - $(this).height();
zoom.maxDragTop = 0;
} else {
//set drag boundaries (relative to zoombox)
zoom.minDragLeft = 0;
zoom.maxDragLeft = $(zoombox).width();
zoom.minDragTop = 0;
zoom.maxDragTop = $(zoombox).height();
//activate zoom-selector
$(selector).css({"display":"block", "width":0, "height":0, "left":zoom.cursorStartX, "top":zoom.cursorStartY});
}
});
//MOUSEMOVE----------------------------------------------
$(document).mousemove(function(e) {
if ($(".zoombox img").hasClass("moving")) {
if ($(".zoombox img").hasClass("drag")) {
var img = $(".zoombox.active img")[0];
//update image position (relative to zoombox)
$(img).css({
"left": zoom.imgStartLeft + (e.pageX-zoom.zoomboxLeft)-zoom.cursorStartX,
"top": zoom.imgStartTop + (e.pageY-zoom.zoomboxTop)-zoom.cursorStartY
});
//prevent dragging in prohibited areas (relative to zoombox)
if ($(img).position().left <= zoom.minDragLeft) {$(img).css("left",zoom.minDragLeft);} else
if ($(img).position().left >= zoom.maxDragLeft) {$(img).css("left",zoom.maxDragLeft);}
if ($(img).position().top <= zoom.minDragTop) {$(img).css("top",zoom.minDragTop);} else
if ($(img).position().top >= zoom.maxDragTop) {$(img).css("top",zoom.maxDragTop);}
} else {
//calculate selector width and height (relative to zoombox)
var width = (e.pageX-zoom.zoomboxLeft)-zoom.cursorStartX;
var height = (e.pageY-zoom.zoomboxTop)-zoom.cursorStartY;
//prevent dragging in prohibited areas (relative to zoombox)
if (e.pageX-zoom.zoomboxLeft <= zoom.minDragLeft) {width = zoom.minDragLeft - zoom.cursorStartX;} else
if (e.pageX-zoom.zoomboxLeft >= zoom.maxDragLeft) {width = zoom.maxDragLeft - zoom.cursorStartX;}
if (e.pageY-zoom.zoomboxTop <= zoom.minDragTop) {height = zoom.minDragTop - zoom.cursorStartY;} else
if (e.pageY-zoom.zoomboxTop >= zoom.maxDragTop) {height = zoom.maxDragTop - zoom.cursorStartY;}
//update zoom-selector
var selector = $(".zoombox.active .selector")[0];
$(selector).css({"width":Math.abs(width), "height":Math.abs(height)});
if (width<0) {$(selector).css("left",zoom.cursorStartX-Math.abs(width));}
if (height<0) {$(selector).css("top",zoom.cursorStartY-Math.abs(height));}
}
}
});
//MOUSEUP------------------------------------------------
$(document).mouseup(function() {
if ($(".zoombox img").hasClass("moving")) {
if (!$(".zoombox img").hasClass("drag")) {
var img = $(".zoombox.active img")[0];
var selector = $(".zoombox.active .selector")[0];
if ($(selector).width()>0 && $(selector).height()>0) {
//resize zoom-selector and image
var magnification = ($(selector).width()<$(selector).height() ? $(selector).parent().width()/$(selector).width() : $(selector).parent().height()/$(selector).height()); //go for the highest magnification
var hFactor = $(img).width() / ($(selector).position().left-$(img).position().left);
var vFactor = $(img).height() / ($(selector).position().top-$(img).position().top);
$(selector).css({"width":$(selector).width()*magnification, "height":$(selector).height()*magnification});
$(img).css({"width":$(img).width()*magnification, "height":$(img).height()*magnification});
//correct for misalignment during magnification, caused by size-factor
$(img).css({
"left": $(selector).position().left - ($(img).width()/hFactor),
"top": $(selector).position().top - ($(img).height()/vFactor)
});
//reposition zoom-selector and image (relative to zoombox)
var selectorLeft = ($(selector).parent().width()/2) - ($(selector).width()/2);
var selectorTop = ($(selector).parent().height()/2) - ($(selector).height()/2);
var selectorDeltaLeft = selectorLeft - $(selector).position().left;
var selectorDeltaTop = selectorTop - $(selector).position().top;
$(selector).css({"left":selectorLeft, "top":selectorTop});
$(img).css({"left":"+="+selectorDeltaLeft, "top":"+="+selectorDeltaTop});
}
//deactivate zoom-selector
$(selector).css({"display":"none", "width":0, "height":0, "left":0, "top":0});
} else {$(".zoombox img").removeClass("drag");}
$(".zoombox img").removeClass("moving");
$(".zoombox.active").removeClass("active");
}
});
});
/*CONTAINER-------------------*/
#container {
width: 234px;
height: 199px;
margin-left: auto;
margin-right: auto;
}
/*ZOOMBOX=====================*/
/*IMAGE-----------------------*/
.zoombox {
position:relative;
width: 100%;
height: 100%;
border: 2px solid #AAAAAA;
background-color: #666666;
overflow: hidden;
}
.zoombox img {position:relative;}
.zoombox img.drag {cursor:move;}
.zoombox .selector {
display: none;
position: absolute;
border: 1px solid #999999;
background-color: rgba(255,255,255, 0.3);
}
/*CONTROL---------------------*/
.reset {float:left;}
.info {float:right;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<!--ZOOMBOX-->
<div class="zoombox">
<img src="http://www.w3schools.com/colors/img_colormap.gif" />
<div class="selector"></div>
</div>
<input type="button" class="reset" value="Reset" /><span class="info">Press SPACE to drag</span>
</div>
jsfiddle: http://jsfiddle.net/2nt8k8e6/
The container element can be anything, just place the .zoombox on your webpage and it should work.
You should even be able to put multiple .zoomboxes next to each other in the same container-element. I haven't tested it though.
It's not too complicated, there's not a whole lot of comments, but the variable names are pretty self-explanatory and make the code easy enough to read, and all the jquery-functions can be looked up.
The code is essentially divided into three handlers: .mousedown(), .mousemove(), .mouseup().
- In mousedown some values are stored into variables (like the start-coordinates for the selector), which are used in mousemove and mouseup as a reference.
If you want to know exactly what's happening, just have a look at the code, as I said it's not too difficult.