i have a div for which i want to show multiple images in the background as a fade in fade out by changing the css background image am unable to find the best way.
JSFiddle
My HTML:
<div id="background"></div>
Jquery
var bgArr = ["http://malsup.github.io/images/p1.jpg", "http://malsup.github.io/images/p1.jpg", "images/TopImage-03.jpg"];
var i = 0;
// Start the slide show
var interval = self.setInterval("swapBkgnd()", 5000)
function swapBkgnd() {
if (i > (bgArr.length - 1)) {
i = 0
$("#background").css("background-image", "url(" + bgArr[i] + ")");
} else {
$("#background").css("background-image", "url(" + bgArr[i] + ")");
}
i++;
};
CSS:
#background {
position: absolute;
min-height: 100%;
width: 100%;
height: auto;
top: 0;
left: 0;
background: url(http://2.bp.blogspot.com/-ayEwJpMGTPQ/USqliwPWo1I/AAAAAAAAHtI/ab6NHVy0Q48/s1600/tree.jpg) no-repeat center center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Use:
Jsfiddle: http://jsfiddle.net/ook3ah4p/
var interval = self.setInterval(swapBkgnd, 5000) // true syntax
instead of:
var interval = self.setInterval("swapBkgnd()", 5000) // wrong syntax
for animation:
$('#background')
.animate({opacity: 0}, 'slow', function() {
$(this)
.css({'background-image': "url(" + bgArr[i] + ")"})
.animate({opacity: 1});
});
Set it up like this:
function swapBkgnd() {
if (i > (bgArr.length - 1)) {
i = 0;
}
$("#background").fadeOut("slow", function () {
$(this).css("background-image", "url(" + bgArr[i] + ")");
$(this).fadeIn("slow");
});
i++;
};
Refering to this answer How to fade changing background image
var interval = self.setInterval(swapBkgnd, 5000)
function swapBkgnd() {
if (i > (bgArr.length - 1)) {
i = 0
$('#background').fadeTo('slow', 0.3, function(){
$(this).css('background-image', 'url(' + bgArr[i] + ')');
}).fadeTo('slow', 1);
} else {
$('#background').fadeTo('slow', 0.3, function(){
$(this).css('background-image', 'url(' + bgArr[i] + ')');
}).fadeTo('slow', 1);
}
i++;
};
Related
I have a heart movement on my page starting from the bottom of the page. Each randomly generates the size and speed of movement.
How can I make them, instead of appearing at the bottom of the page, appear when you click on the specified place, and move not evenly, but more chaotically and disappear before reaching the end?
var love = setInterval(function() {
var r_num = Math.floor(Math.random() * 40) + 1;
var r_size = Math.floor(Math.random() * 30) + 10;
var r_left = Math.floor(Math.random() * 100) + 1;
var r_time = Math.floor(Math.random() * 5) + 5;
$('.bg_heart').append("<div class='heart' style='width:" + r_size + "px;height:" + r_size + "px;left:" + r_left + "%;background:#ff94a7;-webkit-animation:love " + r_time + "s ease;-moz-animation:love " + r_time + "s ease;-ms-animation:love " + r_time + "s ease;animation:love " + r_time + "s ease'></div>");
$('.bg_heart').append("<div class='heart' style='width:" + (r_size - 10) + "px;height:" + (r_size - 10) + "px;left:" + (r_left + r_num) + "%;background:#ff94a7;-webkit-animation:love " + (r_time + 5) + "s ease;-moz-animation:love " + (r_time + 5) + "s ease;-ms-animation:love " + (r_time + 5) + "s ease;animation:love " + (r_time + 5) + "s ease'></div>");
$('.heart').each(function() {
var top = $(this).css("top").replace(/[^-\d\.]/g, '');
var width = $(this).css("width").replace(/[^-\d\.]/g, '');
if (top <= -100 || width >= 150) {
$(this).detach();
}
});
}, 500);
html,body{
height:100%
}
.bg_heart {
position: relative;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden
}
.heart {
position: absolute;
top: -50%;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-m-transform: rotate(-45deg);
transform: rotate(-45deg)
}
.heart:before {
position: absolute;
top: -50%;
left: 0;
display: block;
content: "";
width: 100%;
height: 100%;
background: inherit;
border-radius: 100%;
}
.heart:after {
position: absolute;
top: 0;
right: -50%;
display: block;
content: "";
width: 100%;
height: 100%;
background: inherit;
border-radius: 100%;
}
#-webkit-keyframes love {
0%{top:110%}
}
#-moz-keyframes love {
0%{top:110%}
}
#-ms-keyframes love {
0%{top:110%}
}
#keyframes love {
0%{top:110%}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header-plugin"></div>
<div class="bg_heart"></div>
To fly more chaotically use setInterval. You can also change the speed to whatever you need.
var brd = document.createElement("DIV");
document.body.insertBefore(brd, document.getElementById("board"));
const duration = 3000;
const speed = 0.5;
const cursorXOffset = 0;
const cursorYOffset = -5;
var hearts = [];
function generateHeart(x, y, xBound, xStart, scale)
{
var heart = document.createElement("DIV");
heart.setAttribute('class', 'heart');
brd.appendChild(heart);
heart.time = duration;
heart.x = x;
heart.y = y;
heart.bound = xBound;
heart.direction = xStart;
heart.style.left = heart.x + "px";
heart.style.top = heart.y + "px";
heart.scale = scale;
heart.style.transform = "scale(" + scale + "," + scale + ")";
if(hearts == null)
hearts = [];
hearts.push(heart);
return heart;
}
var down = false;
var event = null;
document.onmousedown = function(e) {
down = true;
event = e;
}
document.onmouseup = function(e) {
down = false;
}
document.onmousemove = function(e) {
event = e;
}
document.ontouchstart = function(e) {
down = true;
event = e.touches[0];
}
document.ontouchend = function(e) {
down = false;
}
document.ontouchmove = function(e) {
event = e.touches[0];
}
var before = Date.now();
var id = setInterval(frame, 5);
var gr = setInterval(check, 100);
function frame()
{
var current = Date.now();
var deltaTime = current - before;
before = current;
for(i in hearts)
{
var heart = hearts[i];
heart.time -= deltaTime;
if(heart.time > 0)
{
heart.y -= speed;
heart.style.top = heart.y + "px";
heart.style.left = heart.x + heart.direction * heart.bound * Math.sin(heart.y * heart.scale / 30) / heart.y * 100 + "px";
}
else
{
heart.parentNode.removeChild(heart);
hearts.splice(i, 1);
}
}
}
function check()
{
if(down)
{
var start = 1 - Math.round(Math.random()) * 2;
var scale = Math.random() * Math.random() * 0.8 + 0.2;
var bound = 30 + Math.random() * 20;
generateHeart(event.pageX - brd.offsetLeft + cursorXOffset, event.pageY - brd.offsetTop + cursorYOffset, bound, start, scale);
}
}
html,body{
height:100%
}
#keyframes heartfade {
0% {
opacity : 1;
}
50% {
opacity : 0;
}
}
.heart {
z-index : 999;
animation : heartfade 6s linear;
position : absolute;
}
.heart:before,
.heart:after {
content : "";
background-color : #ff94a7;
position : absolute;
height : 30px;
width : 45px;
border-radius : 15px 0px 0px 15px;
}
.heart:before {
transform : rotate(45deg);
}
.heart:after {
left : 10.5px;
transform : rotate(135deg);
}
I'm using this script for change img on click function
var fstSrc = 'img/1.jpg';
var sndSrc = 'img/2.jpg';
var trdSrc = 'img/3.jpg';
$(".aktualita1").click(function () {
$('img[src="' + sndSrc + '"]').attr('src', fstSrc);
$('img[src="' + trdSrc + '"]').attr('src', fstSrc);
});
When click, image changes immidiately, of course. How could i set a 0.5s duration for this click, so images will change with nice fade animation? :) Thanks!
You can fadeOut change the src of the image and then fadeIn giving you the desired effect.
var fstSrc = 'img/1.jpg';
var sndSrc = 'img/2.jpg';
var trdSrc = 'img/3.jpg';
$(".aktualita1").click(function () {
$('img[src="' + sndSrc + '"], img[src="' + trdSrc + '"]').fadeOut(250, function(){
$(this).attr('src', fstSrc);
}).fadeIn(250)
});
If you want the image to fade on top of the other one, consider using another image element on top of that one (or viceversa).
For example:
var fstSrc = 'https://i.imgur.com/EUym7Pw.jpg';
var sndSrc = 'https://i.imgur.com/Xt8ICog.jpg';
var trdSrc = 'https://i.imgur.com/Fp2EwFc.jpg';
$(".aktualita1").click(function() {
$('img[src="' + sndSrc + '"], img[src="' + trdSrc + '"]').each(function() {
if ($(this).is(':visible')) {
var pos = $(this).position();
$(this).parent().append($('<img src="' + fstSrc + '">').css({
position: 'absolute',
left: pos.left,
top: pos.top,
display: 'none'
}).fadeIn(500));
$(this).fadeOut(500);
}
})
});
.aktualita1 {
position: relative;
}
.aktualita1 img {
height: 200px;
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="aktualita1">
<img src="https://i.imgur.com/Xt8ICog.jpg">
<img src="https://i.imgur.com/Fp2EwFc.jpg">
</div>
I wrote a script that creates a set of smaller circles arranged in a circle, which are added to the DOM one by one with a loop. After first loop is done (so I would expected this to be when i == 54) I would like to start another loop, starting from the first circle in a list and one by one changing the color of the circles from grey to red.
This is my code:
var i = 1;
var appendCircle = function loop() {
setTimeout(function() {
var $circle = "<div class='circle circle" + i + "' style='transform:rotate(" + 7.2 * i + "deg) translate(3em)'></div>";
var $container = $(".circles-wrapper .circles");
$container.append($circle);
i++;
if (i < 55) {
loop();
}
}, 20);
// this is the problem because this change color of all small circles at once.
if (i == 54) {
setTimeout(function() {
$(".circle").each(function() {
$(this).css({
"background": "blue"
});
})
}, 20);
}
};
setTimeout(appendCircle, 100);
.circles-wrapper {
position: absolute;
top: 39%;
left: 51%;
}
.circles {
position: relative;
transform: rotateY(48deg);
}
.circle {
width: .2em;
height: .2em;
margin: -.2em;
border-radius: 50%;
background: #ceced0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="circles-wrapper">
<div class="circles"></div>
</div>
You're giving each circle the class "circle"+index so all you have to do is loop through each index and change the background color of each element. What I did was used the same loop function and after i reached 55 I took the mod 55 of it and used that to select the circle. Code and snippet below.
I also noticed that some circles overlap. if you generate 50 circles then there won't be any overlap. I wrote the code below to reflect this.
var i = 1;
var appendCircle = function loop() {
setTimeout(function() {
if (i < 51) {
var $circle = "<div class='circle circle" + i + "' style='transform:rotate(" + 7.2 * i + "deg) translate(3em)'></div>";
var $container = $(".circles-wrapper .circles");
$container.append($circle);
}
else{
var circleIndex = (i % 51)+1;
$(".circle"+circleIndex).css("background-color", "blue");
}
if(i<109){
loop();
}
i++;
}, 20);
};
setTimeout(appendCircle, 100);
.circles-wrapper {
position: absolute;
top: 39%;
left: 51%;
}
.circles {
position: relative;
transform: rotateY(48deg);
}
.circle {
width: .2em;
height: .2em;
margin: -.2em;
border-radius: 50%;
background: #ceced0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="circles-wrapper">
<div class="circles"></div>
</div>
After your first pass you probably want to find the circle created and modify those. You are giving them a class of circle + i so you can easily find them. Check the code snip. I added a third pass just because.
var i = 1,
CIRCLE_COUNT = 52;
var appendCircle = function loop() {
setTimeout(function() {
i++;
// first pass
if (i < CIRCLE_COUNT * 1) {
var $circle = "<div class='circle circle" + i + "' style='transform:rotate(" + 7.2 * i + "deg) translate(3em)'></div>";
var $container = $(".circles-wrapper .circles");
$container.append($circle);
}
// second pass
else if (i < CIRCLE_COUNT * 2) {
$(".circle" + (i % CIRCLE_COUNT+1)).css('background', 'blue');
}
// third pass
else if (i < CIRCLE_COUNT * 3) {
$(".circle" + (i % CIRCLE_COUNT+1)).remove();
}
// keep looping?
if (i <= CIRCLE_COUNT * 3)
loop();
}, 20);
};
setTimeout(appendCircle, 100);
.circles-wrapper {
position: absolute;
top: 39%;
left: 51%;
}
.circles {
position: relative;
transform: rotateY(48deg);
}
.circle {
width: .2em;
height: .2em;
margin: -.2em;
border-radius: 50%;
background: #ceced0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="circles-wrapper">
<div class="circles"></div>
</div>
something like this? i put a timeout function in your .each() in order to make a delay between each iteration of the loop when you change the color of the circles to blue
var i = 1;
var appendCircle = function loop() {
setTimeout(function() {
var $circle = "<div class='circle circle" + i + "' style='transform:rotate(" + 7.2 * i + "deg) translate(3em)'></div>";
var $container = $(".circles-wrapper .circles");
$container.append($circle);
i++;
if (i < 55) {
loop();
}
}, 20);
// this is the problem because this change color of all small circles at once.
if (i == 54) {
var time = 50;
$(".circle").each(function() {
var $this = $(this)
setTimeout(function(){
$this.css({
"background": "blue"
});
}, time)
time += 50;
});
}
};
setTimeout(appendCircle, 100);
.circles-wrapper {
position: absolute;
top: 39%;
left: 51%;
}
.circles {
position: relative;
transform: rotateY(48deg);
}
.circle {
width: .2em;
height: .2em;
margin: -.2em;
border-radius: 50%;
background: #ceced0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="circles-wrapper">
<div class="circles"></div>
</div>
You need to change the CSS of just one element, then start a timeout to change the next one.
var i = 1;
var appendCircle = function loop() {
setTimeout(function() {
var $circle = "<div class='circle circle" + i + "' style='transform:rotate(" + 7.2 * i + "deg) translate(3em)'></div>";
var $container = $(".circles-wrapper .circles");
$container.append($circle);
i++;
if (i < 55) {
loop();
}
}, 20);
var j = 0;
function changeColor() {
$(".circle").eq(j).css("background", "blue");
j++;
if (j >= $(".circle").length) {
clearInterval(changeInterval);
}
}
if (i == 53) {
setInterval(changeColor, 20);
}
}
setTimeout(appendCircle, 100);
.circles-wrapper {
position: absolute;
top: 39%;
left: 51%;
}
.circles {
position: relative;
transform: rotateY(48deg);
}
.circle {
width: .2em;
height: .2em;
margin: -.2em;
border-radius: 50%;
background: #ceced0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="circles-wrapper">
<div class="circles"></div>
</div>
jQuery has features that make animations like this reasonably trivial, though you need to understand several methods.
jQuery's .delay(), .promise(), .then() and javascript's Array.prototype.reduce() can be exploited as follows :
var appendCircles = function($container) {
//create and append hidden circles
for(var i=0; i<50; i++) {
$("<div class='circle'></div>").css('transform', 'rotate(' + 7.2 * i + 'deg) translate(3em)').hide().appendTo($container);
}
//find the freshly appended hidden circles
var $circles = $container.find(".circle");
//initial delay
$circles.eq(0).delay(100).promise()
.then(function() {
//show the circles, one by one
return $circles.get().reduce(function(promise, el) {
return promise.then(function() {
return $(el).show().delay(20).promise();
});
}, $.when());//$when() is a resolved promise that gets the built promise chain started
})
.then(function() {
//make circles blue, one by one
return $circles.get().reduce(function(promise, el) {
return promise.then(function() {
return $(el).css('backgroundColor', 'blue').delay(20).promise();
});
}, $.when());//$when() is a resolved promise that gets the built promise chain started
});
};
appendCircles($(".circles"));
codepen
.reduce() probably needs some explanation. $circles.get() returns an array and .reduce(...) is used to build a promise chain equivalent to initialPromise.then(...).then(...).then(...). This trick is performed twice, in sequence, to give the initial "show" effect followed by the color-change effect.
This suite of methods is worth learning if you want to make custom animation sequences with jQuery.
I have some Javascript code that I got from codepen.io. But I'm having a tough time executing it, although it is the same exact code. I'm just learning Javascript so I am a beginner. I didn't use HTML, I just used CSS & Javascript. The background image does shuffle through, but the fade does not work.
Here is my CSS snippet:
body {
margin: 0;
background-image: url(/image1.jpg) no-repeat center center fixed;
background-size: cover;
margin: 0;
width: 100%;
height: 100%;
transition: 1s;
}
Here is the JS that goes with it.
var bgImageArray = ["image2.jpg", "image3.jpg", "image4.jpg"],
base = "/",
secs = 4;
bgImageArray.forEach(function(img){
new Image().src = base + img;
// caches images, avoiding white flash between background replacements
});
function backgroundSequence() {
window.clearTimeout();
var k = 0;
for (i = 0; i < bgImageArray.length; i++) {
setTimeout(function(){
document.documentElement.style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center fixed";
document.documentElement.style.backgroundSize ="cover";
if ((k + 1) === bgImageArray.length) { setTimeout(function() { backgroundSequence() }, (secs * 1000))} else { k++; }
}, (secs * 1000) * i)
}
}
backgroundSequence();
Any help would be greatly appreciated!
I think the problem is that you defined the CSS rules to the body but in your JavaScript, the new images are attached to documentElement, which is equal to html tag and not to body tag.
Try changing these lines:
document.documentElement.style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center fixed";
document.documentElement.style.backgroundSize ="cover";
to this:
document.body.style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center fixed";
document.body.style.backgroundSize ="cover";
Just changed documentElement with body
You should change document.documentElement to document.body and you can remove window.clearTimeout
You can see this demo for working:
http://codepen.io/dangvanthanh/pen/NGpqYr
I've an image slider, in which I want to slice the image to create some kind of 3D-Effekt. I created the slider, but now I'm struggling with the responsive behavior of the slider.
In px values, everything is working finde, but I want the slider to be responsive.
Could somebody look at my code and give me a solution to solve the problem?
Here is my code:
The SCSS:
/*Variables & Helper*/
*{
box-sizing: border-box;
}
%clearfix {
&:after {
content: "";
display: table;
clear: both;
}
}
body, html{
margin: 0;
padding: 0;
background: url('../img/bg.png');
}
img{
max-width: 100%;
height: auto;
}
.article{
width: 80%;
margin: 2rem auto;
background: #fff;
#extend %clearfix;
padding: .8rem;
}
.img__container {
float: left;
width: 100%;
margin: 0;
}
.slice{
float: left;
}
And here is the JavaScript:
$(function(){
$( window ).on('resize',function() {
calcDimensions();
bgPosition();
});
/*Variables*/
var $imgContainer = $('.img__container'),
$img = $imgContainer.children('img'),
slices = 5,
percentage = 100 / slices + '%',
imgWidth = $imgContainer.width(),
imgHeight = $imgContainer.height();
/**/
sliceImg();
/*Functions*/
function calcDimensions(){
imgWidth = $imgContainer.width();
imgHeight = $imgContainer.height();
};
function bgPosition(){
for (var i = 0; i < slices; i++){
$('#slice' + i).css({
'background-position' : - ( (imgWidth / slices) * i ) + 'px 0%',
});
};
}
function sliceImg(){
var imgLink = $img.attr('src');
/* Delete the image */
$img.remove();
/*Loop*/
/*Create new divs*/
for (var i = 0; i < slices; i++){
var newDiv = $('<div></div>').addClass('slice').attr('id', 'slice' + i);
$imgContainer.append(newDiv);
};
/**/
bgPosition();
$('.slice').css({
'background-image' : 'url(' + imgLink + ')',
'width' : percentage,
'height' : imgHeight ,
'background-size' : 'cover',
});
};
});
So, if i resize the window, it's kind of responsive. But not as great as a real responsive experience.
I also tried something like that, which should be the right mathematic operation. But in jQuery i can't do mathematic operations with %, or am I wrong? Because I'm always getting errors....
$('.slice').css({
'background-image' : 'url(' + imgLink + ')',
'width' : (imgWidth / slices / 100 * 1%) ,
'height' : imgHeight ,
'background-size' : 'cover',
});
I'm looking forward to get a solution.
Thanks!
Best regards,
You said you used 'px', so I think everything will go well if you use 'em' instead of 'px'. And correct me If I am wrong, but I think you might want to use Dootstrap for responsive design.