I have two different functions bound to one element and event, basically they are called upon ‘mousedown’.
I’m trying to figure out a way to allow my element to ‘resize’ or ‘move/drag’ but not both at the same time.
Right now I am using a ‘setTimeout’ function that is cleared when the ‘resize’ function is called, by doing this I cancel my ‘move/drag’ function. It works but not very well at all.
I need help figuring out a better way. I appreciate any suggestions.
var timer= "",
resize_select = false;
$('element').resize(function() {
resize_select = true;
//do stuff, called every resize, just like resizing <textarea>
window.clearTimeout(timer);
});
$('element').on("mousedown", function() {
$(this) = $this;
resize_select = false;
if (resize_select === false) {
timer = setTimeout(function() {
$this.addClass('dragable');
}, 500);
}
$(document).on("mousemove", function(e) {
$('.dragable').css({
top: e.pageY,
left: e.pageX
});
});
});
$(document).on('mouseup', function() {
resize_select = false;
$('.resize').removeClass('dragable');
});
I am using Ben Alman’s ‘jQuery resize event’ to allow any element to bind to .resize();
HERE is a jsfiddle of where I am currently at.
UPDATED
$('.resize').css({
resize:'both',
overflow:'hidden'
});
$('.resize').on('mousedown', function(event) {
var $this = $(this),
$this_height = $this.height(),
$this_width = $this.width(),
x = event.pageX - $this.offset().left,
y = event.pageY - $this.offset().top,
xx = $this_width - 10,
yy = $this_height - 10,
img_num = $(this).index();
event.preventDefault();
if (xx - x > 0 || yy - y > 0) {
$(document).mousemove(function(pos) {
var thisX = pos.pageX - $this_width / 2,
thisY = pos.pageY - $this_height / 2;
$this.offset({
left: thisX,
top: thisY
})
});
}
if (xx - x < 0 && yy - y < 0) {
$(document).mousemove(function(pos) {
var thisX = pos.pageX - $this.offset().left,
thisY = pos.pageY - $this.offset().top,
ratio = ((thisX + thisY) / 2) / (($this_height + $this_width) / 2),
height_new = $this_height * ratio,
width_new = $this_width * ratio;
$this.css({
'width': width_new,
'height': height_new
});
});
}
});
$(document).on('mouseup', function() {
$(document).unbind('mousemove');
});
this works due to @jfriend00 for the idea of figuring out where in each element the ‘mousedown’ event happens & to @Jeremy C providing various optimizations.
js fiddle here HERE
You don’t need a timer at all. This works on Chrome at least, I would test in all browsers to be safe. Here ya go:
EDIT: I added the resize function to restrict the aspect ratio with css ‘resize: vertical’, however it’s a bit jumpy looking. To make it really smooth I would say create your own resize hit area on the bottom right of each div, add a png to it to mimic the browser resize handle and then create your own resize on drag function instead of using the css resize.