It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
How do i animate a line getting longer in jquery? I'm trying to connect two divs, and I need the line to be dynamic as one of the div moves around. Thus, i need the line to get longer.
<div id="a"></div> <!--div A-->
<div id="b"></div> <!--div B-->
<div id="line"></div> <!--Line -->
$("button").click(function () {
var a = $("#a"),
b = $("#b"),
dW = b.offset().left - (a.offset().left), //dX
dH = b.offset().top - (a.offset().top), //dY
angle = Math.atan(dH / dW), //angle
length = Math.sqrt(dW * dW + dH * dH); //length in between
if(dW <0) angle += Math.PI; //some Math stuff
$("#line").css({
top: a.offset().top, //Where the line starts
left: a.offset().left,
width: 0,
rotate: angle + "rad", //rotation (prefixes not included)
transformOrigin: '0px 0px'
}).animate({
width: length //animation
}, 3000);
});
LIVE DEMO: http://jsfiddle.net/DerekL/UwDgq/
I'm assuming you're line is a HTML element, ie <div> or something, so you can just change its width attribute. So animate it by increasing the width over time.
Assuming you are using an <hr> for your line, or even if you are just using a div, you can simply use jquery animate:
http://jsfiddle.net/cd9Xs/
you can try this:
<!DOCTYPE html>
<html>
<head>
<title>demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"
type="text/javascript"></script>
<style type="text/css">
.drag{
position:absolute;
width:100px;
height:100px;
border:1px solid #96C2F1;
background-color: #EFF7FF;
cursor:move;
line-height:100px;
text-align:center;
}
.one{
left:100px;
top:100px;
}
.two{
left:500px;
top:100px;
}
.line{
position: absolute;
display: block;
float: left;
overflow:hidden;
}
</style>
<script type="text/javascript">
function drawQLine(x1, y1, x2, y2, color) {
var wh = (x2 - x1) || 1;
var hg = Math.abs(y2 - y1) || 1;
var up = ((y1 - y2) > 0 ? -1 : 1);
var rate;
var wm;
if (wh >= hg) {
wm = "x";
rate = wh / hg;
} else {
wm = "y"
rate = hg / wh;
}
var srate = rate - Math.floor(rate);
var sumSrate = 0;
var xOffer = x1;
var yoffer = y1;
var body = $("body");
$(".line").remove();
if (wm == "x") {
for (var i = 0; i < hg; i++) {
sumSrate += srate;
body.append($("<span class='line' style='margin-left:" + (xOffer - 7) + "px;margin-top:" + (yoffer) + "px;width:" + Math.floor(rate) + "px;height:1px;line-height:1px;background:" + color + ";'></span>"));
xOffer += Math.floor(rate);
yoffer += up;
if (sumSrate >= 1) {
body.append($("<span class='line' style='margin-left:" + (xOffer - 7) + "px;margin-top:" + (yoffer) + "px;width:1px;height:1px;line-height:1px;background:" + color + ";'></span>"));
sumSrate -= 1;
xOffer += 1;
yoffer += up;
}
}
}
if (wm == "y") {
for (var i = 0; i < wh; i++) {
sumSrate += srate;
body.append($("<span class='line' style='margin-left:" + (xOffer) + "px;margin-top:" + (yoffer) + "px;width:1px;height:" + Math.floor(rate) + "px;line-height:" + Math.floor(rate) + "px;background:" + color + ";'></span>"));
xOffer += 1;
yoffer += Math.floor(rate) * up;
if (sumSrate >= 1) {
body.append($("<span class='line' style='margin-left:" + (xOffer) + "px;margin-top:" + (yoffer) + "px;width:1px;height:1px;line-height:1px;background:" + color + ";'></span>"));
sumSrate -= 1;
xOffer += 1;
yoffer += up;
}
}
}
}
(function(document) {
$.fn.Drag = function() {
var M = false;
var Rx, Ry;
var t = $(this);
t.mousedown(function(event) {
Rx = event.pageX - (parseInt(t.css("left")) || 0);
Ry = event.pageY - (parseInt(t.css("top")) || 0);
t.css("position", "absolute").css('cursor', 'move').fadeTo(20, 0.5);
M = true;
})
.mouseup(function(event) {
M = false;
t.fadeTo(20, 1);
});
$(document).mousemove(function(event) {
if (M) {
t.css({
top: event.pageY - Ry,
left: event.pageX - Rx
});
drawConnectLine();
}
});
}
})(document);
function drawConnectLine() {
var one = $("#divOne");
var two = $("#divTwo");
drawQLine(parseInt(one.css("left")) + one.width(),
parseInt(one.css("top")) + one.height() / 2,
parseInt(two.css("left")),
parseInt(two.css("top")) + two.height() / 2,
"red");
}
$(document).ready(function() {
$("#divTwo").Drag();
drawConnectLine();
});
</script>
</head>
<body>
<div id="divOne" class="drag one">ONE</div>
<div id="divTwo" class="drag two">TWO</div>
</body>
</html>
demo:http://jsfiddle.net/af3qM/
Related
I have created three circles and made it bounce off the wall without using HTML canvas. Now I want two circles to collide with each other and move those circles in the opposite direction. I tried to detect the collision by checking it's position but it doesn't work. I don't know where I went wrong.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Bounce Ball</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.circle{
height: 50px;
width: 50px;
position: absolute;
border-radius: 50%;
}
.container {
height: 300px;
width: 300px;
background-color: skyblue;
position: relative;
}
</style>
</head>
<body>
<div class ="container" id ="container">
<div class="circle" id = "circle1" style="background-color:black;
height: 50px; width: 50px;top:0; left:0"></div>
<div class="circle" id ="circle2" style="background-color:rgb(197, 100,
100);height: 50px; width: 50px;top:200px;left: 150px"></div>
<div class="circle" id ="circle3" style="background-color:brown;height:
50px;width: 50px;top:50px;left: 640px"></div>
</div>
<script>
var container = document.getElementById("container");
container.style.width="700px";
container.style.height = "300px";
var balls = document.getElementsByClassName("circle");
for(var i=0; i <balls.length; i++){
var speed={x:3,y:-3}
setInterval(draw, 50 , balls[i], speed);
}
function draw(ball, speed) {
if(parseInt(ball.style.left) > (parseInt(container.style.width)-
parseInt(ball.style.width)) || (parseInt(ball.style.left) <0) ){
speed.x = -speed.x;
}
ball.style.left = parseInt(ball.style.left) + speed.x + 'px';
if(parseInt(ball.style.top) > (parseInt(container.style.height)-
parseInt(ball.style.height)) || (parseInt(ball.style.top) <0)){
speed.y = -speed.y;
}
ball.style.top = parseInt(ball.style.top) + speed.y + 'px';
//for colliding two circles
for(var i =0 ; i <= balls.length-1; i++){
for(var j = i + 1; j < balls.length; j++){
if(parseInt(balls[i].style.left) +
parseInt(balls[i].style.width) ==
parseInt(balls[j].style.left) ||
parseInt(balls[j].style.left) +
parseInt(balls[j].style.width) ==
parseInt(balls[i].style.left) &&
parseInt(balls[i].style.top) +
parseInt(balls[i].style.height) ==
parseInt(balls[j].style.top) || parseInt(balls[j].style.top)
+ parseInt(balls[j].style.height) ==
parseInt(balls[i].style.top)) {
speed.x = - speed.x;
speed.y = -speed.y;
}
ball[i].style.left = parseInt(ball[i].style.left) +
speed.x + 'px';
ball[j].style.left = parseInt(ball[j].style.left) +
speed.x + 'px';
ball[i].style.top = parseInt(ball[i].style.top) +
speed.y + 'px';
ball[j].style.top = parseInt(ball[j].style.top) +
speed.y + 'px';
}
}
}
</script>
</body>
</html>
I would recommend moving as much as possible into javascript variables so you don't need to consult the HTML for every parameter.
You had quite the number of typos, among them speed.x = - speed.x; where you meant speed.x = -speed.x; and your code was difficult to read without any comments or helper functions to explain what's going on.
I have fixed your typos and restructured your code in the snippet below. Try checking the developer console, typically by pressing F12, as this will show you code errors with line number and severity rating.
In my snippet below i have tried to move the parameters into JavaScript to show how that would work, while still leaving some on the HTML nodes:
//Basic properties
var width = 700;
var height = 300;
//Get container
var container = document.getElementById("container");
// Set dimensions
container.style.width = width + "px";
container.style.height = height + "px";
//Load balls
var balls = Array.prototype.slice.call(document.getElementsByClassName("circle"))
.map(function(ball) {
return {
HTMLNode: ball,
xPos: parseInt(ball.style.left),
yPos: parseInt(ball.style.top),
xAcc: 3,
yAcc: -3,
size: 50
};
});
//Utility functions
function angleBetween(x1, y1, x2, y2) {
return Math.atan2(y2 - y1, x2 - x1);
}
function distanceBetween(x1, y1, x2, y2) {
return Math.abs(y2 - y1) + Math.abs(x2 - x1);
}
//Draw function
function draw() {
//Loop through balls
for (var ballIndex1 = 0; ballIndex1 < balls.length; ballIndex1++) {
var ball1 = balls[ballIndex1];
//Collide with horisontal wall
if (ball1.xPos > width - ball1.size || ball1.xPos < 0) {
ball1.xAcc = -ball1.xAcc;
}
//Collide with vertical wall
if (ball1.yPos > height - ball1.size || ball1.yPos < 0) {
ball1.yAcc = -ball1.yAcc;
}
//Collide with other balls
for (var ballIndex2 = ballIndex1 + 1; ballIndex2 < balls.length; ballIndex2++) {
var ball2 = balls[ballIndex2];
//Test within collision distance
if (distanceBetween(ball1.xPos, ball1.yPos, ball2.xPos, ball2.yPos) > ball1.size) {
continue;
}
//Get angle of collision
var angle = angleBetween(ball1.xPos, ball1.yPos, ball2.xPos, ball2.yPos);
//Apply force to acceleration
ball1.xAcc = -Math.cos(angle) * 3;
ball2.xAcc = -ball1.xAcc;
ball1.yAcc = -Math.sin(angle) * 3;
ball2.yAcc = -ball1.yAcc;
}
//Apply acceleration to position
ball1.yPos += ball1.yAcc;
ball1.xPos += ball1.xAcc;
//Apply to node
ball1.HTMLNode.style.left = ball1.xPos + "px";
ball1.HTMLNode.style.top = ball1.yPos + "px";
}
}
//Start simulation
setInterval(draw, 1000 / 60);
.circle {
position: absolute;
border-radius: 50%;
height: 50px;
width: 50px;
}
.container {
height: 300px;
width: 300px;
background-color: skyblue;
position: relative;
}
<div class="container" id="container">
<div class="circle" id="circle1" style="background-color:black;
top:0; left:0"></div>
<div class="circle" id="circle2" style="background-color:rgb(197, 100,
100);top:200px;left: 150px"></div>
<div class="circle" id="circle3" style="background-color:brown;top:50px;left: 640px"></div>
</div>
I have a wrapper called #mousearea and I have a div called #mouseshift what I would like to do is when I hover over #mousearea I would like to shift the translate3d(0,230%,0) value between a particular range.
I have got the mousemove working but I currently end up with something like translate3d(7881%,230%,0) it's just too sensetive I would like it to translate the X co-ordinate between something like 0-60% so it's far more subtle.
Here is what I have so far:
jQuery(document).ready(function($){
$('#mousearea').mousemove(function (e) {
var shiftAmount = 1;
$('#mouseshift').css(
'transform', 'rotate(90deg) translate3d(' + -e.pageY + shiftAmount + '%,230%,0)'
);
});
});
Update:
This is a little closer, except it logs the correct translate3d but doesn't apply it to #mouseshift.
$('#mousearea').mousemove(function(e){
var x = e.pageY - this.offsetTop;
var transfromPosition = 'translate3d(' + x + ', 230%, 0)';
console.log(transfromPosition);
if ((x <= 800)) {
//$('#mouseshift').css({'top': x});
$('#mouseshift').css('transform', transfromPosition);
}
});
Final Solution:
jQuery(document).ready(function($){
$('#mousearea').mousemove(function(e){
var min = 50;
var max = 70;
var x = e.pageY;
var windowHeight = window.innerHeight;
scrolled = (x / windowHeight);
percentageScrolled = scrolled * 100;
offsetScroll = max - min;
offsetPercentage = scrolled * 20;
translateX = min + offsetPercentage;
console.log(x + 'px');
console.log(windowHeight + 'px window height');
console.log(percentageScrolled + '% scrolled');
console.log(offsetScroll + 'offset scroll');
console.log(offsetPercentage + '% offset percentage');
var transfromPosition = 'rotate(90deg) translate3d(' + translateX + '%, 230%, 0)';
$('#mouseshift h1').css('transform', transfromPosition);
});
});
Convert to a reusable plugin I would like to extend this to work with more than one object now and each object would have a different max and min value:
This is what I have but it seems to effect all the items on only use on elements max and min.
$(function () {
$('#mouseshift-1, #mouseshift-2').mouseShift();
});
(function ($) {
$.fn.mouseShift = function () {
return this.each(function () {
var myEl = $(this);
var min = $(this).data('min');
var max = $(this).data('max');
$('#mousearea').mousemove(function (e) {
var yPosition = e.pageY;
var windowHeight = window.innerHeight;
scrolled = (yPosition / windowHeight);
//percentageScrolled = scrolled * 100;
offsetRange = max - min;
offsetRangePercentage = scrolled * 20;
offset = min + offsetRangePercentage;
//// Debug
console.log('max: ' + max + ', Min:' + min);
console.log(yPosition + 'px');
console.log(windowHeight + 'px window height');
//console.log(percentageScrolled + '% scrolled');
console.log(offsetRange + 'px offset scroll');
console.log(offsetRangePercentage + '% offset percentage');
var transfromPosition = 'rotate(90deg) translate3d(' + offset + '%, 230%, 0)';
myEl.css('transform', transfromPosition);
});
});
};
})(jQuery);
And some HTML for clarity:
<div class="column"><h1 id="mouseshift-1" data-min="50" data-max="70">boo</h1></div>
<div class="column"><h1 id="mouseshift-2" data-min="20" data-max="90">bah</h1></div>
<div class="column"><h1 id="mouseshift-3" data-min="80" data-max="100">bing</h1></div>
I think what you are looking for is finding an average that your can distribute. The best way to do this is to divide by the maximum amount it can move, and multiply it by the maximum value it can have, so basically:
position / maxposition * maxvalue
The first bit will return a number between 0 and 1, while the last bit will make it the value between 0 and 60. Below I have built a simply (jquery-less) version of it to show how this would work:
var mousePointer = document.getElementById('test')
document.addEventListener('mousemove', function(e){
var x = e.pageX / window.innerHeight;
x = x * -60;
mousePointer.style.webkitTransform = 'translateX(' + x + '%)';
mousePointer.style.transform = 'translateX(' + x + '%)';
})
#test {
position: absolute;
left: 50%;
top: 50%;
width: 20px;
height: 20px;
background: red;
}
<div id="test"></div>
Update: Reusable Snippet
I don't really like using jQuery, so once again it will be vanilla javascript (but it's pretty simple). Is that what you were - sort of - trying to do with the reusable plugin?
var divs = Array.prototype.slice.call(document.querySelectorAll('[data-range]'));
document.addEventListener('mousemove', function(e){
var eased = e.pageX / window.innerWidth;
divs.forEach(function(div){
var range = div.getAttribute('data-range').split(',');
var min = parseFloat(range[0]);
var max = parseFloat(range[1]);
var ease = min + (eased * (max - min));
div.style.webkitTransform = 'translateX(' + ease + '%)';
div.style.transform = 'translateX(' + ease + '%)';
});
});
div {
position: absolute;
left: 50%;
top: 50%;
width: 200px;
height: 200px;
background: gray;
}
#d2 { background: yellow; }
#d3 { background: #666; }
<div data-range="60,70" id="d1"></div>
<div data-range="-70,70" id="d2"></div>
<div data-range="-60,-70" id="d3"></div>
From simple reading, I see that you're missing a % sign. Should be like this:
$('#mousearea').mousemove(function(e){
var x = e.pageY - this.offsetTop;
var transfromPosition = 'translate3d(' + x + '%, 230%, 0)';
console.log(transfromPosition);
if ((x <= 800)) {
//$('#mouseshift').css({'top': x});
$('#mouseshift').css('transform', transfromPosition);
}
});
This should be working like your first example, where you do use % for both values inside the translate3d string.
Update:
To coerce your x Value to something between 0 and 60, you need to find a pair of possible min and max values for x. Then you can do something like what's shown in this answer:
Convert a number range to another range, maintaining ratio
I am trying to make the smile.png image to appear in a random position within the specific <div>.
What I have done is to set the variable.style.top= top_position+'px' & variable.style.left = left_position+"px".
However, what I am getting so far are the images the are horizontally aligned and not randomly positioned. How am I able to do that?
var theLeftSide = document.getElementById("leftSide");
var randomY = Math.round(Math.random()) + 'px';
var randomX = Math.round(Math.random()) + 'px';
function generateFaces() {
for (numberOfFaces = 0; numberOfFaces < 5; numberOfFaces++) {
createElement(numberOfFaces);
}
}
number = 0;
function createElement() {
number++;
//creating the image on the leftside
var smiley = document.createElement('img');
smiley.src = "smile.png";
smiley.style.position = "absolute";
smiley.style.left = randomX;
smiley.style.top = randomY;
theLeftSide.appendChild(smiley);
}
#leftSide {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
position: absolute;
width: 500px;
height: 500px;
left: 500px;
border-left: 1px solid black;
}
<body id="smileyGuessingGame" onload="generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left</p>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
</body>
There are few syntax errors in your code. You can compare your code with the code provided below.
Also note toFixed returns a A string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place.
Try this:
var theLeftSide = document.getElementById("leftSide"),
top_position = parseInt(Math.random() * ($(document).width() - 500)),
left_position = parseInt(Math.random() * ($(document).width() - 500));
function generateFaces() {
for (var numberOfFaces = 0; numberOfFaces < 5; numberOfFaces++) {
createElement(numberOfFaces);
}
}
var number = 0;
function createElement() {
number++;
//creating the image on the leftside
var smiley = document.createElement('img');
smiley.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/Smiley_head_happy.svg/2000px-Smiley_head_happy.svg.png";
smiley.style.position = 'absolute';
smiley.style.top = top_position + "px";
smiley.style.left = left_position + "px";
theLeftSide.appendChild(smiley);
top_position += 20;
left_position += 20;
}
#leftSide {
position: absolute;
width: 500px;
height: 500px;
}
#rightSide {
position: absolute;
width: 500px;
height: 500px;
left: 500px;
border-left: 1px solid black;
}
img {
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body id="smileyGuessingGame" onload="generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left</p>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
</body>
Fiddle here
I'd code this using jQuery and lodash. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/3z6wsnyf/2/
The html:
<h1>Matching Game</h1>
<p>Find the unique image</p>
<div class="game"></div>
And the code:
var game = function(options) {
var panes = 2,
game = $('.game'),
height = 500,
width = game.width() / panes - 20,
itemSize = 50,
faces = 5,
guesses = 5,
setupBoard = function() {
game
.empty();
_.times(panes, function(p) {
game
.append(
$('<div>')
.addClass('pane pane' + p)
.css('height', height + 'px')
.css('width', width + 'px')
);
})
},
startGame = function() {
_.times(faces, function(i) {
_.times(panes, function(p) {
$('.pane' + p)
.append(
$('<img>')
.attr('src', 'http://lorempixel.com/200/20' + i)
.addClass('img-' + i)
.css('top', _.random(height - itemSize) + 'px')
.css('left', _.random(width - itemSize) + 'px')
);
})
});
$('.game img').click(function() {
guesses--;
alert('Nope! You\'ve got ' + guesses + ' guesses remaining.');
});
$('.pane' + _.random(panes - 1))
.append(
$('<img>')
.attr('src', 'http://lorempixel.com/200/20'+ (faces + 1))
.addClass('img-t')
.css('top', _.random(height - itemSize) + 'px')
.css('left', _.random(width - itemSize) + 'px')
.click(function() {
alert('You got it! Good job! You just cleared ' + faces + ' images! You\'ve got ' + guesses + ' guesses remaining.');
faces++;
setupBoard();
startGame();
})
);
$('.game img')
.css('height', itemSize + 'px')
.css('width', itemSize + 'px')
.css('-moz-border-radius', itemSize / 2 + 'px')
.css('-webkit-border-radius', itemSize / 2 + 'px')
.css('border-radius', itemSize / 2 + 'px')
.css('-khtml-border-radius', itemSize / 2 + 'px')
};
setupBoard();
startGame();
};
game();
Maybe something like this could work:
function generateRandom(min, max) {
var num = Math.random() * (max - min) + min;
return Math.floor(num);
}
var width,
height,
img;
width = $( '#leftSide' ).width();
height = $( '#leftSide' ).height();
img = $('<img id="smiley">');
img.attr('src', 'http://vignette2.wikia.nocookie.net/robocraft/images/2/26/Smile.png');
img.css('top',generateRandom(0,height));
img.css('left',generateRandom(0,width));
img.appendTo('#leftSide');
demo: http://codepen.io/anon/pen/PZZrzz
I have the following script, when dragging the gray handler (top left) div re-sizes but at release of the mouse div is being place in the wrong place (at left margin).
I need to fix it as would be the bottom right handler.
What could be the problem? It seems related with event.clientX which is set to 0.
NOTES: click on the div to activate the handlers.
http://jsfiddle.net/cx41otxp/
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
#target {
background-color: lightgreen;
}
.selected {
border: 1px dashed red;
}
.handler {
position: absolute;
width: 10px;
height: 10px;
background-color: gray;
}
</style>
<script>
window.App = {
config: {
elm: 'target',
elmInnerContent: 'inner-content',
x: null,
y: null,
w: null,
h: null,
handlerSize: 10
},
start: function () {
this.addEventListeners();
},
addEventListeners: function () {
var elm = document.getElementById(this.config.elm);
elm.addEventListener('click', function () {
if (!elm.classList.contains('selected')) {
elm.classList.add('selected');
this.getDimensions();
this.createHandlers();
this.setPositionHandlers();
this.addEventListenersHandlers();
} else {
elm.classList.remove('selected');
this.removeHandlers();
}
}.bind(this));
},
removeHandlers: function () {
var elm = document.getElementById('handler-wrapper');
elm.parentElement.removeChild(elm);
},
getDimensions: function () {
var elm = document.getElementById(this.config.elm);
this.config.x = elm.offsetLeft;
this.config.y = elm.offsetTop;
this.config.w = elm.clientWidth;
this.config.h = elm.clientHeight;
},
createHandlers: function () {
var wrpHandlers = document.createElement('div'),
htmlHandlers = '<div id="tl" class="tl handler" draggable="true"> </div>';
htmlHandlers += '<div id="tr" class="tr handler" draggable="true"> </div>';
htmlHandlers += '<div id="bl" class="bl handler" draggable="true"> </div>';
htmlHandlers += '<div id="br" class="br handler" draggable="true"> </div>';
wrpHandlers.id = "handler-wrapper";
wrpHandlers.innerHTML = htmlHandlers;
var elm = document.getElementById(this.config.elm);
elm.appendChild(wrpHandlers);
},
setPositionHandlers: function () {
this.getDimensions();
var elmTl = document.getElementById('tl'),
elmTr = document.getElementById('tr'),
elmBl = document.getElementById('bl'),
elmBr = document.getElementById('br');
elmTl.style.top = this.config.handlerSize * -1 + 'px';
elmTl.style.left = this.config.handlerSize * -1 + 'px';
elmTr.style.top = this.config.handlerSize * -1 + 'px';
elmTr.style.left = this.config.w + 'px';
elmBl.style.top = this.config.h + 'px';
elmBl.style.left = this.config.handlerSize * -1 + 'px';
elmBr.style.top = this.config.h + 'px';
elmBr.style.left = this.config.w + 'px';
},
addEventListenersHandlers: function () {
var elmTl = document.getElementById('tl'),
elmTr = document.getElementById('tr'),
elmBl = document.getElementById('bl'),
elmBr = document.getElementById('br');
elmTl.addEventListener('drag', function (event) {
this.resize('tl', event);
}.bind(this));
elmTr.addEventListener('drag', function (event) {
this.resize('tr', event);
}.bind(this));
elmBl.addEventListener('drag', function (event) {
this.resize('bl', event);
}.bind(this));
elmBr.addEventListener('drag', function (event) {
this.resize('br', event);
}.bind(this));
},
resize: function (handler, event) {
var elm = document.getElementById(this.config.elm);
switch (handler) {
case 'tl':
var marginR = elm.offsetLeft + elm.clientWidth,
newW = marginR - event.clientX,
xPos = event.clientX;
elm.style.left = xPos + 'px';
elm.style.width = newW + 'px';
this.setPositionHandlers();
break;
case 'tr':
break;
case 'bl':
break;
case 'br':
var newW = event.clientX - this.config.x,
newH = event.clientY - this.config.y;
elm.style.width = newW + 'px';
elm.style.height = newH + 'px';
this.setPositionHandlers();
break;
}
},
};
</script>
<title></title>
</head>
<body onload="window.App.start();">
<div id="target" style="position: absolute; top: 100px; left: 100px; width: 100px; height: 100px;">
<div id="inner-content">
Some text here
</div>
</div>
</body>
</html>
In the resize function, case 'tl': you have to do the same thing for top & height, what you do for left & width.
marginT = elm.offsetTop + elm.clientHeight,
newH = marginT - event.clientY,
yPos = event.clientY;
and
elm.style.top = yPos + 'px';
elm.style.height = newH + 'px';
Edit: Sorry, I think misread something the first time.
FYI: your code is working fine in Safari, but in Chrome, I see your problem.
Edit2: I don't know what causes this. But if you just check xPos >= 0, you can work around it. I know it's an ugly hack, but this is the best I have. Fiddle updated.
I'm trying to scale some divs inside a 'workspace' div. The problem I have are with the distance between them (I lose it).
I have read a lot of post about CSS3 transform, in special about scale and translate and origin, but I can't solve the problem...
Can someone explain me how can I keep them? I show one code using a mousewheel plugin, regards.
HTML
<body>
<div id="workspace">
<div style="z-index: 101;"><img src="image1-300x300.jpg" /></div>
<div style="z-index: 102; left: 300px; top: 400px;"><img src="image2-400x400.jpg" /></div>
</div>
</body>
CSS
#workspace {
width: 1600px;
height: 900px;
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
display: inline;
}
#workspace > div {
display: inline;
position: absolute;
}
JAVASCRIPT
$(document).ready(function () {
var scale = 1; // scale of the image
var xLast = 0; // last x location on the screen
var yLast = 0; // last y location on the screen
var xImage = 0; // last x location on the image
var yImage = 0; // last y location on the image
// if mousewheel is moved
$("#workspace").mousewheel(function (e, delta) {
// find current location on screen
var xScreen = e.pageX - $(this).offset().left;
var yScreen = e.pageY - $(this).offset().top;
// find current location on the image at the current scale
xImage = xImage + ((xScreen - xLast) / scale);
yImage = yImage + ((yScreen - yLast) / scale);
// determine the new scale
if (delta > 0) {
scale *= 2;
}
else {
scale /= 2;
}
scale = scale < 1 ? 1 : (scale > 64 ? 64 : scale);
// determine the location on the screen at the new scale
var xNew = (xScreen - xImage) / scale;
var yNew = (yScreen - yImage) / scale;
// save the current screen location
xLast = xScreen;
yLast = yScreen;
// redraw
$('#mosaicContainer > div').each(function() {
$(this).css('-webkit-transform', 'scale(' + scale + ')' + 'translate(' + xNew + 'px, ' + yNew + 'px' + ')')
.css('-webkit-transform-origin', (xImage) + 'px ' + (yImage) + 'px');
});
return false;
});
});