My inner div is suppose to move around with the mouse cursor on mousemove but i want it to stop at the if statement if it is dragging with the isDragging variable so it will drag smoothly but it seems to not stop any suggestion and help would be appreciated
update: jsFiddle
var yellow = $('#yellow');
var offset = yellow.offset();
var offsetWidth = offset.left + yellow.width();
var offsetHeight = offset.top + yellow.height();
var isDragging = false;
var red = $('#red');
$('#red').hide();
yellow.on('mousedown', function(event) {
$('#red').show();
});
yellow.on('mouseup', function(event) {
$('#red').hide();
});
yellow.on('mousemove', function (e) {
if(e.pageX > offset.left + ($(red).width() / 2) && e.pageX < offsetWidth - ($(red).width() / 2)
&& e.pageY > offset.top + ($(red).height() / 2) && e.pageY < offsetHeight - ($(red).height() / 2) && !isDragging ){
red.css("left", e.pageX - $(red).width() / 2 );
red.css("top", e.pageY - $(red).height() / 2);
}
$('#red').draggable(
{'containment':'#yellow',
start:function(event, ui) {
isDragging = true;
},
drag:function(event, ui) {
isDragging = true;
},stop:function(event, ui) {
isDragging = false;
}
});
});
<div id="yellow">
<div id="red"></div>
</div>
#yellow {
position: absolute;
width: 250px;
height: 250px;
background-color: Yellow;
}
#red {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
z-index: 100;
}
I can't say i am proud of this solution but it seems to get the stuff done:
http://jsfiddle.net/pPn3v/42/
var yellow = $('#yellow');
var offset = yellow.offset();
var offsetWidth = offset.left + yellow.width();
var offsetHeight = offset.top + yellow.height();
var red = $('#red');
yellow.on('mousemove', function (e) {
if(e.pageX+red.width() < offsetWidth
&& e.pageY+red.height() < offsetHeight){
red.css("left", e.pageX);
red.css("top", e.pageY);
}
});
red.on('mousemove', function (e) {
if(e.pageX+red.width() < offsetWidth
&& e.pageY+red.height() < offsetHeight){
red.css("left", e.pageX);
red.css("top", e.pageY);
}
});
Related
Hello guys i have following problem:
Whenever i drag an element it flickers and it looks very annoying. I couldnt find the root of the problem.
Here is my code snippet:
moveElement(element, e) {
let clientX = e.clientX;
let clientY = e.clientY;
let offsetX = e.offsetX;
let offsetY = e.offsetY;
let height = element.getBoundingClientRect().height;
let width = element.getBoundingClientRect().width;
window.requestAnimationFrame(function() {
element.style.setProperty("left", clientX - (width - offsetX) + "px");
element.style.setProperty("top", clientY - (height - offsetY) + "px");
});
}
Here is he full code:
class Dragger{
constructor() {
this.drags = [];
this.drops = [];
this.mover = null;
this.collectDragAndDrop();
}
dragItem(element) {
element.style.setProperty("position", "fixed");
this.mover = this.moveElement.bind(null, element);
element.addEventListener("mousemove", this.mover);
}
moveElement(element, e) {
let clientX = e.clientX;
let clientY = e.clientY;
let offsetX = e.offsetX;
let offsetY = e.offsetY;
let height = element.getBoundingClientRect().height;
let width = element.getBoundingClientRect().width;
window.requestAnimationFrame(function() {
element.style.setProperty("left", clientX - (width - offsetX) + "px");
element.style.setProperty("top", clientY - (height - offsetY) + "px");
});
}
dropItem(element) {
element.removeEventListener("mousemove", this.mover);
}
collectDragAndDrop() {
document.querySelectorAll("[drag]").forEach(element => {
let name = element.attributes.drag.nodeValue;
let findDup = this.drags.some(el => el.name === name);
if (findDup) throw Error("Duplicated drag attribute: " + name);
this.drags.push({
element,
name
});
element.addEventListener("mousedown", this.dragItem.bind(this, element));
element.addEventListener("mouseup", this.dropItem.bind(this, element));
});
}
}
new Dragger();
.box1 {
background: black;
width: 100px;
height: 100px;
color: white;
}
.box2 {
background: red;
width: 100px;
height: 100px;
position: fixed;
right: 100px;
}
<div class="box1" drag="test"></div>
<div class="box2" drag="test2"></div>
Can somebody tell me why this flickers so much?
Your math is wonky. You're only accounting for the current mouse position instead of calculating the amount of movement that has occurred. The only reason your boxes are moving at all is because the function is waiting for the animation frame so there is some change in those coordinates while it waits.
You should also consider that if the mouseup occurs while the mouse is no longer over the element, the element won't get the event and thus will continue dragging when you mouse back over it. It's better to set a flag that keeps track of the mouse state.
var isMouseDown = false;
addEventListener("mousedown", ()=>isMouseDown = true);
addEventListener("mouseup", ()=>isMouseDown = false);
document.querySelectorAll("[drag]").forEach(element=>{
element.addEventListener("mousemove", e=>{
if(!isMouseDown) return;
requestAnimationFrame(function() {
var rect = element.getBoundingClientRect();
element.style.left = rect.x + e.movementX + "px";
element.style.top = rect.y + e.movementY + "px";
});
});
});
.box1 {
background: black;
width: 100px;
height: 100px;
color: white;
position: absolute
}
.box2 {
background: red;
width: 100px;
height: 100px;
position: fixed;
right: 100px;
}
<div class="box1" drag="test"></div>
<div class="box2" drag="test2"></div>
I have a div1 which animates background position on hover direction of mouse by jquery.
But it's working properly. it's going not right direction and I want it to work on every single mouse hover on the div.
Find jsfiddle
code:
$(function() {
$(".mainCont").hover(function(e) {
// $(this).addClass("hoverOnce");
var edge = closestEdge(e.pageX, e.pageY, $(this).width(), $(this).height());
}, function(){
$(this).removeClass('top right bottom left');
// $(this).removeClass("hoverOnce");
});
});
function closestEdge(x,y,w,h) {
var topEdgeDist = distMetric(x,y,w/2,0);
var bottomEdgeDist = distMetric(x,y,w/2,h);
var leftEdgeDist = distMetric(x,y,0,h/2);
var rightEdgeDist = distMetric(x,y,w,h/2);
var min = Math.min(topEdgeDist,bottomEdgeDist,leftEdgeDist,rightEdgeDist);
switch (min) {
case leftEdgeDist:
$(".hoverOnce").addClass("left");
case rightEdgeDist:
$(".hoverOnce").addClass("right");
case topEdgeDist:
$(".hoverOnce").addClass("top");
case bottomEdgeDist:
$(".hoverOnce").addClass("bottom");
}
}
function distMetric(x,y,x2,y2) {
var xDiff = x - x2;
var yDiff = y - y2;
return (xDiff * xDiff) + (yDiff * yDiff);
}
The size of this image that you use in the background is 700x500:
http://thesis2010.micadesign.org/kropp/images/research/bird_icon.png
I think that if you add these settings to .mainCont that this will get you the desired result:
width: 700px;
height: 500px;
position: absolute;
For example:
.mainCont {
width: 700px;
height: 500px;
background: url(http://thesis2010.micadesign.org/kropp/images/research/bird_icon.png) no-repeat center center;
transition: all 0.5s ease-in-out;
margin: 100px auto;
position: absolute;
}
Fiddle
Finally, It got solved.
find fiddle demo
$('.mainCont').hover(function(e){
var dir = determineDirection($(this), {x: e.pageX, y: e.pageY});
$(this).addClass('direction_'+dir);
}, function() {
$(this).removeClass('direction_3 direction_1 direction_2 direction_0');
});
function determineDirection($el, pos){
var w = $el.width(),
h = $el.height(),
x = (pos.x - $el.offset().left - (w/2)) * (w > h ? (h/w) : 1),
y = (pos.y - $el.offset().top - (h/2)) * (h > w ? (w/h) : 1);
return Math.round((((Math.atan2(y,x) * (180/Math.PI)) + 180)) / 90 + 3) % 4;
}
I have a div which I want to resize from all sides and corners, i.e. nw, n, ne, e, w, sw, s, se. I have tried jquery ui's resizable plugin but in my code that is not working. I have removed complexity from my code and placed it in a very basic fiddle.
I have tried to resize only north-west corner of a div and put that logic in fiddle. Logic seems correct to me but mouse interaction is working in a weird way.
Can you guys tell me what am I doing wrong here? If I get it correct for top left corner I can manage for the remaining ones. Thanks.
HTML:
<div id="box">
<div id="nw"></div>
<div id="n"></div>
<div id="ne"></div>
<div id="w"></div>
<div id="e"></div>
<div id="sw"></div>
<div id="s"></div>
<div id="se"></div>
</div>
<p class="one"></p>
<p class="two"></p>
CSS:
#box{border:1px solid #000;width:100px;height:100px;background-color:red;position:absolute;top:100px;left:100px}
#box > div{height:10px;width:10px;background-color:#000;position:absolute}
#nw{top:-5px;left:-5px;cursor:nw-resize}
#n{top:-5px;left:45px;cursor:n-resize}
#ne{top:-5px;right:-5px;cursor:ne-resize}
#w{top:45px;left:-5px;cursor:w-resize}
#e{top:45px;right:-5px;cursor:e-resize}
#sw{bottom:-5px;left:-5px;cursor:sw-resize}
#s{bottom:-5px;left:45px;cursor:s-resize}
#se{bottom:-5px;right:-5px;cursor:se-resize}
p{margin-top:250px;font-size:8px}
JS:
$(function(){
var mousepress = false;
$("#box > div").mousedown(function(e){
mousepress = true;
});
$("#box > div").mousemove(function(e){
if(mousepress) {
var boxX = $("#box").position().left;
var boxY = $("#box").position().top;
var boxW = $("#box").width();
var boxH = $("#box").height();
var x = boxX - e.pageX;//$(this).position().left;
var y = boxY - e.pageY;//$(this).position().top;
$("p.two").append("x: "+x+"<br />");
$(this).css({
"top":y+"px",
"left":x+"px"
});
$("#box").css({
"top":(boxY+y-5)+"px",
"left":(boxX+x-5)+"px",
"width":(boxW+x)+"px",
"height":(boxH+y)+"px",
});
}
});
$("#box > div").mouseup(function(){
mousepress = false;
});
});
**JSFIDDLE: **http://jsfiddle.net/ashwyn/v8qoLj76/2/
I didn't quite understand how you calculated the size and position of the box, without knowing which of the inside divs the user pressed.
I have changed it to use the mouse event position.
I also moved the mousemove and mouseup events to the document, because when dragging using the mouse, it may move faster then the DOM and got out of the box.
I also changed positions of inside divs to use 50% so it will always be in the middle. You may need to add a bit of margin to have it better centered. (See north vs south - I added margin-left to one of them)
This works fine for me.
http://jsfiddle.net/v8qoLj76/4/
var prev_x = -1;
var prev_y = -1;
var dir = null;
$("#box > div").mousedown(function(e){
prev_x = e.clientX;
prev_y = e.clientY;
dir = $(this).attr('id');
});
$(document).mousemove(function(e){
if (prev_x == -1)
return;
var boxX = $("#box").position().left;
var boxY = $("#box").position().top;
var boxW = $("#box").width();
var boxH = $("#box").height();
var dx = e.clientX - prev_x;
var dy = e.clientY - prev_y;
//Check directions
if (dir.indexOf('n') > -1) //north
{
boxY += dy;
boxH -= dy;
}
if (dir.indexOf('s') > -1) //south
{
boxH += dy;
}
if (dir.indexOf('w') > -1) //west
{
boxX += dx;
boxW -= dx;
}
if (dir.indexOf('e') > -1) //east
{
boxW += dx;
}
$("#box").css({
"top":(boxY)+"px",
"left":(boxX)+"px",
"width":(boxW)+"px",
"height":(boxH)+"px",
});
prev_x = e.clientX;
prev_y = e.clientY;
});
$(document).mouseup(function(){
prev_x = -1;
prev_y = -1;
});
Is it something that you need (see the snippet below)?
$(function() {
var ORIGINAL_TOP = 100, ORIGINAL_LEFT = 100, ORIGINAL_WIDTH = 100, ORIGINAL_HEIGHT = 100, OFFSET = 5;
$('.top').css({top: (ORIGINAL_TOP - OFFSET) + 'px'});
$('.left').css({left: (ORIGINAL_LEFT - OFFSET) + 'px'});
$('.bottom').css({top: (ORIGINAL_TOP + ORIGINAL_HEIGHT - OFFSET) + 'px'});
$('.right').css({left: (ORIGINAL_LEFT + ORIGINAL_WIDTH - OFFSET) + 'px'});
$('.control-element').css({height: (2 * OFFSET) + 'px', width: (2 * OFFSET) + 'px'});
var moveMiddleControls = function(top, left, width, height) {
['top', 'bottom'].forEach(function(coordinate) {
$('#' + coordinate).css({left: (left + width / 2 - OFFSET) + 'px'});
});
['left', 'right'].forEach(function(coordinate) {
$('#' + coordinate).css({top: (top + height / 2 - OFFSET) + 'px'});
});
};
var resizeBox = function(top, left, width, height) {
$('#box').css({
top: top + 'px',
left: left + 'px',
width: width + 'px',
height: height + 'px'
});
};
var updateStatus = function(top, left, width, height) {
$('#status-top').html(Math.round(top));
$('#status-left').html(Math.round(left));
$('#status-width').html(Math.round(width));
$('#status-height').html(Math.round(height));
};
var updatePosition = function(top, left, width, height) {
resizeBox(top, left, width, height);
moveMiddleControls(top, left, width, height);
updateStatus(top, left, width, height);
};
var update = function() {
updatePosition(
$('#top').position().top + OFFSET,
$('#left').position().left + OFFSET,
$('#right').position().left - $('#left').position().left,
$('#bottom').position().top - $('#top').position().top
);
};
update();
var activeElement;
$('.control-element').mousedown(function(e) {
activeElement = this;
e.preventDefault();
return false;
});
$(document).mousemove(function(e) {
if(activeElement !== undefined) {
['top', 'bottom'].forEach(function(className) {
if($(activeElement).hasClass(className)) {
$('.' + className).css({top: e.pageY + 'px'});
}
});
['left', 'right'].forEach(function(className) {
if($(activeElement).hasClass(className)) {
$('.' + className).css({left: e.pageX + 'px'});
}
});
update();
}
});
$(document).mouseup(function() {
activeElement = undefined;
});
});
#box {
border:1px solid #000;
background-color:red;
position: fixed;
}
.control-element {
background-color: #000;
position: fixed;
}
#top-left {
cursor: nw-resize;
}
#top {
cursor:n-resize;
}
#top-right {
cursor:ne-resize;
}
#left {
cursor:w-resize;
}
#right {
cursor:e-resize;
}
#bottom-left {
cursor:sw-resize;
}
#bottom {
cursor:s-resize;
}
#bottom-right {
cursor: se-resize;
}
.status {
position:fixed;
right: 5px;
bottom: 10px;
width: 80px;
height: 80px;
z-index: 999;
font-size:8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="box"></div>
<div id="top-left" class="control-element top left"></div>
<div id="top" class="control-element top"></div>
<div id="top-right" class="control-element top right"></div>
<div id="right" class="control-element right"></div>
<div id="bottom-right" class="control-element bottom right"></div>
<div id="bottom" class="control-element bottom"></div>
<div id="bottom-left" class="control-element bottom left"></div>
<div id="left" class="control-element left"></div>
<div class="status">
<div>top: <span id="status-top"></span>px</div>
<div>left: <span id="status-left"></span>px</div>
<div>width: <span id="status-width"></span>px</div>
<div>height: <span id="status-height"></span>px</div>
</div>
I have a dynamic div, and I want to know when the mouse is hover this div. I tryed with .is( ':hover' ) but doesn't work.
jsFiddle demo
In the demo I have made a moving div and if I doesn't move the mouse the log is never called, but if I put manually the mouse hover the box it write always the logs.
Never writes the log in the console.
Always writes the log in the console, even the box is gone.
It's a bug or I have made a mistake? How can I detect the hover properly?
You should be tracking the mouse movement with the mousemove() event and check the last known position of the mouse on the movement of the div.
Example:
HTML & CSS:
.red-box {
display : inline-block;
position : absolute;
width : 50px;
height : 50px;
top : 10px;
left : 0px;
background-color : red;
}
#wrapper {
height: 100vh;
width: 100vw;
}
<div id="wrapper">
<div class="red-box"></div>
</div>
JavaScript:
var posX = 0;
var step = 10;
var maxX = 200;
var mouseX = -1;
var mouseY = -1;
var entered = false;
var $box = $('.red-box');
setInterval(function () {
posX += step;
if (posX >= maxX)
posX = 0;
$box.css("left", posX);
var top = $box.offset().top;
if (mouseX >= posX && mouseX <= (posX + $box.width()) && mouseY >= top && mouseY <= (top + $box.height())) {
console.log("mouse entered");
entered = true;
} else if (entered) {
console.log("mouse left");
entered = false;
}
}, 500);
$("#wrapper").on("mousemove", function (e) {
mouseX = e.pageX - $(this).position().left;
mouseY = e.pageY - $(this).position().top;
}).on("mouseleave", function()
{
mouseX = -1;
mouseY = -1;
});
FIDDLE
Edit: Added a new mouseleave() event to the wrapper.
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.