JS swapping an image smoothly - javascript

I already have a function to swap the images, but they swap without any animation. Now I want a function witch swaps the images with a fading. Here is my written code for the swap function:
var header = new Array();
header[0] = "images/lan/IMG_2799.jpg";
header[1] = "images/lan/IMG_2816.jpg";
var x = 0;
function swapHeader() {
document.getElementById("header").style.backgroundImage = "url(" + header[x] + ")";
if (x < header.length - 1) x++; else x = 0;
setTimeout("swapHeader()", 5000);
}
window.onload=swapHeader;

You may want to use two elements, one per image. Then, slowly increase and decrease the opacity (a CSS property) of the one on top. The rest of your content should go above those two elements, and have a transparent background.

Related

How can I scroll so that a specific element becomes at the middle of visible region of a div?

I have a series of list items and I want to put every specific item in the middle of the visible region of their parent div. So the first element can scroll to the middle I added some dummy items before it. (and also to the end of list items). and this is my function:
function scrollToMiddleView(elem) {
if (elem) {
var main = $("#container");
m = main.scrollTop() + main.height() / 2;
t = main.offset().top + m;
main.animate({scrollTop: elem.offset().top - t}, 500);
}
}
I test it on a sequence of elements. It works for some elements and doesn't work for some others. I works when the scrollbar is at the top. I want each element precisely located in the middle.
This is the function that worked. the main.scrollTop() must be subtracted from main.offset().top, and then the result must be subtracted from elem.offset().top.
function scrollToMiddleView(elem) {
if (elem) {
var main = $("#container");
m = main.height() / 2;
t = main.offset().top - main.scrollTop() + m;
q = elem.offset().top - t;
main.animate({scrollTop: q}, 500);
}
}

Progress Bar - Loop Through Array and Display Divs

Getting really stuck on this one... I'm trying to build a donation progress bar... In ReactJS - but I'm a beginner, so I want to get the code right first in Vanilla js...
What I'm trying to do, is loop through an array of numbers, (aka, donations already submitted via a form). EG:
[2, 5, 25] etc.
Everytime, a donation is submitted, it get's added to this array.
Want I want, is for my donation bar to increase/fill in colour, based on the donations already made in the array.
The bar would be full at 100%. Or £100.
Here's the snippet of JS I already have:
// FUNCTION TO CALCULATE TOTAL DONATIONS
const numbers = donated.map(Number);
function add(a, b) {
return a + b;
}
// SUM VALUE OF NUMBERS IN THE ARRAY
const sum = numbers.reduce(add, 0);
console.log('numbers', numbers);
//THE VALUE OF NUMBERS IN ARRAY, TURNED INTO A PERCENTAGE
const total = 100;
const percentage = (sum / total) * 100;
console.log('percentage', percentage);
// LOOP THROUGH EVERY NUMBER IN THE ARRAY, AND ADD A DIV WITH A MATCHING WIDTH
for (var i = 0; i < numbers; i++) {
if (i < 100) {
const div = document.createElement('div');
div.style.background = 'red';
div.style.width = numbers + 'px';
div.style.height = '50px';
div.style.float = 'left';
document.querySelector('.bar').appendChild(div);
}
}
The loop works, slightly. The first div in the array gets added. But as I add more donations, no more divs are added to the progress bar.
Eventually, I want to stop at 100...
Got it working! I needed to set numbers[i] in my style width:
for (var i = 0; i < numbers.length; i++) {
if (i < 100) {
div +1;
const div = document.createElement('div');
div.style.background = 'red';
**div.style.width = numbers[i] + 'px';**
div.style.height = '50px';
div.style.float = 'left';
document.querySelector('.bar').appendChild(div);
}
}
As i see, you styled your divs float left. That mean each div will appears over the previous on left. In chrome, right click on the div and left click on inspect. You will see that you have many divs generated in your Dom.

Javascript animation infinite loop

I am writing a simple animation in javascript (I can't use css) and I don't seem to make it infinite. this is what I have so far:
myMove(ball , i, size) {
var id = setInterval(frame, 3* i);
function frame() {
if (size == 100) {
size = 0;
} else {
size++;
ball.style.width = size/10 + 'px';
ball.style.height = size/10 + 'px';
}
}
}
the ball would be the element, the i is the iterated element in a for loop in which the function is called for each element.
for (var i = 0; i < numberOfBalls; i++{
myMove(document.getElementByClassName[i]('ball'), i, 10)
}
and size is the max size I wish my element expands to.
I wish to have a smooth transition, where the 5 balls will expand in succession (so first ball after 300ms, the second, after 300ms the third and so on) and when the last ball has expanded, repeat the process. I'm really struggling to get a decent result.
Thanks for your help

Animation changes the position of div's

Well I've implementes some divs and when I start the page I want them animate, they do, but the problem is that sometimes one div overlaps another one then I see a blank space... How could I avoid this? I'm doing this :
This is how I change the divs :
function swap(d1, d2){
var topaux, leftaux;
topaux = d1.css("top");
leftaux = d1.css("left");
d1.animate({
top: d2.css("top"),
left: d2.css("left"),
}, { duration: 1000, queue: false });
d2.animate({
top: topaux,
left: leftaux,
}, { duration: 1000, queue: false });
}
This is how I'm trying to do it now, but after try this, I didn't have any animation so I had this code and it worked I mean no overlaps between div's....
d1.css("top", d2.css("top"));
d1.css("left", d2.css("left"));
d2.css("top", topaux);
d2.css("left", leftaux);
I call this function (swap) when I'm shuffling the divs as follows :
function swapdivs(){
var i,r, c, d1, d2;
for (i = 1; i < 100; i++) {
r = Math.floor((Math.random() * rows) + 1);
c = Math.floor((Math.random() * columns) + 1);
d1= $("#r"+r+"c"+c);
r = Math.floor((Math.random() * rows) + 1);
c=Math.floor((Math.random() * columns) + 1);
d2 = $("#r"+r+"c"+c);
swap(d1,d2);
}
}
This is the jfiddle
What I'm missing?
Ok, now i see the problem.
In your barrejarPeces function you're scrambling randomly all elements multiple times (100)
for (i = 1; i < 100; i++) {
In the interanvipeces function you try to switch the position of 2 different elements with an animation of 1000ms, calculating their css attributes top and left
Well, the problem is when one (or both) elements are already switching position (since the barrejarPeces function will scramble 100 times without waiting any animation to finish), top and left values won't be correct.
So there are 2 possible solutions:
Don't use animation delay (try to set to 0 instead of 1000 in your fiddle and you'll see it works)
Scramble all elements just once (see my example here, where i changed some logic)

move object using css

I have an array of image objects:
var pics = ["pic1","pic2","pic3","pic4","pic5","pic6"]
I want to loop through and set the style.left value to 1 less than the current value. This loop iterates 100 times.
I got a great suggestion here to use css for this. I created a style called move:
margin-left: -1px;
This works great the first time through the loop:
for (i = 0; i < 100; i++) {
for (j = 0; j < 6; j++) {
var image = document.getElementById(pics[j]);
image.className = image.className + " move"
}
}
The problem is the images do not move after the first iteration though the loop. Any ideas what I can do?
The images do not move after the first iteration because you are applying the move class which sets the margin left to -1. Note it does not subtract 1 from their current left margin it sets it to -1.
So lets say it starts out with a left margin of 10 . When it goes through this loop I think you are expecting it to have a left margin of 9 to move it one pixel closer to the left side of the screen. Instead when it goes through this loop it will skip all the way -1 as the left margin because you are explicitly telling it to do that with your move class.
What you really want to do is use javascript to grab its current left margin , subtract 1 from that and then reset the left margin as the new, now less one, number.
At quick glance I think this tutorial could help you.
You can save off the margin variable and apply css with this:
var margin = -1;
for (i = 0; i < 100; i++) {
for (j = 0; j < 6; j++) {
var image = document.getElementById(pics[j]);
image.style.marginLeft = margin + "px";
margin--;
}
}

Categories

Resources