Javascript resize and crop on mobile devices - javascript

I implement this resize and crop tool on my website : http://tympanus.net/codrops/2014/10/30/resizing-cropping-images-canvas/
I changed some codes to have what I want, like a final crop picture with a size of 390px * 390px.
It works fine, but my site is responsive, and on a mobile device, the website width is 320px.
How can I changed my code to, on mobile version, have a smallest crop zone, but a final picture of 390px * 390px ?
Thanks.
Javascript code :
var resizeableImage = function(image_target) {
// Some variable and settings
var $container,
orig_src = new Image(),
image_target = $(image_target).get(0),
event_state = {},
constrain = false,
min_width = 100, // Change as required
min_height = 100,
max_width = 900, // Change as required
max_height = 900,
resize_canvas = document.createElement('canvas');
init = function(){
// When resizing, we will always use this copy of the original as the base
orig_src.src=image_target.src;
// Wrap the image with the container and add resize handles
$(image_target).wrap('<div class="resize-container"></div>')
.before('<span class="resize-handle resize-handle-nw"></span>')
.before('<span class="resize-handle resize-handle-ne"></span>')
.after('<span class="resize-handle resize-handle-se"></span>')
.after('<span class="resize-handle resize-handle-sw"></span>');
// Assign the container to a variable
$container = $(image_target).parent('.resize-container');
// Add events
$container.on('mousedown touchstart', '.resize-handle', startResize);
$container.on('mousedown touchstart', 'img', startMoving);
$('.js-crop').on('click', crop);
};
startResize = function(e){
e.preventDefault();
e.stopPropagation();
saveEventState(e);
$(document).on('mousemove touchmove', resizing);
$(document).on('mouseup touchend', endResize);
};
endResize = function(e){
e.preventDefault();
$(document).off('mouseup touchend', endResize);
$(document).off('mousemove touchmove', resizing);
};
saveEventState = function(e){
// Save the initial event details and container state
event_state.container_width = $container.width();
event_state.container_height = $container.height();
event_state.container_left = $container.offset().left;
event_state.container_top = $container.offset().top;
event_state.mouse_x = (e.clientX || e.pageX || e.originalEvent.touches[0].clientX) + $(window).scrollLeft();
event_state.mouse_y = (e.clientY || e.pageY || e.originalEvent.touches[0].clientY) + $(window).scrollTop();
// This is a fix for mobile safari
// For some reason it does not allow a direct copy of the touches property
if(typeof e.originalEvent.touches !== 'undefined'){
event_state.touches = [];
$.each(e.originalEvent.touches, function(i, ob){
event_state.touches[i] = {};
event_state.touches[i].clientX = 0+ob.clientX;
event_state.touches[i].clientY = 0+ob.clientY;
});
}
event_state.evnt = e;
};
resizing = function(e){
var mouse={},width,height,left,top,offset=$container.offset();
mouse.x = (e.clientX || e.pageX || e.originalEvent.touches[0].clientX) + $(window).scrollLeft();
mouse.y = (e.clientY || e.pageY || e.originalEvent.touches[0].clientY) + $(window).scrollTop();
// Position image differently depending on the corner dragged and constraints
if( $(event_state.evnt.target).hasClass('resize-handle-se') ){
width = mouse.x - event_state.container_left;
height = mouse.y - event_state.container_top;
left = event_state.container_left;
top = event_state.container_top;
} else if($(event_state.evnt.target).hasClass('resize-handle-sw') ){
width = event_state.container_width - (mouse.x - event_state.container_left);
height = mouse.y - event_state.container_top;
left = mouse.x;
top = event_state.container_top;
} else if($(event_state.evnt.target).hasClass('resize-handle-nw') ){
width = event_state.container_width - (mouse.x - event_state.container_left);
height = event_state.container_height - (mouse.y - event_state.container_top);
left = mouse.x;
top = mouse.y;
if(constrain || e.shiftKey){
top = mouse.y - ((width / orig_src.width * orig_src.height) - height);
}
} else if($(event_state.evnt.target).hasClass('resize-handle-ne') ){
width = mouse.x - event_state.container_left;
height = event_state.container_height - (mouse.y - event_state.container_top);
left = event_state.container_left;
top = mouse.y;
if(constrain || e.shiftKey){
top = mouse.y - ((width / orig_src.width * orig_src.height) - height);
}
}
// Optionally maintain aspect ratio
if(constrain || e.shiftKey){
height = width / orig_src.width * orig_src.height;
}
/*if(width > min_width && height > min_height && width < max_width && height < max_height){
// To improve performance you might limit how often resizeImage() is called
resizeImage(width, height);
// Without this Firefox will not re-calculate the the image dimensions until drag end
$container.offset({'left': left, 'top': top});
}*/
if(width > min_width && height > min_height /*&& width < max_width && height < max_height*/){
// To improve performance you might limit how often resizeImage() is called
resizeImage(width, height);
// Without this Firefox will not re-calculate the the image dimensions until drag end
$container.offset({'left': left, 'top': top});
}
}
resizeImage = function(width, height){
resize_canvas.width = width;
resize_canvas.height = height;
resize_canvas.getContext('2d').drawImage(orig_src, 0, 0, width, height);
$(image_target).attr('src', resize_canvas.toDataURL("image/png"));
};
startMoving = function(e){
e.preventDefault();
e.stopPropagation();
saveEventState(e);
$(document).on('mousemove touchmove', moving);
$(document).on('mouseup touchend', endMoving);
};
endMoving = function(e){
e.preventDefault();
$(document).off('mouseup touchend', endMoving);
$(document).off('mousemove touchmove', moving);
};
moving = function(e){
var mouse={}, touches;
e.preventDefault();
e.stopPropagation();
touches = e.originalEvent.touches;
mouse.x = (e.clientX || e.pageX || touches[0].clientX) + $(window).scrollLeft();
mouse.y = (e.clientY || e.pageY || touches[0].clientY) + $(window).scrollTop();
$container.offset({
'left': mouse.x - ( event_state.mouse_x - event_state.container_left ),
'top': mouse.y - ( event_state.mouse_y - event_state.container_top )
});
// Watch for pinch zoom gesture while moving
if(event_state.touches && event_state.touches.length > 1 && touches.length > 1){
var width = event_state.container_width, height = event_state.container_height;
var a = event_state.touches[0].clientX - event_state.touches[1].clientX;
a = a * a;
var b = event_state.touches[0].clientY - event_state.touches[1].clientY;
b = b * b;
var dist1 = Math.sqrt( a + b );
a = e.originalEvent.touches[0].clientX - touches[1].clientX;
a = a * a;
b = e.originalEvent.touches[0].clientY - touches[1].clientY;
b = b * b;
var dist2 = Math.sqrt( a + b );
var ratio = dist2 /dist1;
width = width * ratio;
height = height * ratio;
// To improve performance you might limit how often resizeImage() is called
resizeImage(width, height);
}
};
crop = function(){
//Find the part of the image that is inside the crop box
var crop_canvas,
left = $('.overlay').offset().left - $container.offset().left,
top = $('.overlay').offset().top - $container.offset().top,
width = $('.overlay').width(),
height = $('.overlay').height();
crop_canvas = document.createElement('canvas');
crop_canvas.width = width;
crop_canvas.height = height;
crop_canvas.getContext('2d').drawImage(image_target, left, top, width, height, 0, 0, width, height);
//window.open(crop_canvas.toDataURL("image/png"));
var canvasData = crop_canvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'upload_picture.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData)
}
init();
};
HTML code :
<div id="crop_canvas">
<div class="overlay">
<div class="overlay-inner"></div>
</div>
<img class="resize-image" src="mypicture.jpg" />
</div>
<button class="btn-crop js-crop">Découper</button>
CSS code :
.resize-container {
position: relative;
display: inline-block;
cursor: move;
margin: 0 auto;
}
.resize-container img {
display: block
}
.resize-container:hover img,
.resize-container:active img {
outline: 2px dashed rgba(222,60,80,.9);
}
.resize-handle-ne,
.resize-handle-ne,
.resize-handle-se,
.resize-handle-nw,
.resize-handle-sw {
position: absolute;
display: block;
width: 10px;
height: 10px;
background: rgba(222,60,80,.9);
z-index: 999;
}
.resize-handle-nw {
top: -5px;
left: -5px;
cursor: nw-resize;
}
.resize-handle-sw {
bottom: -5px;
left: -5px;
cursor: sw-resize;
}
.resize-handle-ne {
top: -5px;
right: -5px;
cursor: ne-resize;
}
.resize-handle-se {
bottom: -5px;
right: -5px;
cursor: se-resize;
}
.overlay {
position: absolute;
left:40%;
top:31%;
margin-left: -100px;
margin-top: -100px;
z-index: 999;
width:390px;
height:390px;
border: solid 2px #f8b028;
box-sizing: content-box;
pointer-events: none;
}
.overlay:after,
.overlay:before {
content: '';
position: absolute;
display: block;
width: 394px;
height: 40px;
border-left: dashed 2px #f8b028;
border-right: dashed 2px #f8b028;
}
.overlay:before {
top: 0;
margin-left: -2px;
margin-top: -40px;
}
.overlay:after {
bottom: 0;
margin-left: -2px;
margin-bottom: -40px;
}
.overlay-inner:after,
.overlay-inner:before {
content: '';
position: absolute;
display: block;
width: 40px;
height: 394px;
border-top: dashed 2px #f8b028;
border-bottom: dashed 2px #f8b028;
}
.overlay-inner:before {
left: 0;
margin-left: -40px;
margin-top: -2px;
}
.overlay-inner:after {
right: 0;
margin-right: -40px;
margin-top: -2px;
}
.btn-crop {
position: absolute;
vertical-align: bottom;
right:20px;
bottom:13px;
padding: 6px 10px;
z-index: 999;
background-color:#f8b028;
border: none;
border-radius:0 0 5px 5px;
color: #FFF;
font-weight:700;
text-transform:uppercase;
}
#crop_modal .modal-dialog{width:980px;}
#crop_modal .modal-content{
background:#0082c6;
border-radius:0;
padding:10px 20px;
}
#crop_modal .modal-content p{
color:#fff;
font-size:12px;
}
#crop_canvas{
background:#fff;
border:3px solid #f8b028;
height:600px;
overflow:hidden;
margin-bottom:35px;
position:relative;
width:100%;
}
You can find a demo here : http://darkcid.olympe.in/

Related

Div Following Cursor With Dead Zone

I am trying to make an element follow the cursor with an added dead zone behaviour.
As long as the cursor moves within a radius of 100 pixels around the element, then the element should not move. Otherwise the element should follow behind the cursor when the 100 pixel radius is exceeded (in any direction). I don't want the orb to catch up with the cursor so it would prevent clicking on other elements, but rather stay on the edge of the dead zone.
In my example, the element is pushed away from the cursor, which is not what I want.
NOTE: I want a native JavaScript solution that doesn't use a library, like jQuery's stop().animate().
const $TheOrb = document.getElementById('TheOrb')
const deadzone = 100
document.addEventListener('mousemove', (event = {}) => {
const x = Math.abs(event.pageX - ($TheOrb.getBoundingClientRect().left + $TheOrb.clientWidth / 2))
const y = Math.abs(event.pageY - ($TheOrb.getBoundingClientRect().top + $TheOrb.clientHeight / 2))
if (x > deadzone || y > deadzone)
$TheOrb.style.transform = `translate(${
event.pageX - $TheOrb.clientWidth / 2 + deadzone // Don't work correctly with dead zone!
}px, ${
event.pageY - $TheOrb.clientHeight / 2 + deadzone // Don't work correctly with dead zone!
}px)`
})
#TheOrb {
position: absolute;
padding: 1em;
background-color: red;
font-size: 1.2em;
font-style: open-sans;
color: #fff;
border: 2px solid #000;
border-radius: 50%;
cursor: pointer;
transition: .1s;
}
<div id="TheOrb">Voff!</div>
New Version
I have made a new version, which uses transform: translate() instead of the left and right properties. It also ensures the orb stops at the deadzone distance when moving towards the cursor. I have also removed transition: 0.2s.
const $TheOrb = document.getElementById('TheOrb');
const deadzone = 100;
let orbX = 0;
let orbY = 0;
document.addEventListener('mousemove', e => {
const x = e.pageX - (orbX + $TheOrb.clientWidth / 2);
const y = e.pageY - (orbY + $TheOrb.clientHeight / 2);
if (x > deadzone) {
orbX = e.pageX - $TheOrb.clientWidth / 2 - deadzone;
} else if (Math.abs(x) > deadzone) {
orbX = e.pageX - $TheOrb.clientWidth / 2 + deadzone;
}
if (y > deadzone) {
orbY = e.pageY - $TheOrb.clientHeight / 2 - deadzone;
} else if (Math.abs(y) > deadzone) {
orbY = e.pageY - $TheOrb.clientHeight / 2 + deadzone;
}
$TheOrb.style.transform = `translate(${orbX}px, ${orbY}px)`;
});
#TheOrb {
position: absolute;
padding: 1em;
background-color: red;
font-size: 1.2em;
font-style: open-sans;
color: #fff;
border: 2px solid #000;
border-radius: 50%;
cursor: pointer;
}
<div id="TheOrb">Voff!</div>
Old Version
I have rewritten the JavaScript to use the CSS left and top properties instead of transform. I have also added transition: 0.2s; to the CSS, so that the orb follows the mouse smoothly.
const $TheOrb = document.getElementById('TheOrb');
const deadzone = 100;
document.addEventListener('mousemove', e => {
const x = Math.abs(e.pageX - (Number($TheOrb.style.left.replace('px', '')) + $TheOrb.clientWidth / 2));
const y = Math.abs(e.pageY - (Number($TheOrb.style.top.replace('px', '')) + $TheOrb.clientHeight / 2));
if (x > deadzone || y > deadzone) {
$TheOrb.style.left = e.pageX - $TheOrb.clientWidth / 2 + 'px';
$TheOrb.style.top = e.pageY - $TheOrb.clientHeight / 2 + 'px';
}
});
#TheOrb {
position: absolute;
padding: 1em;
background-color: red;
font-size: 1.2em;
font-style: open-sans;
color: #fff;
border: 2px solid #000;
border-radius: 50%;
cursor: pointer;
transition: 0.2s;
}
<div id="TheOrb">Voff!</div>

element flickering when it gets dragged

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>

change background position with skrollr.js

i want to change the background position on scroll with skrollr.js library , my background image has lots of images ( about 500 images ) and i want to change theme on scrolling , how can i do it ?
i want to do something like this code but with skrollr.js library :
$(function() {
var rotator = $('#rotator');
var container = $(document);
var viewport = $(window);
var images = 72;
var imageHeight = 30000 / images;
var scrollHeight = container.height() - viewport.height() + imageHeight;
var step = images / scrollHeight;
viewport.scroll(function(event) {
var x = -Math.floor(step * viewport.scrollTop()) * imageHeight;
rotator.css('background-position', x + 'px 0');
});
});
body {
height: 2000px;
}
#rotator {
font-size: 416px;
width: 1em;
height: 1em;
position: fixed;
top: 0;
right: 0;
z-index: -1;
background: transparent url(http://www.3sessanta.it/images/polaroid/sprite_polaroid_total.jpg) no-repeat 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rotator"></div>
Example Demo

Calling a jQuery function on an external file for all the images on a page

I was trying to make a web page with images, which should provide the exact functionality of other pages on the same site. I could do that, except image enlarging feature on it.
Images should be enlarged on a popped-up box. For that, on the other pages a js file is used. (Attached)
The way I have tried is below. Since the other pages' codes are messy I couldn't grab exact thing to do. Help on this is much appreciated.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(window).load(function() {
var productThumbImage = $('.search_holder .product-enlarge-trigger img');
productThumbImage.each(function() {
// Get on screen image
var screenImage = $(this);
// Create new offscreen image to test
var theImage = new Image();
theImage.src = screenImage.attr("src");
// Get accurate measurements from that.
var imageWidth = theImage.width;
var imageHeight = theImage.height;
if (imageWidth > imageHeight) {
$(this).addClass('thumbCheckLandscape');
}
});
});
$(".product-enlarge-trigger img").hover(function() {
alert('aaa');
});
$('body').removeClass();
detectThumbs();
function detectThumbs() {
var productThumbImage = $('.product-enlarge-trigger img');
alert(productThumbImage);
productThumbImage.each(function() {
var thumbCheck = $(this).attr('src');
thumbCheck = thumbCheck.split('/');
thumbCheck = thumbCheck[2];
thumbCheck = thumbCheck.replace("%20", "");;
$(this).parent().addClass(thumbCheck);
});
}
</script>
<script type="text/javascript" src="JS/Enlarge/image.enlarge.js"></script>
<style type="text/css">
.tablet_thumb_landscape.thumbCheckLandscape {
margin-top: 16px;
width: 117px !important;
}
.thumbCheckLandscape {
width: 100% !important;
}
.product-enlarge-trigger img {
width: 7%;
position: static !important;
}
.item_thumb_wrapper {
height: 186px;
-webkit-box-shadow: inset 0px -15px 0px 0px rgba(218, 218, 218, 0.99);
-moz-box-shadow: inset 0px -15px 0px 0px rgba(218, 218, 218, 0.99);
box-shadow: inset 0px -15px 0px 0px rgba(218, 218, 218, 0.99);
padding-bottom: 8px;
border-bottom: 8px solid #c8c7c8;
margin-bottom: 8px;
position: relative;
}
.enlarge_thumb_close {
width: 33px;
height: 33px;
right: -16px;
top: -16px;
position: absolute;
display: block;
background: url(../../../Images/Structure/search_enlarge_close.png)top left no-repeat;
background-size: 100%;
z-index: 1001 !important;
}
</style>
</head>
<body>
<div class="item_thumb_wrapper">
<img src="aa\xxx.jpg" class="resize" width="250" />
</div>
<div class="product-enlarge-trigger">
<img src="aa\xxx.jpg" class="resize" width="250" />
</div>
<div class="box">
<img src="aa\xxx.jpg" class="resize" width="250" />
</div>
</body>
</html>
External js file
// Plugin Definition
$.fn.productEnlarge = function(options) {
var defaults = {
'fadeInSpeed': 300,
'lastRowClass': 'last',
'overlayDiv': 'item-overlay-global',
'enlargeDiv': 'product-scroll-enlarge'
}
// Extend our default options with those provided
var opts = $.extend({}, defaults, options);
var getScrollTop = function() {
var ScrollTop = document.body.scrollTop;
if (ScrollTop == 0) {
if (window.pageYOffset)
ScrollTop = window.pageYOffset;
else
ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
}
return ScrollTop;
}
var getViewportHeight = function() {
var viewportheight;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined') {
viewportheight = window.innerHeight
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0) {
viewportheight = document.documentElement.clientHeight
}
// older versions of IE
else {
viewportheight = document.getElementsByTagName('body')[0].clientHeight
}
return viewportheight;
}
/*** sniff the UA of the client and show hidden div's for that device ***/
var ua = navigator.userAgent;
var windowwidth = $(window).width();
var checker = {
android: ua.match(/Android/),
appleiPad: ua.match(/iPad/)
};
if (windowwidth <= 660) {
//if (checker.android){
// do nothing
} // end UA detection
else {
// For every trigger passed bind our events
return this.each(function() {
$this = $(this);
$this.mouseover(function() {
var hover_link = $(this).parent().attr('href');
//var hover_call = $(this).parent().attr('rel');
var hover_call = $(this).attr('rel');
//alert (hover_link);
// Create our overlay div
//$('body').append('<a class="enlarge_thumb_close">Close</a>');
$('body').append('');
$(this).parent().parent().find('.card-link').addClass('cardTitleSelected');
//$(this).parent().parent().find('.card-link').appendTo('.product-scroll-enlarge');
//$('.cardTitleSelected').appendTo('.product-scroll-enlarge');
//$('.cardTitleSelected').show();
var product_target_title = $(this).parent().parent().find('.card-link span');
//$('.product-scroll-enlarge').append('<div class="enlarge_title"><div class="et_text_wrap">'+ product_target_title.html() +'<br><strong>A6</strong> £1.79 / <strong>A4</strong> £2.99 / <strong>A3</strong> £5.99</div></div>');
$('.enlarge_title').hide().remove();
$('.product-scroll-enlarge').append('<div class="enlarge_title"><div class="et_text_wrap">' + product_target_title.html() + '</div></div>');
//alert(product_target_title.html());
$('body').append('<div class="enlarge_thumb_close"></div>');
// Get our targets
var target = $('.' + opts.overlayDiv);
// Set a fallback bind to remove this new target on mouseout
target.mouseout(function() {
$(this).remove();
});
var product_target = $(this).parent().parent().parent().find('.' + opts.enlargeDiv);
if (product_target.length == 0) {
return false;
}
$(target).html(product_target.html()).fadeIn(opts.fadeInSpeed);
// Calculate our positioning
var pos_top = (($(this).offset().top + ($(this).height() / 2)) - (target.height() / 2));
var pos_left = $(this).offset().left + $(this).width() + 25;
var totalwidth = pos_left + target.width() + 25;
// If our image goes beyond our viewport width or has a class of 'last' flip our offset
if ($(this).parent().hasClass(opts.lastRowClass) || totalwidth > document.body.offsetWidth) {
pos_left = ($(this).offset().left - target.width()) - 30;
}
var totalheight = (pos_top - getScrollTop()) + parseInt(target.height());
//var totalheight = ((pos_top - getScrollTop()) + ($(this).height() / 2)) - parseInt(taget.height() / 2);
var windowHeight = getViewportHeight();
// If our image goes beyond our window height
if (totalheight > windowHeight) {
var minusval = parseInt(totalheight) - windowHeight;
pos_top = pos_top - (minusval + 30);
}
// If our image is less than the product height, display below
if (totalheight < target.height()) {
pos_top = getScrollTop() + 50;
}
// Set our positional coordinates
$(target).css('top', pos_top).css('left', pos_left);
setTimeout(function() {
//do something special
var mainimagewidth = $('.item-overlay-global img').width();
$('.enlarge_thumb_close').css('top', pos_top - 16).css('left', pos_left + mainimagewidth - 16);
}, 100);
$('.enlarge_thumb_close').click(function() {
$this.hide().remove();
$('.' + opts.overlayDiv).hide().remove();
$('.enlarge_thumb_close').hide().remove();
});
});
$this.mouseout(function() {
var windowwidth = $(window).width();
var ua = navigator.userAgent;
var checker = {
appleiPad: ua.match(/iPad/)
};
if (windowwidth <= 440 || checker.appleiPad) {
} else {
$('.' + opts.overlayDiv).hide().remove();
$('.enlarge_thumb_close').hide().remove();
$('.enlarge_title').hide().remove();
}
//$('.cardTitleSelected').appendTo('.product-scroll-enlarge');
//$('.cardTitleSelected').hide();
//$('.product-scroll-enlarge .cardTitleSelected').after(''+ $this +' .shortlistSave');
});
$('.enlarge_thumb_close').click(function() {
$('.' + opts.overlayDiv).hide().remove();
$('.enlarge_thumb_close').hide().remove();
$('.enlarge_title').hide().remove();
});
$('.item-overlay-global').click(function() {
window.location = hover_link;
});
});
}
};

Moving a image in jQuery (image crop)

My code is working fine, but Im getting a few problems. The first problem regards to the browsers ability to drag images around, when it happens a "stop signal" appears, and it breaks the code. Sometimes the signal appears (firefox), sometimes not. I dont know why. The second problem regards to the text outside the div. When the user drag the image, the text outside gets selected. Who can I solve it?
If you run the code, you need a 140px width image.
The code:
<div style="position: relative; height: 100px; width: 100px; overflow: hidden;" class="img-profile">
<div id="crop" style="position: absolute; width: 140px; left: -20px; height: 140px; top: 0px; background: url(/image/user/teste.jpg) no-repeat; cursor: move;"></div>
</div>
var x = 0;
var y = 0;
$(document).ready(function () {
$("#crop").mousedown(function () {
var crop = $(this);
$(document).mousemove(function (e) {
var x_movement = 0;
var y_movement = 0;
if (x == e.pageX || x == 0) {
x = e.pageX;
} else {
x_movement = e.pageX - x;
x = e.pageX;
}
if (y == e.pageY || y == 0) {
y = e.pageY;
} else {
y_movement = e.pageY - y;
y = e.pageY;
}
var left = parseFloat(crop.css("left")) + x_movement;
var min_left = 0;
var max_left = -40;
if (left >= min_left) left = min_left;
if (left <= max_left) left = max_left;
crop.css("left", left);
var top = parseFloat(crop.css("top")) + y_movement;
var min_top = 0;
var max_top = (parseFloat(crop.css("height")) - 100) * -1;
if (top >= min_top) top = min_top;
if (top <= max_top) top = max_top;
crop.css("top", top);
});
});
$(document).mouseup(function () {
x = 0;
y = 0;
$(document).unbind("mousemove");
});
});
Just noted that changing the crop div to a input solved both problems.
<input type="button" id="crop" style="position: absolute; width: 140px; left: -20px; height: 140px; top: 0px; background: url(/image/user/teste.jpg) no-repeat; cursor: move; border: 0px;" />

Categories

Resources