I am attempting to make a webpage that randomly positions divs across the page on loading without them overlapping. I found code online that does exactly what I want it to, (Linked Here) but I am having issues with the code...
I copied all of the components from the above link into a pre-existing site, but it does not work. All of the divs appear to be overlapping in the top right corner of the page. A commenter said it worked for them, but I don't see why it wouldn't work on my computer.
I would appreciate any help in making this feature work, as I would love to use it on a website I am working on. Below is a photo of what the page looks like on load...
https://imgur.com/lnby2gw
;(() => {
"use strict";
const TRIES_PER_BOX = 50;
const randUint = range => Math.random() * range | 0;
const placing = [...document.querySelectorAll(".random")].map(el => Bounds(el, 5));
const fitted = [];
const areaToFit = Bounds();
var maxTries = TRIES_PER_BOX * placing.length;
while (placing.length && maxTries > 0) {
let i = 0;
while (i < placing.length) {
const box = placing[i];
box.moveTo(randUint(areaToFit.w - box.w), randUint(areaToFit.h - box.h));
if (fitted.every(placed => !placed.overlaps(box))) {
fitted.push(placing.splice(i--, 1)[0].placeElement());
} else { maxTries-- }
i++;
}
}
function Bounds(el, pad = 0) {
const box = el?.getBoundingClientRect() ?? {
left: 0, top: 0,
right: innerWidth, bottom: innerHeight,
width: innerWidth, height: innerHeight
};
return {
l: box.left - pad,
t: box.top - pad,
r: box.right + pad,
b: box.bottom + pad,
w: box.width + pad * 2,
h: box.height + pad * 2,
overlaps(bounds) {
return !(
this.l > bounds.r ||
this.r < bounds.l ||
this.t > bounds.b ||
this.b < bounds.t
);
},
moveTo(x, y) {
this.r = (this.l = x) + this.w;
this.b = (this.t = y) + this.h;
return this;
},
placeElement() {
if (el) {
el.style.top = (this.t + pad) + "px";
el.style.left = (this.l + pad) + "px";
el.classList.add("placed");
}
return this;
}
};
}
})();
.random {
position: absolute;
margin: 2;
border: 1px solid black;
font-size: xx-large;
top: 0px;
left: 0pc;
}
.placed {
color: red;
border: 1px solid red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<link rel="stylesheet" href="assets/css/style.css">
<script src="assets/js/script.js"></script>
<script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="random">Div 1</div>
<div class="random">Div 2</div>
<div class="random">Div 3</div>
<div class="random">Div 4</div>
<div class="random">Div 5</div>
<div class="random">Div 6</div>
<div class="random">Div 7</div>
<div class="random">Div 8</div>
<div class="random">Div 9</div>
<div class="random">Div 10</div>
<div class="random">Div 11</div>
<div class="random">Div 12</div>
</body>
</html>
Related
Problem
I have a series of cells in a table that store several individual cards. These cards can be rearranged within a cell or moved between cells by dragging and dropping. However, I am finding that when I pick up my card, it does not track directly from where I clicked it. In other words, if I clicked on the upper-right-most corner, it immediately shifts away from my mouse in an unexpected manner. Even stranger is the fact that it works fine if I have my cards stored outside of a table tag. What does the table do that causes my mouse-shift calculation to be incorrect?
JSFiddle
Here is a link to jsfiddle: https://jsfiddle.net/0atymsb9/1/
Keep an eye on where you click, and where the div is positioned relative to your mouse. EDIT: It is while you are dragging the card that the visual defect is occurring, but once you place it it's okay.
(The first square is a within a (doesn't work right), and the second is simply a div (works well.))
I am following this tutorial: https://htmldom.dev/drag-and-drop-element-in-a-list/
Code
JS
// Setup
function setupCards() {
const cards = document.getElementsByClassName("card");
const cells = document.getElementsByClassName("cell");
for (const card of cards) {
card.classList.add("draggable");
}
for (const cell of cells) {
[].slice.call(cell.querySelectorAll('.draggable')).forEach((item) => {
item.addEventListener('mousedown', mouseDownHandler);
});
}
}
// Dragging Logic
let placeholder;
let draggingEle;
let isDraggingStarted = false;
let mouse = { x: 0, y: 0 };
function swap(nodeA, nodeB) {
const parentA = nodeA.parentNode;
const siblingA = nodeA.nextSibling === nodeB ? nodeA : nodeA.nextSibling;
// Move `nodeA` to before the `nodeB`
nodeB.parentNode.insertBefore(nodeA, nodeB);
// Move `nodeB` to before the sibling of `nodeA`
parentA.insertBefore(nodeB, siblingA);
};
function isAbove(nodeA, nodeB) {
const rectA = nodeA.getBoundingClientRect();
const rectB = nodeB.getBoundingClientRect();
return (rectA.top + rectA.height / 2 < rectB.top + rectB.height / 2);
}
// Handlers
const mouseMoveHandler = function (e) {
// Set position for dragging element
const draggingRect = draggingEle.getBoundingClientRect();
if (!isDraggingStarted) {
isDraggingStarted = true;
placeholder = document.createElement('div');
placeholder.classList.add('placeholder');
draggingEle.parentNode.insertBefore(
placeholder,
draggingEle.nextSibling
);
placeholder.style.height = `${draggingRect.height}px`;
}
draggingEle.style.position = 'absolute';
draggingEle.style.top = `${e.pageY - mouse.y}px`;
draggingEle.style.left = `${e.pageX - mouse.x}px`;
const prevEle = draggingEle.previousElementSibling;
const nextEle = placeholder.nextElementSibling;
if (prevEle && isAbove(draggingEle, prevEle)) {
swap(placeholder, draggingEle);
swap(placeholder, prevEle);
return;
}
if (nextEle && isAbove(nextEle, draggingEle)) {
swap(nextEle, placeholder);
swap(nextEle, draggingEle);
}
};
const mouseUpHandler = function () {
placeholder && placeholder.parentNode.removeChild(placeholder);
isDraggingStarted = false;
// Remove the position styles
draggingEle.style.removeProperty('top');
draggingEle.style.removeProperty('left');
draggingEle.style.removeProperty('position');
mouse.x = null;
mouse.y = null;
draggingEle = null;
// Remove the handlers of `mousemove` and `mouseup`
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
};
function mouseDownHandler(e) {
draggingEle = e.target;
const rect = draggingEle.getBoundingClientRect();
mouse.x = e.pageX - rect.left;
mouse.y = e.pageY - rect.top;
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
}
// Main
function main() {
setupCards()
}
main()
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="script.js" defer></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<table>
<td>
<div class="cell">
<div class="card">Test 1</div>
<div class="card">Test 2</div>
<div class="card">Test 3</div>
<div class="card">Test 4</div>
<div class="card">Test 5</div>
<div class="card">Test 6</div>
</div>
</td>
</table>
<div class="cell">
<div class="card">Test 1</div>
<div class="card">Test 2</div>
<div class="card">Test 3</div>
<div class="card">Test 4</div>
<div class="card">Test 5</div>
<div class="card">Test 6</div>
</div>
</body>
CSS
td {
width: 8em;
height: 8em;
position: relative;
}
.cell {
overflow-y: auto;
overflow-x: hidden;
background-color: aquamarine;
border: 1px solid black;
width: 100%;
height: 100%;
}
.card {
background-color: darkgreen;
color: white;
width: 4em;
height: 1em;
text-align: center;
}
/* Dragging */
.draggable {
user-select: none;
}
Thank you for your time!
The problem is not exactly with the table tag. I found two ways to solve this problem.
First solution that change the HTML: Simply comment or remove the <td> tag as follows
<body>
<table>
<!-- <td> --> <!--comment or remove this line-->
<div class="cell">
<div class="card">Test 1</div>
<div class="card">Test 2</div>
<div class="card">Test 3</div>
<div class="card">Test 4</div>
<div class="card">Test 5</div>
<div class="card">Test 6</div>
</div>
<!-- </td>--> <!--comment or remove this line-->
</table>
<div class="cell">
<div class="card">Test 1</div>
<div class="card">Test 2</div>
<div class="card">Test 3</div>
<div class="card">Test 4</div>
<div class="card">Test 5</div>
<div class="card">Test 6</div>
</div>
</body>
Second solution that change the CSS:
This solution is better because you do not need to remove anything in the HTML (maybe is what you want), i.e, do not need to remove <td> or <table> tags. In the CSS file change the position: relative to position: center as follows
td {
width: 8em;
height: 8em;
position: center; /*change from relative to center*/
}
I'm using the code below to create a 'rotation' of images for display on a website. I wish for the images to display within a 'div' element...and i'm having trouble accomplishing that. It seems the problem is when I attempt to set each image as the 'background image' for the element (the line that reads "document.getElementById("rotation").style.backgroundImage = "url(toString(ImgName[number]))";). Only the initial image displays, without any 'rotation' of other images. Any help appreciated, this is becoming very frustrating.
<!DOCTYPE html>
<html>
<title>test page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<head>
<style>
div.rotation {
height: 256px;
width: 100%;
padding: 0px;
background-color: powderblue;
border-style: solid;
border-width: 5px;
border-radius: 25px;
}
</style>
</head>
<body>
<div class="w3-quarter">
<div class="w3-padding-small">
<div class="w3-center">
<div class="rotation">
<p>
<img src='images/rotation/LA_Panel.png' id='rotateImg0' alt='image rotation' />
<img src='images/rotation/McCulloch_256.png' id='rotateImg1' style='display:none;' alt='image rotation' />
<img src='images/rotation/MO_Panel.png' id='rotateImg2' style='display:none;' alt='image rotation' />
<img src='images/rotation/Rommel.png' id='rotateImg3' style='display:none;' alt='image rotation' />
</p>
</div>
</div>
</div>
</div>
</body>
</html>
<script type='text/javascript'>
var rotation = function () {
var currentImage,
images = [],
ImgName = [],
count,
hideImages,
showImage,
fn;
count = (function () {
// Figure out how many images we have on the rotation
var x = 0;
while (document.getElementById('rotateImg' + (x + 1).toString())) {
images[x] = document.getElementById('rotateImg' + x.toString());
ImgName[x] = document.getElementById('rotateImg' + x.toString()).src;
x++;
}
return images.length;
})();
hideImages = function () {
// Hide all the images
for (var i = 0; i < count; i++) {
images[i].style.display = 'none';
}
};
showImage = function (number) {
document.getElementById("rotation").style.backgroundImage = "url(toString(ImgName[number]))";
images[number].style.display = 'block';
};
fn = {};
fn.setupRotation = function () {
// Show the first image
currentImage = 0;
showImage(currentImage);
// Start the rotation
var interval = setInterval(rotation.advanceRotation, 4000);
};
fn.advanceRotation = function () {
if (currentImage + 1 == count)
currentImage = 0;
else
currentImage++;
hideImages();
showImage(currentImage);
};
return fn;
} ();
rotation.setupRotation();
</script>
One thought might be to pluck off the first child and slam him to the end of the line.
let images = document.querySelector('#images');
setInterval(() => {
let el = images.removeChild(images.childNodes[0]);
images.appendChild(el);
}, 1000);
#images {
font-size: 0;
}
.img {
display: inline-block;
width: 30px;
height: 30px;
}
<div id="images">
<div class="img" style="background-color: red"></div>
<div class="img" style="background-color: orange"></div>
<div class="img" style="background-color: yellow"></div>
<div class="img" style="background-color: green"></div>
<div class="img" style="background-color: blue"></div>
</div>
I am programming a simple game in javascript and when the user hovers on the given coordinates it's score increases. My problem is the score does not increment after 1.
var x = Math.floor(Math.random() * 500) + 150;
var y = Math.floor(Math.random() * 500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
//live tracking of coordinates
$("div.frame").mousemove(function (event) {
var xco = event.clientX;
var yco = event.clientY;
var xcoor = "X co-ords: " + xco;
var ycoor = "Y co-ords: " + yco;
document.getElementById("display1").innerHTML = xcoor;
document.getElementById("display2").innerHTML = ycoor;
//keeping score
if (xco == x && yco == y) {
count++;
console.log(count);
document.getElementById("score").innerHTML = count;
generate();
}
//Generating Co-ordinates
function generate() {
var x = Math.floor(Math.random() * 500) + 150;
var y = Math.floor(Math.random() * 500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
function points(x, y) {
if (xco == x && yco == y) {
count++;
console.log(count);
document.getElementById("score").innerHTML = count;
generate();
}
}
points(x, y);
}
})
Even after adding a global count variable, your code is not working properly because of your if (xco == x && yco == y) condition fails after first run. Here you are comparing randomly generated x and y with xco, yco and updating score and calling generate again.
On your generate function you are creating new local variable x and y, not updating the global x and y. And the subsequent comparison (xco == x && yco == y) will fail because it still using the old x and y.
On your generate function, updating the global x and y should fix this issue,
x = Math.floor(Math.random() * 500) + 150;
y = Math.floor(Math.random() * 500) + 150;
Here is the complete code, I also made some minor changes, removed some redundant and duplicate codes
// Code goes here
$(document).ready(function(){
//on clicking let's play
var t = 120;
var count = 0;
$("button.play").click(function(event){
event.preventDefault();
$(".fadeout").fadeOut(2000, function(){
$(".heading").text("Click on the Start button when you're ready");
});
$(".hidden").attr("hidden", false);
});
function start(){
//init game timer
var Timer = setInterval(function(){
document.getElementById("time1").innerHTML = t;
--t;
if(t < 0){
clearInterval(Timer);
document.getElementById("timeout").innerHTML = "Time's Up |";
$("div.frame").attr("hidden",true);
}
},1000);
var x = Math.floor(Math.random()*500)+150;
var y = Math.floor(Math.random()*500)+150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
//live tracking of coordinates
$("div.frame").mousemove(function(event){
var xco = event.clientX;
var yco = event.clientY;
var xcoor = "X co-ords: " + xco;
var ycoor = "Y co-ords: " + yco;
document.getElementById("display1").innerHTML = xcoor;
document.getElementById("display2").innerHTML = ycoor;
//keeping score
points(xco, yco);
})
$("div.frame").mouseout(function(event){
document.getElementById("display1").innerHTML = " ";
document.getElementById("display2").innerHTML = " ";
})
//Generating Co-ordinates
function generate(){
x = Math.floor(Math.random()*500) + 150;
y = Math.floor(Math.random()*500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
}
function points(xco, yco){
if(x == xco && y == yco){
count++;
console.log(count);
document.getElementById("score").innerHTML = count;
generate();
}
}
}
$("button.start").click(function(event){
event.preventDefault();
start();
$(this).fadeOut(1500);
$(this).attr("disabled",true);
$(".afterstart").fadeOut(1500);
});
});
/* Styles go here */
body{
height: 1200px;
background-size: cover;
}
.jumbotron{
margin-top: 250px;
padding: 20px;
height: 350px;
background-size: cover;
background-attachment: fixed;
}
.heading{
font-size: 30px;
margin-top: 100px;
}
.frame{
height: 1000px;
width: 1500px;
border: 10px solid black;
}
ul {
background: #40475A;
padding: 10px;
width: 100%;
}
.stats{
font-size: 30px;
margin-top: 80px;
}
.info{
font-size: 30px;
color:aliceblue;
}
.bold{
font-size: 25px;
color:antiquewhite;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Irritate</title>
</head>
<body>
<div>
<ul class="nav nav-pills pl-5 fixed-top d-flex justify-content-center" style="font-size: 25px">
<li class="nav-item">
<a class="nav-link" data-toggle="pill" id="display1"></a>
</li>
<li class="nav-item">
<a class="nav-link" id="display2"></a>
</li>
</ul>
</div>
<div class="jumbotron fadeout">
<div class="display-3 text-muted d-flex justify-content-center"> Hand-Job </div>
<p class="info"> All you have to do is try to match the co-ordinates that will display on the screen </p>
<p class="bold"><kbd>PS:</kbd>This game will test your patience</p>
<form>
<div class="input-group w-75">
<div class="input-group-prepend">
<span class="input-group-text">Name:</span>
</div>
<input type="text" class="form-control" value="">
<div class="input-group-append">
<button class="btn btn-outline-success play">Let's Play</button>
</div>
</div>
</form>
</div>
<div class="hidden" hidden="true">
<div>
<p class="text-danger heading afterstart"></p>
<button class="btn btn-danger w-25 start">Start</button>
<div class="d-flex d-flex-inline stats">
<p class="ml-3">X Co-ordinate:<span id="demo1" class="ml-2"></span><span> | </span></p>
<p class="ml-3">Y Co-ordinate:<span id="demo2" class="ml-2"></span><span> | </span></p>
<p class="ml-3">Time Left:<span id="time1" class="ml-2"></span> <span> | </span></p>
<p id="timeout" class="ml-3"></p>
<p>Score: <span id="score"></span></p>
</div>
</div>
<div class="frame ml-2">
</div>
<p id="result"></p>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>
Here is plunker url for the above code https://plnkr.co/edit/7ia7MkMimzlsAxTCWAc9?p=preview
i think its because your count variable is local and only live in if block if you want to have count in other place please declare it as global variable
var x = Math.floor(Math.random() * 500) + 150;
var y = Math.floor(Math.random() * 500) + 150;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo1").innerHTML = x;
var count = 0;
//live tracking of coordinates
$("div.frame").mousemove(function (event) {
...
})
So after trying different things for 3 hours or so, I finally decided to post a question on StackOverFlow. Here is the problem:
On click of the "next" button, I want to remove the old div by sliding it to the left and add a dynamically created div by sliding it from the right.
So far, I can only create the remove effect by sliding it to the left while fading it. But I can't add a new div sliding in from the right. How would I accomplish this?
Here is the html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Website Google Project</title>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="bootstrap-2.3.6-dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/scripts.js"></script>
<script type="text/javascript" src="js/secret_api.js"></script>
<link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/styles.css">
<link rel="shortcut icon" type="image/ico" href="photos/favIcon.png">
</head>
<body>
<h1 class="text-center">All Your Directions In One Spot</h1>
<div class="container">
<div class="row row-content" id="tempDiv">
<div class="col-xs-12 col-sm-6 col-sm-offset-3">
<div class="text-center">
<h2>From:</h2>
</div>
</div>
<div style="padding: 20px 20px"></div>
<div class="col-xs-12 col-sm-6 col-sm-offset-3">
<div>
<input id="origin" type="text" class="form-control input-lg" placeholder="Origin" value="8844 N Wisner St">
</div>
</div>
<div style="padding: 40px 40px"></div>
<div class="col-xs-12 col-sm-6 col-sm-offset-3">
<div class="row row-content">
<div class="text-center">
<div class="col-xs-12 col-sm-3 col-sm-offset-3">
<button class ="btn btn-lg" id="next">Next</button>
</div>
<div class="col-xs-12 col-sm-3">
<button class="btn btn-lg" id="done">Done</button>
</div>
</div>
</div>
</div>
</div>
<div style="padding: 40px 40px"></div>
<div id="listDirections">
</div>
</div>
<script src="js/scripts.js"></script>
</body>
</html>
Here is the Css:
body {
background-color: #2b669a;
}
h1 {
color: white;
font-size: 3em;
}
button {
background-color: #204056;
color: white;
font-weight: bold;
}
button:hover,
button:focus {
color: lightgray !important;
}
.directions {
background-color: whitesmoke;
color: #5A5A5A;
padding: 20px 20px;
font-size: 1.5em;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
margin-bottom: 20px;
}
.glyphicon-plus {
font-size: 2em;
color: white;
padding: 5px 5px;
}
.glyphicon-plus:hover {
color: coral;
cursor: pointer;
}
Here is the javascript:
function getDirections(json) {
"use strict";
var steps = json.routes[0].legs[0].steps;
var directions = [];
var counter = 1;
steps.forEach(function (step) {
directions.push(counter + ". " + step.html_instructions);
counter += 1;
});
// Separates the 2 conjoint words in the last line.
// so "Ave Destination" instead of "AveDestination"
directions[directions.length - 1] = directions[directions.length - 1].replace(/([a-z])([A-Z])/g, "$1 $2");
return directions;
}
/**
* Takes in the Google Maps API JSON object as input and returns the ETA as a string.
* #param {Object} json
* #return {string}
*/
function getEta(json) {
"use strict";
return json.routes[0].legs[0].duration.text;
}
function showDirections(json) {
"use strict";
// creates div, adds class, and appends the div
var div = document.createElement("div");
$(div).addClass("directions col-xs-12 col-sm-8 col-sm-offset-2");
$(div).append("<b>FROM: </b> " + $("#origin").val() + "<br>");
$(div).append("<b>TO: </b>" + $("#destination").val() + "<br>");
$(div).append("<em>It will take you " + getEta(json) + " to get there.</em> <p></p>");
getDirections(json).forEach(function (item) {
$(div).append("<p>" + item + "</p>");
});
$("#listDirections").append(div);
}
$('#next').click(function() {
$('#tempDiv').animate({
opacity: 0, // animate slideUp
marginLeft: '-100%',
marginRight: '100%'
}, 'fast', 'linear', function() {
$(this).remove();
});
$('.container').append($("#origin"));
});
/*
$("#next").click(function() {
// $('#tempDiv').hide('slide', {direction: 'left'}, 500).fadeOut('fast');
$('#next').show('slide', {direction: 'left'}, 500);
});
*/
$(document).ready(function () {
"use strict";
$("#getButton").click(function () {
// Get the user input
var origin = $('#origin').val().replace(/ /g, "%20");
var destination = $('#destination').val().replace(/ /g, "%20");
// Create the URL
var URL = "https://maps.googleapis.com/maps/api/directions/json?origin=" +
"" + origin + "&destination=" + destination + "&key=" + APIKEY;
// Obtain json object through GET request
$.getJSON(URL, function (json) {
console.log(getEta(json));
console.log(getDirections(json));
showDirections(json);
});
});
});
If I've understood well your question, you want to remove an "old div" animating it to the left, and then you want to create a "new div" animating it from the right. This code will helps you with that task (The comments in the code will help you to understand it):
HTML Code:
<button id="btn">Create</button>
<div id="container"></div>
JavaScript Code:
var sum = 1;
//---Function to create divs to animate
function createDiv() {
//---Disable button
active(false);
//---Access to the slide div
var slide = $("#container .slide");
//---If slide exists
if (slide.length > 0) {
//---Dissapear the slide to the left
slide.animate({
"opacity": 0,
"right": "100%"
}, function() {
//---Delete slide
$(this).remove();
//---Create new slide
var slide = create();
//---Appear slide from the right
appearSlide(slide);
});
//---If the slide no exists
} else {
//---Create slide
var slide = create();
//---Appear slide from the right
appearSlide(slide);
}
}
//---Create slide function
function create() {
var slide = $("<div/>");
slide.addClass("slide");
slide.text("div " + sum);
$("#container").append(slide);
sum++;
return slide;
}
//---Appear slide from the right function
function appearSlide(slide) {
slide.animate({
"opacity": 1,
"right": "0"
}, function() {
//---Enable button
active(true);
});
}
//---Enable / disable button function
function active(state) {
$("#btn").prop("disabled", !state);
}
//---Create a div by default
createDiv();
//---Create a alide when press the button
$("#btn").on("click", createDiv);
jsfiddle
I have the following HTML:
<div style="min-width:1024px;max-width:82%;margin:0 auto;overflow:auto">
<div style="height:344px;width:100%;float:left;margin-top:72px"></div>
<div style="width:100%;float:left;">
<div id="left" class="radius" style="height:700px;width:220px;background:#fff;float:left"></div>
<div id="middle" class="radius" style="width:760px;background:#fff;float:left;margin:0px 18px;">
<div style="height:700px;width:100%;float:left"></div>
</div>
<div id="right" class="radius" style="height:700px;width:280px;background:#fff;float:left"></div>
</div>
</div>
and script:
function scalling() {
var a = $(window).width();
if (a < '1300') {
var def = a * 82 / 100,
l = 22000 * def / 10,
m = 76000 * def / 10,
p = 28000 * def / 10;
$('#left').css('width', l);
$('#middle').css('width', m);
$('#right').css('width', p);
} else {
$('#left').css('width', '220px');
$('#middle').css('width', '760px');
$('#right').css('width', '280px');
}
}
scalling();
$(window).resize(function () {
scalling();
});
It works but add size to divs in oder way when window is scaling to be biger divs are smaler and when window is smaller the divs are bigger
Sorry for my bad anglish
You could simply use this CSS statement:
#media ( min-width :1300px){
selector{
width: constant-value;
}
}
#media ( max-width :1300px){
selector{
width: percent-value;
}
}