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;
}
}
});
Related
I need everyone's help. I currently need to implement a marquee effect. The yellow box needs to be scrolled up to show the name. Every time I scroll, I have to stay in the middle of the box for 1 second before continuing to scroll. I can find such an example on the Internet. , but the logic of this program is a bit difficult for me to understand for urban beginners. I wonder if anyone would like to provide a simpler and easier-to-understand writing method if I want to achieve this marquee effect?
Sorry, I am a beginner in the program, the current logic More complex programs are more difficult to understand.
function slideLine(box, stf, delay, speed, h) {
var slideBox = document.getElementById(box);
var delay = delay || 1000,
speed = speed || 20,
h = h || 40;
var tid = null,
pause = false;
var s = function() {
tid = setInterval(slide, speed);
};
var slide = function() {
if (pause) return;
slideBox.scrollTop += 1;
if (slideBox.scrollTop % h == 0) {
clearInterval(tid);
slideBox.appendChild(slideBox.getElementsByTagName(stf)[0]);
slideBox.scrollTop = 0;
setTimeout(s, delay);
}
};
setTimeout(s, delay);
}
slideLine("kanban_info", "p", 1000, 25, 40);
.kanban {
position: absolute;
margin: 0 auto;
width: 278px;
height: 50px;
background-color: yellow;
left: 50%;
transform: translate(-50%);
text-align: center;
line-height: 6;
}
.kanban .kenban_wrap {
height: 38px;
transform: translateY(28px);
overflow: hidden;
}
.kanban .kenban_wrap .kanban_info {
line-height: 38px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="kanban">
<div class="kenban_wrap" id='kanban_info'>
<p class="kanban_info">Allen</p>
<p class="kanban_info">james</p>
<p class="kanban_info">jack</p>
</div>
</div>
By combining scroll-behavior with anchor tags that are programmatically clicked you can simplify it. This should be easier to understand and you can go from there, even if it might not be the best solution.
let links = document.querySelectorAll("a"); // List of links
let div = document.querySelector("div");
let index = 0;
let t = 2000; // setTimeout duration
// Change Scroll behavior to prevent the animation from the last to first list item
function scrollBeh() {
if(index == 1) {
div.style.scrollBehavior = "auto";
t = 0; // Timeout duration to 0 to prevent `1` being shown longer than other list items
} else {
div.style.scrollBehavior = "smooth";
t = 2000;
}
}
// Loop through list items
function resetInd() {
if(index < 3) {
index++;
} else {
index = 0;
}
}
function clickLinks() {
links[index].click();
resetInd();
scrollBeh();
setTimeout(clickLinks, t);
}
setTimeout(clickLinks, t);
div {
width: 200px;
height: 100px;
background-color: darkblue;
overflow: hidden;
scroll-behavior: smooth;
}
li {
height: 100px;
list-style: none;
}
a {
text-decoration: none;
color: #FFF;
font-size: 50px;
}
<div>
<ul>
<li id="one">1</li>
<li id="two">2</li>
<li id="three">3</li>
<li id="one_loop">1</li>
</ul>
</div>
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/
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.
I have a function which counts the number of line breaks in a div, depending on the width of the window. While the functions works fine when placed in the $(window).on('resize') function, it does not work when put in $(document).ready() function. I want it to work right on page load, and also window resize, how do I support both?
JSFiddle
Javascript/jQuery:
// functions called in both document.ready() and window.resize
$(document).ready(function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Ready");
});
$(window).on('resize', function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Number of lines: " + lineCount);
});
// calculates the amount of lines required to hold the items
function getLineCount() {
var lineWidth = $('.line').width();
var itemWidthSum = 0;
var lineCount=1;
$('.item').each(function(index, element) {
if((lineWidth - itemWidthSum) > ($(element).outerWidth())) {
itemWidthSum = itemWidthSum + $(element).outerWidth();
} else {
lineCount++;
itemWidthSum = $(element).outerWidth();
}
});
return lineCount;
}
// overlays rows for the amount of linebreaks
function postItems(lineCount){
var container = $('<div />');;
for(var i = 1; i <= lineCount; i++) {
container.append('<div class="line">' + i + '</div>');
}
$('.line-wrap').html(container);
}
You'll see at the start of the page, it incorrectly shows 17 lines, and then once you resize it will show the correct amount.
The issue lies in the first line of getLineCount(). Originally you had
var lineWidth = $('.line').width();
but no elements with the class "line" exist yet on your page (since they get added in your postItems() method. I changed it to
var lineWidth = $(".container").width();
instead, and now your code should be working. Snippet posted below:
$(document).ready(function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Ready");
});
$(window).on('resize', function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Number of lines: " + lineCount);
});
// calculates the amount of lines required to hold the items
function getLineCount() {
var lineWidth = $('.container').width();
var itemWidthSum = 0;
var lineCount=1;
$('.item').each(function(index, element) {
if((lineWidth - itemWidthSum) > ($(element).outerWidth())) {
itemWidthSum = itemWidthSum + $(element).outerWidth();
} else {
lineCount++;
itemWidthSum = $(element).outerWidth();
}
});
return lineCount;
}
// overlays rows for the amount of linebreaks
function postItems(lineCount){
var container = $('<div />');;
for(var i = 1; i <= lineCount; i++) {
container.append('<div class="line">' + i + '</div>');
}
$('.line-wrap').html(container);
}
body {
text-align:center;
}
.answer {
position: fixed;
left: 0;
bottom: 0;
}
.container {
position: relative;
width: 50%;
margin: 0 auto;
border: 1px solid #e8e8e8;
display: inline-block;
}
.item {
height: 50px;
padding:0 10px;
background-color: #aef2bd;
float: left;
opacity:0.2;
white-space: nowrap;
}
.line-wrap {
position: absolute;
border: 1px solid red;
width: 100%;
height: 100%;
top:0; left: 0;
}
.line {
height: 50px;
width: 100%;
background-color: blue;
opacity:0.5;
color: white;
transition: all 0.5s ease;
}
.line:hover {
background-color: yellow;
color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="item-wrap">
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
</div>
<div class="line-wrap">
</div>
</div>
<h1 class="answer"></h1>
I have been working on this functionality where I have 5 circles then when a button is clicked they all move down the page one at a time in order. I am trying to get them to go down in a random order. (if not random at least something that doesn't make them fall in order)
JsFiddle: https://jsfiddle.net/n12zj90p/2/
HTML:
<div class="container">
<button>CLICK</button>
<div class="circle circle-1"></div>
<div class="circle circle-2"></div>
<div class="circle circle-3"></div>
<div class="circle circle-4"></div>
<div class="circle circle-5"></div>
</div>
CSS:
.circle{
width: 40px;
height: 40px;
position: absolute;
background: red;
border-radius: 100%;
}
.circle-1{ top: 10em; left: 10em; }
.circle-2{ top: 20em; left: 20em; }
.circle-3{ top: 30em; left: 30em; }
.circle-4{ top: 40em; left: 40em; }
.circle-5{ top: 50em; left: 50em; }
button{ padding: 10px 50px; display: table; margin: auto; }
JQUERY:
$(document).ready(function(){
var $c = $(".circle");
$("button").click(function(){
$c.each(function(i, elem){
$(elem).delay(i * 500).animate({top:"300em"}, { duration: 2000, complete: function(){
//just something to do after the animation has been completed, you can disregaurd this area
}
});//animate end
});//each end
});
});
var $c = $(".circle"); is an array. So you just need to randomly shuffle it before doing each on it
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
shuffle($c).each(...
Shuffle comes from here
Not sure I deserve any credit for this because it was Pointy's idea, but here's a code that's working and pretty simple:
$(document).ready(function(){
var $c = $(".circle");
$("button").click(function(){
$c.each(function(i, elem){
var rando_time = Math.floor((Math.random() * 600) + 1);
$(elem).delay(i * rando_time).animate({top:"300em"}, { duration: 2000, complete: function(){
//just something to do after the animation has been completed, you can disregaurd this area
}
});//animate end
});//each end
});
});