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.
Related
Its basicly an image, but I want to add some points with dropdowns, and its like 15 points, ajusting it with px would be very time consuming, I wonder if there is any other way around it. Thanks
<div id="map">
<div id="slide">
<img id="mapimg" src="https://i.imgur.com/NLS1KX0.jpg">
<div id="point">
<i id="pointIcon" class="fa-solid fa-location-dot"></i>
</div>
</div>
</div>
$(document).ready(function (){
var scroll_zoom = new ScrollZoom($('#map'),5,0.5)
})
//The parameters are:
//
//container: The wrapper of the element to be zoomed. The script will look for the first child of the container and apply the transforms to it.
//max_scale: The maximum scale (4 = 400% zoom)
//factor: The zoom-speed (1 = +100% zoom per mouse wheel tick)
function ScrollZoom(container,max_scale,factor){
var target = container.children().first()
var size = {w:target.width(),h:target.height()}
var pos = {x:0,y:0}
var scale = 1
var zoom_target = {x:0,y:0}
var zoom_point = {x:0,y:0}
var curr_tranform = target.css('transition')
var last_mouse_position = { x:0, y:0 }
var drag_started = 0
target.css('transform-origin','0 0')
target.on("mousewheel DOMMouseScroll",scrolled)
target.on('mousemove', moved)
target.on('mousedown', function() {
drag_started = 1;
target.css({'cursor':'move', 'transition': 'transform 0s'});
/* Save mouse position */
last_mouse_position = { x: event.pageX, y: event.pageY};
});
target.on('mouseup mouseout', function() {
drag_started = 0;
target.css({'cursor':'default', 'transition': curr_tranform});
});
function scrolled(e){
var offset = container.offset()
zoom_point.x = e.pageX - offset.left
zoom_point.y = e.pageY - offset.top
e.preventDefault();
var delta = e.delta || e.originalEvent.wheelDelta;
if (delta === undefined) {
//we are on firefox
delta = e.originalEvent.detail;
}
delta = Math.max(-1,Math.min(1,delta)) // cap the delta to [-1,1] for cross browser consistency
// determine the point on where the slide is zoomed in
zoom_target.x = (zoom_point.x - pos.x)/scale
zoom_target.y = (zoom_point.y - pos.y)/scale
// apply zoom
scale += delta * factor * scale
scale = Math.max(1,Math.min(max_scale,scale))
// calculate x and y based on zoom
pos.x = -zoom_target.x * scale + zoom_point.x
pos.y = -zoom_target.y * scale + zoom_point.y
update()
}
function moved(event){
if(drag_started == 1) {
var current_mouse_position = { x: event.pageX, y: event.pageY};
var change_x = current_mouse_position.x - last_mouse_position.x;
var change_y = current_mouse_position.y - last_mouse_position.y;
/* Save mouse position */
last_mouse_position = current_mouse_position;
//Add the position change
pos.x += change_x;
pos.y += change_y;
update()
}
}
function update(){
// Make sure the slide stays in its container area when zooming out
if(pos.x>0)
pos.x = 0
if(pos.x+size.w*scale<size.w)
pos.x = -size.w*(scale-1)
if(pos.y>0)
pos.y = 0
if(pos.y+size.h*scale<size.h)
pos.y = -size.h*(scale-1)
target.css('transform','translate('+(pos.x)+'px,'+(pos.y)+'px) scale('+scale+','+scale+')')
}
}
I tried using this, but the image is very long, and it would take to much time, I wonder if there is any easy way to do it.
#point {
position: relative;
overflow: hidden;
margin-left: 338px;
margin-top: -243px;
width: 25px;
height: 25px;
}
I tried using this, but the image is very long, and it would take to much time, I wonder if there is any easy way to do it.
#point {
position: relative;
overflow: hidden;
margin-left: 338px;
margin-top: -243px;
width: 25px;
height: 25px;
}
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'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 been trying to modify a code which scrolls the images horizontally. I want to scroll it vertically. I don't know JQuery at all. After trying for hours I couldn't find any way to sort this thing out. Can anyone help me out in this regard.
Heres the whole code.
$(function() {
$(window).load(function() {
var $gal = $("#propertyThumbnails"),
galW = $gal.outerWidth(true),
galSW = $gal[0].scrollWidth,
wDiff = (galSW / galW) - 1, // widths difference ratio
mPadd = 60, // Mousemove Padding
damp = 20, // Mousemove response softness
mX = 0, // Real mouse position
mX2 = 0, // Modified mouse position
posX = 0,
mmAA = galW - (mPadd * 2), // The mousemove available area
mmAAr = (galW / mmAA); // get available mousemove fidderence ratio
$gal.mousemove(function(e) {
mX = e.pageX - $(this).parent().offset().left - this.offsetLeft;
mX2 = Math.min(Math.max(0, mX - mPadd), mmAA) * mmAAr;
});
setInterval(function() {
posX += (mX2 - posX) / damp; // zeno's paradox equation "catching delay"
$gal.scrollLeft(posX * wDiff);
}, 10);
});
});
#parent {
position: relative;
margin: 0 auto;
width: 100%;
background: #ddd;
}
#propertyThumbnails {
position: relative;
overflow: hidden;
background: #444;
width: 100%;
white-space: nowrap;
}
#propertyThumbnails img {
vertical-align: middle;
display: inline;
margin-left: -4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="parent">
<div id="propertyThumbnails">
<img src="http://placehold.it/1000x100" />
</div>
</div>
Heres the demo:
http://jsbin.com/alokat/1/edit?html,css,js,output
I changed the script as
$(function(){
$(window).load(function(){
var $gal = $("#propertyThumbnails"),
galW = $gal.outerHeight(true),
galSW = $gal[0].scrollHeight,
wDiff = (galSW/galW)-1, // widths difference ratio
mPadd = 60, // Mousemove Padding
damp = 20, // Mousemove response softness
mX = 0, // Real mouse position
mX2 = 0, // Modified mouse position
posX = 0,
mmAA = galW-(mPadd*2), // The mousemove available area
mmAAr = (galW/mmAA); // get available mousemove fidderence ratio
$gal.mousemove(function(e) {
mX = e.pageY - $(this).parent().offset().top - this.offsetTop;
mX2 = Math.min( Math.max(0, mX-mPadd), mmAA ) * mmAAr;
});
setInterval(function(){
posX += (mX2 - posX) / damp; // zeno's paradox equation "catching delay"
$gal.scrollTop(posX*wDiff);
}, 10);
});
});
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.