first question.
Basically, I’ve made an array of images and managed to loop it through randomly in order to change the background. It works fine. At set intervals and everything. But the transition is too sudden/jarring.
How can I make it fade in and out slowly please? Thats the whole code relating to that, there is even a button to trigger the change rather than wait. I’d like to make that fade in too! thank you.
var backs= [ "bike-1505039_1280.jpg",
"bananas-698608_1280.jpg",
"camera-813814_1280.jpg",
"chevrons-937583_1280.jpg",
"music-1283877_1280.jpg",
"pattern-26442_1280.png",
"people-2587310_1280.jpg",
"puppy-1903313_1280.jpg",
"road-166543_1280.jpg",
"stone-1664918_1280.jpg",
"street-1209403_1280.jpg",
"technology-2643270_1280.jpg"
];
setInterval(function() {
$("BODY").css("background-image", "url(" + backs[Math.floor(Math.random() * backs.length)] + ")");
}, 10000);
$("#backChange").on('click', function(event) {
$("BODY").css("background-image", "url(" + backs[Math.floor(Math.random() * backs.length)] + ")");
});
Since you're using the image as background for the body, I suggest to use CSS3 for the background property:
Please take a look at this post: CSS3 Fade Effect
use animate property to fade in
$('background-image').animate({ opacity: 1 }, { duration: 3000 });
Related
I'm trying to animate the elements on my page using jquery and CSS.
The elements are created dynamically thus using jquery.
The issue that i have is that the elements do not animate properly at all. they are actually blinking and go and back/forth and then animating which is not wanted.
This is a working fiddle to explain the issue better:
https://jsfiddle.net/npvsrkcy/12/
This is the sort of animation I'm trying to achieve:
This is my entire jquery code:
$.each($('.images '), function(i, el){
$(el).css({'opacity':0});
setTimeout(function(){
$(el).animate({
'-webkit-animation-delay': i+'s',
'animation-delay': i+'s',
'opacity':1.0
}, 450);
},500 + ( i * 500 ));
//add delay 3s
i+1000;
});
Could someone please advise on this issue?
This should be a good starting point for the effect you're looking for.
I moved the animation into a class. There's no need to specify css animation delay. Applying the class within the loop and timeout is all we need.
$.each($('.images '), function(i, el){
setTimeout(function(){
$(el).addClass('animate');
},500 + ( i * 500 ));
//add delay 3s
i+1000;
});
https://jsfiddle.net/8kpzwtoz/
I`m using the code to change background picture over time:
function getRandomInt(min, max)
{return Math.floor(Math.random()*(max-min+1))+min;}
function nextBackground()
{
var url = "url('images/" + getRandomInt(1, 33) + ".jpg')";
$body.css("background-image", url);
setTimeout(nextBackground, 7000);
}
setTimeout(nextBackground, 7000);
But I would like pictures to change not that sharply. Are there any way to do that?
If you use timing events with two overlaid images and have the opacity adjust slowly from 1 to 0, that should work for you I think.
This may be useful.
You could use CSS animationns with an animatable property... but this one isn't. The answers to this question should help you solve your problem, basically you should put your image behind the other one and turn the opacity of the old one up to 100% smoothly.
Hope it helped :)
You can fade the next image in by transitioning the property. Here's an example stripped down to the basics that does it on the background of a <div>, but you can change it to the background of the document, simply by changing the selector used in the nextBackground() function.
// If you put all the image paths into an array, the rest of the code gets much simpler
var images = ["https://images.seeklogo.net/2016/09/facebook-icon-preview-1.png",
"https://www.brandsoftheworld.com/sites/default/files/styles/logo-thumbnail/public/062012/twitter-bird-light-bgs.png?itok=HAQz1yQN",
"http://seeklogo.com/images/L/linkedin-icon-logo-05B2880899-seeklogo.com.gif",
"https://www.youtube.com/yt/brand/media/image/YouTube-logo-full_color.png",
"http://3835642c2693476aa717-d4b78efce91b9730bcca725cf9bb0b37.r51.cf1.rackcdn.com/Instagram_App_Large_May2016_200.png",
"http://lescalier-montreal.com/restaurant-bar/wp-content/uploads/2014/07/small-red-googleplus-icon.png"];
function getRandomInt() {
// No longer need min and max parameters, just the length of the array
return Math.floor(Math.random() * images.length);
}
function nextBackground(){
$("div").css("background-image", "url(" + images[getRandomInt()] + ")");
}
// For a continuously running timer, user setInterval, instead of setTimeout
setInterval(nextBackground, 1250);
div {
background-size:contain;
/*
CSS transitions cause properties that change to transition to the new value
There are numererous ways to configure the transition, but here, we're just
saying that any properties that change on the div should take 1 second to transition
from the old value to the new value.
*/
transition:1s;
height:250px;
width:250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
When I click a certain link I want the background-image to fadeOut, change to another image and then fadeIn.
The code I have:
$('.link').on('click',function(){
var image = $(this).data('image');
$('#div-with-the-bgimage').css('background-image', 'url('+image+')');
})
I tried this:
$('.link').on('click',function(){
var image = $(this).data('image');
$('#div-with-the-bgimage').fadeOut('3000').fadeIn('3000').css('background-image', 'url(' + image + ')');
})
but this didn't work, what am I doing wrong? (I'm new to jQuery)
EDIT:
I solved this with Rory McCrossan answer:
$('.link').on('click',function(){
var image = $(this).data('image');
$('#div-with-the-bgimage').fadeOut('3000', function() {
$(this).css('background-image', 'url('+image+')').fadeIn('3000');
});
});
But now this fadesOut to a white background and and then fadesIn to the image, giving a sensation of a flash? Is there a way to load the image before?
You need to chain the fades by calling the fadeIn after the fadeOut has completed. You can do this by using the callback function parameter. Try this:
$('.link').on('click',function(){
var image = $(this).data('image');
$('#div-with-the-bgimage').fadeOut('3000', function() {
$(this).css('background-image', 'url('+image+')').fadeIn('3000');
});
});
Wouldn't it be much simpler if you append / remove a div with the image you want and not change anything in the background? Just an example:
<div data-image="some-other-image.jpg" class="appendhere" style="position:relative">some content and an image background here</div>
Now using jQuery, you may put the image in the above data attribute on top, with 0 opacity, fade it in and out:
$('.link').on('click',function(){
var image = $(this).data('image');
var appendcode = '<div class="appended" style="display:none;position:absolute;width:200px;height:200px;overflow:hidden"><img src="' + image + '"></div>';
$('#div-with-the-bgimage').append(appendcode);
$('.appended').css({'opacity': 0, 'display':'block', 'z-index': 999}).fadeIn('3000', function() {
$(this).fadeOut('3000');
});
});
I used some inline styles there to point you need to make the wrapper relative positioned and the appended absolute positioned and with a higher z-index, you can make it much more elegant by including these in your CSS of course.
U can combine animate and opacity or use fadeOut and fadeIn functions.
Check out this link jsfiddle to see a working example using fadeOut and fadeIn.
U can also specify a unique img tag with data-gallery attribute storing multiple url's for images to toggle between all of them. Check this other link jsfiddle to see a working example. Click on the button Toggle to change the image.
Hope it useful!
I would like to change an image in my site with fading effect. The thing is that I am using two different classes for the same div, so actually I want to fade out one class and in the meanwhile start fading in the second class, before the first one has been completely removed.
HTML:
<div id="background_image" class="day"></div>
CSS:
.day{
background: url(day.png);
}
.night {
background: url(night.png);
}
JQuery:
setTimeout(function(){
if($("#background_image").hasClass("day")){
$("#background_image").fadeOut(function() {
$(this).removeClass("day");
});
$("#Landscape").fadeIn(function() {
$(this).addClass("night");
});
}else{
$("#background_image").fadeOut(function() {
$(this).removeClass("night");
});
$("#Landscape").fadeIn(function() {
$(this).addClass("day");
});
}
}, 5000);
But this code makes the image "day.png" first to disappear completely and then the "night.png" comes which is not what I want.
Is there a way to fade out the class "day" and start fade it "night" without having a blank space between the fading? Thanks in advance
It seems that what you're trying to do is cross-fading. This is normally done using 2 divs. If this is for the entire background, then I suggest http://srobbin.com/jquery-plugins/backstretch/. You can take a look at their implementation to narrow it down to just a div if you don't need it to cover the entire background.
This is how I solved it for a similar case.
var images = [
"/content/images/crane1.jpg",
"/content/images/crane2.jpg",
"/content/images/crane-interior.jpg"
];
// The index variable will keep track of which image is currently showing
var index = 0;
// Call backstretch for the first time,
// In this case, I'm settings speed of 500ms for a fadeIn effect between images.
$.backstretch(images[index], { speed: 500 });
// Set an interval that increments the index and sets the new image
// Note: The fadeIn speed set above will be inherited
setInterval(function () {
index = (index >= images.length - 1) ? 0 : index + 1;
$.backstretch(images[index]);
}, 5000);
EDIT:
For non-full background, take a look at this post Crossfade Background images using jQuery
Also take a look at this, might be closer to your scenario Cross fade background-image with jQuery
So I've been trying to figure this out for awhile and can't seem to get it.
I use a navigation consisting of circles (see website below) and when the user clicks on one, it forwards him/her to the corresponding slide.
When you click around, it will sometimes slide all the way back to the beginning of the window (margin-left = 0). If it doesn't do it at first, just click around for a second or two and you'll eventually see it.
http://dan.stargroupdev.com/
Here's the code that's buggy:
$("#footer-slidenav .links a").click(function () {
// Get nav index
var slidenum = $(this).attr("id").slice(3);
// Setup slide selector with string to avoid issues
var slidetext = ".slide:eq(" + slidenum + ")";
slidenum = $(slidetext).offset().left;
console.log("Top: " + slidenum);
var offset2 = 0;
// Find window offset to center slide if screen is bigger than 1000px (size of one slide)
if (($(window).width() - 1000) / 2 > 0) {
offset2 = ($(window).width() - 1000) / 2;
}
// Slide window to slide # that was clicked
$("html:not(:animated), body:not(:animated)").animate({
scrollLeft: slidenum
}, 1000, function () {
console.log("Middle: " + slidenum);
// Callback to center slide and give a nice little animated touch
slidenum = $(slidetext).offset().left;
console.log("Bottom: " + slidenum);
$("html:not(:animated), body:not(:animated)").animate({
scrollLeft: (slidenum - offset2)
}, "fast");
});
return false;
});
I tried things like $("html:not(:animated), body:not(:animated)") along with a few other similar possible solutions, but the bug is still there.
Any advice would be great and I'm more than happy to entertain any ideas you guys might have.
Thanks.
Turns out I had a leftover piece of code in another JS file. Sorry for wasting your time guys, that's why it was getting messed up.
I appreciate your answers though.
Ill propose an entirely new solution(mostly new)
$("#footer-slidenav .links a").click(function () {
var slidenum = $(this).attr("id").slice(3);
var slidetext = ".slide:eq(" + slidenum + ")";
offset = $(slidetext).position().left;
console.log(offset );
$("body").animate({
scrollLeft: offset
});
});
Could you give it a try?
my suggestion is to test the site without the class front on body. The script http://dan.stargroupdev.com/sites/all/themes/starsite/js/starsite.js use this class with result to create the unwanted behavior I think. If I remove it with firebug it works ok for me. Check it and give feedback to see if this is true.
First of all can I suggest Arial Flesler's scrollTo plugin? It's awesome and works like a charm.
You can use offsets to center the final position.
If you want some kind of easing then you can use them to make the animation look more natural. What about an elastic animation?
I've been using this plugin for over one year, without finding any problem.
Also, remember to .stop() the scrolled/animated element.