I'm attempting to make these balls move along the border of this parent div. The parent div is a pill/discorectangle. I'm sure there must be a way to do this using some trig or equation of a circle. So the straight sides are 200px long and the radius of each semi circle is 100px. So from 0-100px and 300-400px the top style needs to be calculated for each ball. Has anyone done anything similar or have any advice?
HTML:
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
</head>
<button id="start_stop">Orbit</button>
<div id="oval">
<div id="ball0" class="ball"></div>
<div id="ball1" class="ball"></div>
<div id="ball2" class="ball"></div>
<div id="ball3" class="ball"></div>
</div>
<script src="orbit.js"></script>
</html>
CSS:
#oval {
position: absolute;
margin-top: 200px;
height: 200px;
width: 400px;
border: 3px solid black;
border-radius: 400px/400px;
right: 50%;
transform: translate(50%, -50%);
}
.ball {
height: 30px;
width: 30px;
border-radius: 30px;
position: absolute;
}
#ball0 {
left:270px;
top:185px;
/*right: 100px;
bottom: -15;*/
background-color: blue;
}
#ball1 {
left:100px;
/* bottom:-15px; */
top: 185px;
background-color: green;
}
#ball2 {
top:-15px;
/* right: 100px; */
left: 270px;
background-color: yellow;
}
#ball3 {
top:-15px;
left: 100px;
background-color: red;
}
JS:
var oval = document.getElementById('oval');
var balls = document.getElementsByClassName('ball');
var run_animation = false;
var req;
document.getElementById("start_stop").addEventListener("click", toggle);
function toggle() {
run_animation = !run_animation
if(run_animation) {
req = window.requestAnimationFrame(orbit);
}
}
console.log(balls.length);
var max_x = oval.clientWidth; // - 100;
var min_x = 0;
var step = 0;
var map = {
"ball0": {"top": 185, "left": 270, forward: true},
"ball1": {"top": 185, "left": 100, forward: true},
"ball2": {"top": -15, "left": 270, forward: false},
"ball3": {"top": -15, "left": 100, forward: false}
}
function get_y(x){
//some math here?
// return 100 * Math.sin(x);
// return Math.sqrt(100**2 + x**2);
}
function orbit() {
if (run_animation){
for(var i=0; i<balls.length; i++){
var curr_left = map["ball"+i].left;
if (curr_left >= max_x) map["ball"+i].forward = false;
if (curr_left <= min_x ) map["ball"+i].forward = true;
if(map["ball"+i].forward){
map["ball"+i].left += 3;
}
else {
forward = false
map["ball"+i].left -= 3;
}
//left edge - curve around semicircle
if(map["ball"+i].left <= 100) {
// map["ball"+i].top = -1 * get_y(map["ball"+i].left);
}
//right edge - curve around semicircle
if(map["ball"+i].left >= 300) {
// map["ball"+i].top = -1 * get_y(map["ball"+i].left);
}
balls[i].style.left = map["ball"+i].left + 'px';
balls[i].style.top = map["ball"+i].top + 'px';
}
req = window.requestAnimationFrame(orbit);
}
else {
console.log("cancel");
window.cancelAnimationFrame(req);
}
}
/* orbit(); */
req = window.requestAnimationFrame(orbit);
https://jsfiddle.net/gzjfxtbu/2/
Well I did it. Not sure if this is the best way to do this or not. I'd still like to figure out any other methods to accomplish this. Eventually I was going to turn the balls into actual divs containing info and images. So I'm not sure if the SVG route is the best?
Hopefully this can help someone.
JS:
var oval = document.getElementById('oval');
var balls = document.getElementsByClassName('ball');
var run_animation = false;
var req;
document.getElementById("start_stop").addEventListener("click", toggle);
function toggle() {
run_animation = !run_animation
if(run_animation) {
req = window.requestAnimationFrame(orbit);
}
}
console.log(balls.length);
var max_x = oval.clientWidth;
var min_x = 0;
var step = 0;
var map = {
"ball0": {"top": 185, "left": 270, forward: false},
"ball1": {"top": 185, "left": 100, forward: false},
"ball2": {"top": -15, "left": 270, forward: true},
"ball3": {"top": -15, "left": 100, forward: true}
}
function get_y(x){
//some math here?
// return 100 * Math.sin(x);
return 1 * (Math.sqrt(100**2 - (100-x)**2));
}
function get_y2(x) {
return 1 * (Math.sqrt(100**2 - (300-x)**2));
}
function orbit() {
if (run_animation){
for(var i=0; i<balls.length; i++){
var curr_left = map["ball"+i].left;
if (curr_left >= max_x) map["ball"+i].forward = false;
if (curr_left <= min_x ) map["ball"+i].forward = true;
if(map["ball"+i].forward){
map["ball"+i].left += 3;
}
else {
map["ball"+i].left -= 3;
}
//left edge - curve around semicircle
if(map["ball"+i].left <= 85 && !map["ball"+i].forward ) {
map["ball"+i].top = 1*get_y(map["ball"+i].left) + 85;
}
else if(map["ball"+i].left <= 85 && map["ball"+i].forward ) {
map["ball"+i].top = -1*get_y(map["ball"+i].left) + 85;
}
//right edge - curve around semicircle
if(map["ball"+i].left >= 315 && map["ball"+i].forward) {
map["ball"+i].top = -1*get_y2(map["ball"+i].left) + 85;
}
else if(map["ball"+i].left >= 315 && !map["ball"+i].forward) {
map["ball"+i].top = get_y2(map["ball"+i].left) + 85;
}
balls[i].style.left = map["ball"+i].left + 'px';
balls[i].style.top = map["ball"+i].top + 'px';
}
req = window.requestAnimationFrame(orbit);
}
else {
console.log("cancel");
window.cancelAnimationFrame(req);
}
}
/* orbit(); */
req = window.requestAnimationFrame(orbit);
HTML:
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
</head>
<button id="start_stop">Orbit</button>
<div id="oval">
<div id="ball0" class="ball">0</div>
<div id="ball1" class="ball">1</div>
<div id="ball2" class="ball">2</div>
<div id="ball3" class="ball">3</div>
</div>
<script src="orbit.js"></script>
</html>
CSS:
#oval {
position: absolute;
margin-top: 100px;
height: 200px;
width: 400px;
border: 3px solid black;
border-radius: 400px/400px;
right: 50%;
transform: translate(50%, -50%);
}
.ball {
height: 30px;
width: 30px;
border-radius: 30px;
position: absolute;
}
#ball0 {
left:270px;
top:185px;
/*right: 100px;
bottom: -15;*/
background-color: blue;
}
#ball1 {
left:100px;
/* bottom:-15px; */
top: 185px;
background-color: green;
}
#ball2 {
top:-15px;
/* right: 100px; */
left: 270px;
background-color: yellow;
}
#ball3 {
top:-15px;
left: 100px;
background-color: red;
}
https://jsfiddle.net/nwm3r4he/3/
Related
I need the image in the both divs below to be in the same position even if the other div changes height or width. I have tried calculating top and left to % from px but still it is not working. I have also tried calculating the % of how big or small other div is and adding or removing the top and left to the image in other div and still no luck.
To check the issue, drag the image around inside the first div and click on submit. Now the image inside the bottom div should be in the same position as the above div, same top and left distance.
Please help. Thanks.
Here is the fiddle : https://jsfiddle.net/kashyap_s/gLdt62nh
var zoomLevel = 1;
$("#myimage").draggable({
start: function() {
},
stop: function() {
}
});
$('#save').click(function() {
var topcss = $('#myimage').css('top');
var leftcss = $('#myimage').css('left');
var transformcss = zoomLevel;
topcss = topcss.replace('px', '');
leftcss = leftcss.replace('px', '');
topcss = parseInt(topcss);
leftcss = parseInt(leftcss);
var parentWidth = $('#dragDiv').outerWidth()
var parentHeight = $('#dragDiv').outerHeight()
console.log('leftcss', leftcss, 'width', parentWidth)
console.log('topcss', topcss, 'height', parentHeight)
var percentLeft = leftcss / parentWidth * 100;
var percentTop = topcss / parentHeight * 100;
console.log('percentLeft', percentLeft, 'percentTop', percentTop)
transformcss = parseFloat(transformcss).toFixed(2);
var result = {
"top": topcss,
"left": leftcss,
'percentTop': percentTop,
'percentLeft': percentLeft,
'parentWidth': parentWidth,
'parentHeight': parentHeight,
"transform": "scale(" + transformcss + ")"
};
var output = JSON.stringify(result);
console.log('output', output)
$("#newimg").css({
'left': leftcss
});
$("#newimg").css({
'top': topcss
});
});
.transperentimage {
width: 497px;
height: 329px;
border: 1px solid black;
margin: 0 auto;
}
#bigimg {
width: 651px;
height: 431px;
border: 1px solid black;
margin: 0 auto;
}
img {
border: 2px solid red;
padding: 3px;
width: auto;
height: auto;
cursor: move;
max-height: 180px;
}
#newimg {
position: absolute;
max-height: 180px;
width: auto!important;
height: auto!important;
max-width: 100%!important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="transperentimage" id="dragDiv">
<img id="myimage" src="agent.png">
</div>
<button id="save">Save</button>
<div id="bigimg">
<img id="newimg" src="agent.png" />
</div>
$(function() {
$("#logo1").draggable({
containment: "parent",
drag: function() {
}
});
});
function setpos() {
var image1_w = $("#logo1").width();
var div1_w = $(".div1").width();
var image2_w = $("#logo2").width();
var div2_w = $(".div2").width();
var image1_h = $("#logo1").height();
var div1_h = $(".div1").height();
var image2_h = $("#logo2").height();
var div2_h = $(".div2").height();
var div1_aw = div1_w - image1_w;
var div2_aw = div2_w - image2_w;
var div1_ah = div1_h - image1_h;
var div2_ah = div2_h - image2_h;
var div
var xPos = $('#logo1').css('left');
var yPos = $('#logo1').css('top');
var ratio_w = parseFloat(div1_aw) / parseFloat(div2_aw);
var ratio_h = parseFloat(div1_ah) / parseFloat(div2_ah);
//let act = 1.39;
var div2_nw = parseFloat(xPos) / ratio_w;
var div2_nh = parseFloat(yPos) / ratio_h;
$("#posX").text('Div left:' + div2_nw);
$("#posA").text('Div Top:' + div2_nh);
$("#logo2").css({
'left': div2_nw,
'top': div2_nh
});
}
.div1 {
width: 497px;
height: 329px;
border: 1px solid black;
}
.div2 {
width: 651px;
height: 431px;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
<p>Drag my logo.</p>
<div class="div1">
<img src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" style=" position: relative; left: 0px; top: 0px;" width="100" id="logo1">
</div>
<br>
<div class="div2">
<img style="position: relative;left: 0px;top: 0px" src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" width="100" id="logo2">
</div>
<br>
<button onclick="setpos();">
Save
</button>
<div id="posX">
</div>
<div id="posA">
</div>
<div id="posz">
</div>
<div id="posZ1">
</div>
Solved! check this out
HTML
<p>Drag my logo.</p>
<div class="div1">
<img src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" style=" position: relative; left: 0px; top: 0px;" width="100" id="logo1">
</div>
<br>
<div class="div2">
<img style="position: relative;left: 0px;top: 0px" src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" width="100" id="logo2">
</div>
<br>
<button onclick="setpos();">
Save
</button>
<div id="posX"></div>
<div id="posA"></div>
JS CODE
$( function() {
$( "#logo1" ).draggable(
{
containment: "parent",
drag: function() {
}
}
);
} );
function setpos()
{
var image1_w = $("#logo1").width();
var div1_w = $(".div1").width();
var image2_w = $("#logo2").width();
var div2_w = $(".div2").width();
var image1_h = $("#logo1").height();
var div1_h = $(".div1").height();
var image2_h = $("#logo2").height();
var div2_h = $(".div2").height();
var div1_aw = div1_w-image1_w;
var div2_aw = div2_w-image2_w;
var div1_ah = div1_h-image1_h;
var div2_ah = div2_h-image2_h;
var div
var xPos = $('#logo1').css('left');
var yPos = $('#logo1').css('top');
var ratio_w = parseFloat(div1_aw)/parseFloat(div2_aw);
var ratio_h = parseFloat(div1_ah)/parseFloat(div2_ah);
//let act = 1.39;
var div2_nw = parseFloat(xPos)/ratio_w;
var div2_nh = parseFloat(yPos)/ratio_h;
$("#posX").text('Div left:' + div2_nw);
$("#posA").text('Div Top:' + div2_nh);
$("#logo2").css({ 'left' : div2_nw, 'top' : div2_nh});
}
CSS
.div1{
width: 497px;
height: 329px;
border: 1px solid black;
}
.div2{
width: 651px;
height: 431px;
border: 1px solid black;
}
For your newimg, the parent must have a position that is relative. This way, the absolute positioning will be relative to the parent and not the body.
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).
Consider the following code.
$(function() {
var zoomLevel = parseFloat(1 - ($("#dragDiv").outerWidth() / $("#bigimg").outerWidth()).toFixed(2));
function log(str) {
if ($(".log").length) {
$(".log").html(str);
} else {
$("<div>", {
class: "log"
}).html(str).appendTo("body");
}
}
function getPos(el) {
var par = $(el).parent();
var pos = {
top: parseInt($(el).css("top")),
left: parseInt($(el).css("left")),
zoom: "scale(" + (1 + zoomLevel) + ")",
parWidth: par.outerWidth(),
parHeight: par.outerHeight()
};
pos['perLeft'] = parseFloat((pos.left / pos.parWidth).toFixed(2)) * 100;
pos['perTop'] = parseFloat((pos.top / pos.parHeight).toFixed(2)) * 100;
return pos;
}
$("#myimage").draggable({
containment: "parent",
drag: function(e, ui) {
log("Left: " + ui.position.left + ", Top: " + ui.position.top);
},
start: function() {
// coordinates('#myimage');
},
stop: function() {
// coordinates('#myimage');
var p = getPos(this);
$(this).attr("title", JSON.stringify(p));
}
});
$('#save').click(function() {
var result = getPos($("#myimage"));
var output = JSON.stringify(result);
var nLeft = Math.round(result.perLeft * (1 + zoomLevel)) + "%";
var nTop = Math.round(result.perTop * (1 + zoomLevel)) + "%"
console.log(output, nLeft, nTop);
$("#newimg").css({
left: nLeft,
top: nTop
});
var p = getPos($("#newimg"));
$("#newimg").attr("title", JSON.stringify(p));
});
});
.transperentimage {
width: 497px;
height: 329px;
border: 1px solid black;
margin: 0 auto;
}
#bigimg {
width: 651px;
height: 431px;
border: 1px solid black;
margin: 0 auto;
position: relative;
}
img {
border: 2px solid red;
padding: 3px;
width: auto;
height: auto;
cursor: move;
/* max-width: 100%; */
max-height: 180px;
}
#newimg {
position: absolute;
max-height: 180px;
width: auto!important;
height: auto!important;
max-width: 100%!important;
}
.log {
font-size: 11px;
font-family: "Arial";
position: absolute;
top: 3px;
left: 3px
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="transperentimage" id="dragDiv">
<img id="myimage" src="https://i.imgur.com/4ILisqH.jpg">
</div>
<button id="save">Save</button>
<div id="bigimg">
<img id="newimg" src="https://i.imgur.com/4ILisqH.jpg" />
</div>
See More: https://www.w3schools.com/css/css_positioning.asp
Updated
Looking at it further, I am guessing that you might be trying to reposition the bigimg in relationship to myimage position. This requires scaling the percentage.
For example, if we move myimage to the far left, it will be at left: 247, and this is roughly 49% of 499px. 49% of 653 is around 319, and this would not place the image where we want it. We want it at 401.
bigimg is about 24% larger than dragDiv, so we need to scale our percentage. 49 * 1.24 = 60.74, round up to 61. 653 * .61 = 398.33 so better yet not perfect.
My code is forking this pen, I also include my code in the stack snippet under this post.
what I want to achieve are:
When the cursor is not inside the body, the eyeball would move randomly ( achieved ).
When the cursor enters the body, the eyeball follows the cursor ( achieved ).
When the cursor leaves the body, the eyeball starts moving randomly again ( not achieved ).
I called the function which is used to move the eyeball randomly in on("mouseleave") event, and it does move to a random position but it will immediately go back to the last cursor position, rather than staying at the new position. Can anyone point me to the right direction to fix the problem?
Thanks!
var
mouseOvering = false,
pupil = $("#pupil"),
eyeball = $("#iris"),
eyeposx = 40,
eyeposy = 20,
r = $(pupil).width()/2,
center = {
x: $(eyeball).width()/2 - r,
y: $(eyeball).height()/2 - r
},
distanceThreshold = $(eyeball).width()/2 - r,
mouseX = 0,
mouseY = 0;
$("body").ready( function(){
if ( !mouseOvering ) {
moveRandomly();
}
});
$("body").on('mouseleave', function(){
mouseOvering = false;
moveRandomly();
console.log("mouseleave");
});
$("body").on('mousemove', function(e){
mouseOvering = true;
console.log("mouseovering");
followCursor(e);
});
function moveRandomly() {
var loop = setInterval(function(){
var xp = Math.floor(Math.random()*80);
var yp = Math.floor(Math.random()*80);
pupil.animate({left:xp, top:yp});
}, 3500);
}
function followCursor(e) {
var d = {
x: e.pageX - r - eyeposx - center.x,
y: e.pageY - r - eyeposy - center.y
};
var distance = Math.sqrt(d.x*d.x + d.y*d.y);
if (distance < distanceThreshold) {
mouseX = e.pageX - eyeposx - r;
mouseY = e.pageY - eyeposy - r;
} else {
mouseX = d.x / distance * distanceThreshold + center.x;
mouseY = d.y / distance * distanceThreshold + center.y;
}
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 1 to alter damping/momentum - higher is slower
xp += (mouseX - xp) / 1;
yp += (mouseY - yp) / 1;
pupil.css({left:xp, top:yp});
}, 2);
}
body {
background-color: #D1D3CF;
}
#container {
display: inline;
height: 400px;
width: 400px;
}
#eyeball {
background: radial-gradient(circle at 100px 100px, #EEEEEE, #000);
height: 300px;
width: 300px;
border-radius: 100%;
position: relative;
}
#iris {
top: 10%;
left: 10%;
background: radial-gradient(circle at 100px 100px, #4DC9EF, #000);
height: 80%;
width: 80%;
border-radius: 100%;
position: absolute;
}
#pupil {
top: 10%;
left: 10%;
background: radial-gradient(circle at 100px 100px, #000000, #000);
height: 55%;
width: 55%;
border-radius: 100%;
position: absolute;
}
#keyframes move {
50% {
transform: translate(-50px, 50px);
}
}
#keyframes move2 {
50% {
transform: translate(-20px, 20px);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<div id="eyeball">
<div id="iris">
<div id="pupil"></div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
With Javascript you can only track where the cursor is on the webpage. If you shift your cursor outside the body, it's not possible for your code to know where the cursor is.
This is the reason the eye tracking your cursor stops moving when you move your cursor outside the window.
The problem is that once the followcursor function was started it kept on moving back to the last known mouse position, even after the mouse had left the body. I just put a check on your mouseOvering variable inside your followcursor function:
var
mouseOvering = false,
pupil = $("#pupil"),
eyeball = $("#iris"),
eyeposx = 40,
eyeposy = 20,
r = $(pupil).width()/2,
center = {
x: $(eyeball).width()/2 - r,
y: $(eyeball).height()/2 - r
},
distanceThreshold = $(eyeball).width()/2 - r,
mouseX = 0,
mouseY = 0;
$("body").ready( function(){
if ( !mouseOvering ) {
moveRandomly();
}
});
$("body").on('mouseleave', function(){
mouseOvering = false;
console.log("mouseleave");
});
$("body").on('mousemove', function(e){
mouseOvering = true;
console.log("mouseovering");
followCursor(e);
});
function moveRandomly() {
var loop = setInterval(function(){
var xp = Math.floor(Math.random()*80);
var yp = Math.floor(Math.random()*80);
if (!mouseOvering) {
pupil.animate({left:xp, top:yp});
}
}, 3500);
}
function followCursor(e) {
var d = {
x: e.pageX - r - eyeposx - center.x,
y: e.pageY - r - eyeposy - center.y
};
var distance = Math.sqrt(d.x*d.x + d.y*d.y);
if (distance < distanceThreshold) {
mouseX = e.pageX - eyeposx - r;
mouseY = e.pageY - eyeposy - r;
} else {
mouseX = d.x / distance * distanceThreshold + center.x;
mouseY = d.y / distance * distanceThreshold + center.y;
}
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 1 to alter damping/momentum - higher is slower
xp += (mouseX - xp) / 1;
yp += (mouseY - yp) / 1;
if (mouseOvering) {
pupil.css({left:xp, top:yp});
}
}, 2);
}
body {
background-color: #D1D3CF;
}
#container {
display: inline;
height: 400px;
width: 400px;
}
#eyeball {
background: radial-gradient(circle at 100px 100px, #EEEEEE, #000);
height: 300px;
width: 300px;
border-radius: 100%;
position: relative;
}
#iris {
top: 10%;
left: 10%;
background: radial-gradient(circle at 100px 100px, #4DC9EF, #000);
height: 80%;
width: 80%;
border-radius: 100%;
position: absolute;
}
#pupil {
top: 10%;
left: 10%;
background: radial-gradient(circle at 100px 100px, #000000, #000);
height: 55%;
width: 55%;
border-radius: 100%;
position: absolute;
}
#keyframes move {
50% {
transform: translate(-50px, 50px);
}
}
#keyframes move2 {
50% {
transform: translate(-20px, 20px);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<div id="eyeball">
<div id="iris">
<div id="pupil"></div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
When I click-drag (#cssNav) to the right, it is not moving proportionately along with the #html and #css div.
This might be something very obvious, but still am not able to figure it out, what am I missing here, please help?
Note: I don't want to use display:flex
codepen
$("#htmlNav").on("mousedown", dragStartH);
$("#cssNav").on("mousedown", dragStartH);
$("#jsNav").on("mousedown", dragStartH);
function dragStartH(e) {
e.preventDefault();
dragMeta = {};
dragMeta.pageX0 = e.pageX;
dragMeta.elem = this;
dragMeta.offset0 = $(this).offset();
dragMeta.codeWindow = "#" + $(e.target).attr("id").replace("Nav", "");
function handle_dragging(e) {
var change = e.pageX - dragMeta.pageX0;
var left = dragMeta.offset0.left + change;
$(dragMeta.elem).offset({ left: left });
$("#css").width($("#css").width() - change + "px");
$("#html").width($("#html").width() + change + "px");
}
function handle_mouseup(e) {
$("body")
.off("mousemove", handle_dragging)
.off("mouseup", handle_mouseup);
}
$("body").on("mouseup", handle_mouseup).on("mousemove", handle_dragging);
}
$(document).ready(function() {
var widthPercent = ($(window).width() - 30) / 3;
$("#html").width(widthPercent + "px");
$("#css").width(widthPercent + "px");
$("#js").width(widthPercent + "px");
});
html, body {
height: 100%;
margin: 0;
}
.container{
width:100%;
height: 100%;
background-color:#343;
display: flex;
flex-direction: column;
color: #fff;
margin: 0;
}
#preview, #code{
background-color:#433;
height: 50%;
width: 100%;
margin: 0;
}
#code{
border-bottom: #333 solid 2px;
width: 100%
}
#previewNav, #codeNav{
background-color:#bbb;
height: 10px;
width: 100%;
cursor: row-resize;
}
#html{
background-color: #BFB;
}
#css{
background-color: #FBB;
}
#js{
background-color: #BBF;
}
#html, #css, #js{
float: left;
width: 32%;
height: 100%;
}
#htmlNav, #cssNav, #jsNav{
background-color:#bbb;
float: left;
height:100%;
width: 10px;
cursor: col-resize;
z-index:10;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="codeNav"></div>
<div id="code">
<div id="htmlNav"></div>
<div id="html">H</div>
<div id="cssNav"></div>
<div id="css">C</div>
<div id="jsNav"></div>
<div id="js">J</div>
</div>
<div id="previewNav"></div>
<div id="preview">P</div>
</div>
This is how I would do it:
Keep track of which handle you press with navTypeand check if the user is holding its mouse down with dragging.
Then when the user moves the mouse in the document and it is holding its mouse down (dragging) it will move the #html, #css and #js accordingly
Change your javascript into this:
var mouseX, prevMouseX, navType, change;
var dragging = false;
$("#cssNav").mousedown(function () {
dragging = true;
navType = "css";
});
$("#jsNav").mousedown(function () {
dragging = true;
navType = "js";
});
$(document).mousemove(function (e) {
mouseX = e.pageX;
if(dragging){
e.preventDefault();
change = mouseX - prevMouseX;
if(navType == "css" && ($("#css").width() - (change)) > 0 && ($("#html").width() + (change)) > 0){
var hw = $("#html").width();
var cw = $("#css").width();
$("#html").width(hw + change);
$("#css").width(cw - change);
} else if(navType == "js" && ($("#css").width() + (change)) > 0 && ($("#js").width() - (change)) > 0){
var cw = $("#css").width();
var jw = $("#js").width();
$("#css").width(cw + change);
$("#js").width(jw - change);
}
}
prevMouseX = mouseX;
}).mouseup(function () {
dragging = false;
}).mouseleave(function () {
dragging = false;
});
These are my javascript, css, and html files for simple web page for dragging an element and putting it into the container(div) :
var xContainer;
var yContainer
var insideFirst = false;
$(window).load(
function() {
xContainer = $("#center").offset().left;
yContainer = $("#center").offset().top;
console.log("ready");
$("#center").on("click", function(event) {
console.log(event);
});
$("#center").droppable();
$("#firstID").draggable({
cursor : 'move',
revert: "invalid"
});
$("#firstID").mousedown(function() {
isDragging = false;
}).mousemove(
function() {
isDragging = true;
var x = $("#firstID").offset().left;
var y = $("#firstID").offset().top;
xContainer = $("#center").offset().left;
yContainer = $("#center").offset().top;
var xPosition = (x - xContainer).toFixed(2);
var yPosition = (y - yContainer).toFixed(2);
console.log("center:" + xContainer);
console.log("x:" + x);
console.log("difference: "+(x-xContainer));
/*
* if (x < 750 && y < 750) {
* $("#firstID").css('background','#ffffff') }
*/
if (xPosition >= 0.0 && yPosition >= 0.0
&& xPosition <= 500.0 && yPosition <= 200.0) {
$("#xPosition").val("x:" + xPosition);
$("#yPosition").val("y:" + yPosition);
$("#firstID").css('background', '#e4e4e4')
$('#firstID').draggable({containment : [xContainer,yContainer,xContainer+500,yContainer+200.0] });
} else {
//$("#xPosition").val("GO IN!!!");
//$("#yPosition").val("GO IN!!!");
$("#firstID").css('background', '#d1f1fc')
}
}).mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
if (!wasDragging) {
console.log("clicked");
}
});
$("#secondID").draggable({
cursor : 'move'
});
$("#secondID").mousedown(function() {
isDragging = false;
}).mousemove(function() {
isDragging = true;
var x = $("#secondID").offset().left;
var y = $("#secondID").offset().top;
// $("#text-x").val ("x:"+x);
// $("#text-y").val ("y:"+y);
}).mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
if (!wasDragging) {
console.log("clicked");
}
});
$("#secondID").dblclick(function() {
rotation += 90;
$(this).rotate(rotation);
});
});
jQuery.fn.rotate = function(degrees) {
$(this).css({
'-webkit-transform' : 'rotate(' + degrees + 'deg)',
'-moz-transform' : 'rotate(' + degrees + 'deg)',
'-ms-transform' : 'rotate(' + degrees + 'deg)',
'transform' : 'rotate(' + degrees + 'deg)'
});
return $(this);
};
var rotation = 0;
var isDragging = false;
body {
height: 100%;
background-color: #e4e4e4;
}
#firstID {
width: 100px;
height: 100px;
margin: 0 auto;
border-style: groove;
background-color: #d1f1fc;
color: black;
position: relative;
text-align: center;
z-index: 99;
}
#secondID {
width: 100px;
height: 50px;
margin: 0 auto;
color: black;
border-style: groove;
position: relative;
background-color: #d1f1fc;
text-align: center;
z-index: 99;
}
#center {
width: 600px;
height: 300px;
position: relative;
margin: 0 auto;
border-style: groove;
background-color: #c0c0c0;
}
/* If in mobile screen with maximum width 479px. The iPhone screen resolution is 320x480 px (except iPhone4, 640x960) */
#media only screen and (max-width: 479px) {
#center{
width: 50%;
height : 50%;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<html>
<head>
<link rel="stylesheet" type="text/css" href="drag.css">
</head>
<body>
<input type="text" id="xPosition" value="x:0">
<input type="text" id="yPosition" value="y:0">
<div id="firstID" >MJ</div>
<div id="secondID" >MJ</div>
<div id="center">
</div>
</body>
</html>
The code is not finished, so the logic works with only a square, not rectangle.
What i need is to drag square element into the container on the page and make it stay inside it, with no possibility to leave it. That works fine in Mozilla, but in Chrome, i have problems with dragging the square after entering container. When i click on it and try to drag it, it moves far to the right side of the page. Why is that happening only in Chrome?
I'm trying to create div boxes step by step and animate them for several times when a button is pressed. I have a running code, and everything is going well. It goes right to the endhost, then it goes left again to its original place. This is mainly what I do, and also the demo is found here: http://jsfiddle.net/LSegC/1/
Now what I want to do is to increase the number of whole animated DIVs one-by-one (as it is now) up to 3 Divs, but then have exponential increase on the total number of DIVs. So the total number of animated DIVs will be like 1, 2, 3, and then 4, 8, 16, etc.
Remember, my problem is not with the number being shown inside the DIV, it's actually that how many DIVS are being created! So I want for instance 8 DIVs, numbered from 1 to 8 animated. Hope it is now clear.
$(document).ready(function(){
$("button").click(function() {
var d = $(".t").fadeIn();
var speed = +$("#number1").val();
d.animate({left:'+=230px'}, speed);
d.animate({left:'+=230px'}, speed);
d.animate({top:'+=20px', backgroundColor: "#f09090", text:'12'}, speed/4, "swing", function() {
$('.span', this).fadeOut(100, function() {
$(this).text(function() {
return 'a' + $(this).text().replace('a', '');
}).fadeIn(100);
});
});
d.delay(1000).animate({left:'-=230px'}, speed);
d.animate({left:'-=230px'}, speed);
d.fadeOut().promise().done(function() {
d.last().after(function() {
var top = +$(this).css('top').replace('px', ''),
number = +$(this).data('number') + 1,
$clone = $(this).clone();
$clone.data('number', number).css('top', top + 20);
$clone.find('.span').text(number);
return $clone;
});
d.find('.span').text(function() {
return $(this).text().replace('a', '');
});
})
});
EDIT
Your code was too hard to manipulate as it was, I recreated the whole thing:
HTML:
<img id="streamline1" src="https://cdn3.iconfinder.com/data/icons/streamline-icon-set-free-pack/48/Streamline-04-48.png" />
<img id="LAN" src="https://cdn1.iconfinder.com/data/icons/ecqlipse2/NETWORK%20-%20LAN.png" />
<img src="https://cdn3.iconfinder.com/data/icons/streamline-icon-set-free-pack/48/Streamline-04-48.png" id="streamline" />
<div id="mid"></div>
<div id="bottom"></div>
<div>Speed (mS):
<input value="500" id="speed" type="number" style="position: relative"></input>
<button>Apply!</button>
<!-- dynamic area -->
<div class="packets"></div>
</div>
JS:
$(document).ready(function () {
var count = 0;
var items = 0;
var packetNumber = 0;
var speed = 0;
$("button").click(function () {
if (count < 4) {
items = items + 1;
count++;
} else {
items = items * 2;
}
speed = $("#speed").val();
createDivs(items);
animateDivs();
});
function createDivs(divs) {
packetNumber = 1;
var left = 60;
for (var i = 0; i < divs; i++) {
var div = $("<div class='t'></div>");
div.appendTo(".packets");
$("<font class='span'>" + packetNumber + "</font>").appendTo(div);
packetNumber++;
div.css("left",left+"px");
div.hide();
left += 20;
}
}
function animateDivs() {
$(".t").each(function () {
var packet = $(this);
packet.show();
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
top: '+=20px',
backgroundColor: "#f09090",
text: '12'
}, speed / 4, "swing", function () {
$('.span').fadeOut(100, function () {
$(this).text(function () {
return 'a' + $(this).text().replace('a', '');
}).fadeIn(100);
});
});
packet.delay(1000).animate({left:'-=230px'}, speed);
packet.animate({left:'-=230px'}, speed);
}).promise().done(function(){
$(".packets").empty();});
}
});
CSS:
#bottom {
border: 1px dashed gray;
position: absolute;
left: 55px;
height: 20px;
width: 500px;
opacity: 0.5;
top: 30px;
z-index=-1;
}
#mid {
border: 1px dashed gray;
position: absolute;
left: 55px;
height: 20px;
width: 500px;
opacity: 0.5;
top: 10px;
z-index=-1;
}
.t {
display: inline-block;
position: absolute;
top: 10px;
left: 60px;
text-align: center;
vertical-align: middle;
width: 20px;
height: 20px;
background-color: lightgreen
}
#streamline {
width: 50px;
height: 50px;
right: 0px;
position: fixed;
left: 548px;
}
#streamline1 {
left: 0px;
width: 50px;
height: 50px;
}
#LAN {
width: 50px;
height: 50px;
left: 275px;
position: fixed;
}
.packets {
display: inline;
}
FIDDLE: http://jsfiddle.net/54hqm/3/
It was tough for me to follow the code also, but I cut it back quite a bit, came up with a "one-way" "empiric" approach. FIDDLE
The speed can be adjusted by the change in the increment (inc), but there are a variety of methods that can be used.
Can you be more specific about what you mean by "exponential"? Do you mean an exponential speed increase across the div, or rather a speed increase until you get to 50%, then a decrement in speed.
JS
$("button").click(function() {
var speed = 1000;
var d = $('.mover');
d.show();
var inc = 1;
for (var i=0; i<290; i=i+inc)
{
d.animate({ left: i,
easing: 'linear'}, 1);
if (inc < 11)
{
inc = inc + 1;
} else {
inc = inc - 1;
}
}
});