Changing background images with js - javascript

Im trying to work out script that will change background images every 3 sec using fadeIn, fadeOut, addClass and removeClass.
Is there a better way to do it using setInterval?
$("document").ready(function () {
$("#bg").delay(3000);
$("#bg").fadeOut(300);
$("#bg").removeClass('bg1');
$("#bg").addClass('bg2');
$("#bg").fadeIn(300);
$("#bg").delay(3000);
$("#bg").fadeOut(300);
$("#bg").removeClass('bg2');
$("#bg").addClass('bg1');
$("#bg").fadeIn(300);
});
btw. its not working properly.
HTML:
<div id="bg" class="ShowBG bg1"></div>
CSS:
#bg{
position:absolute;
width:100%;
height:70%;
background-size:cover;
background-position:center;
display:none;
}
.bg1{background-image:url("/img/index/bg1.png");}
.bg2{background-image:url("/img/index/bg2.png");}

Your method should work just fine but it's not the best way to write it: what if your graphic designer suddenly decides to add another background image in the cycle? Your code could become pretty long pretty fast. Here's how I would do it:
var backgroundClasses = ['bg1', 'bg2']; // Store all the background classes defined in your css in an array
var $element = $('.container'); // cache the element we're going to work with
var counter = 0; // this variable will keep increasing to alter classes
setInterval(function() { // an interval
counter++; // increase the counter
$element.fadeOut(500, function() { // fade out the element
$element.removeClass(backgroundClasses.join(' ')). // remove all the classes defined in the array
addClass(backgroundClasses[counter % backgroundClasses.length]). // add a class from the classes array
fadeIn(500); // show the element
});
}, 3000)
.container {
width: 100vw;
height: 100vh;
}
.bg1 {
background-color: red;
}
.bg2 {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container bg1"></div>
The hardest part of the code is this:
$element.addClass(backgroundClasses[counter % backgroundClasses.length])
It basically adds one of the classes stored in the backgroundClasses array. Using the modulo operator (%) on the counter will basically start over every time it has reached the end of the array, counting 0, 1, 0, 1, 0, 1 if you're array is only 2 elements long. If it's 3 elements long it counts 0, 1, 2, 0, 1, 2, ... and so on. Hope that makes sense.

Use callback of fadeOut() method (see complete parameter here) to perform class change when the animation is done. Otherwise the class will swap while the animation is still going.
There is no better way than using setInterval() if you want to do it automatically and continuously.
Here is working example:
$("document").ready(function () {
var bg = $("#bg");
setInterval(function() {
// We fadeOut() the image, and when animation completes we change the class and fadeIn() right after that.
bg.fadeOut(300, function() {
bg.toggleClass('bg1 bg2');
bg.fadeIn(300);
});
}, 1500);
});
#bg {
position:absolute;
width:100%;
height:70%;
background-size:cover;
background-position:center;
}
.bg1 {
background-image: url("https://www.w3schools.com/css/img_fjords.jpg");
}
.bg2 {
background-image: url("https://www.smashingmagazine.com/wp-content/uploads/2015/06/10-dithering-opt.jpg");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bg" class="ShowBG bg1"></div>

Edit
Just noticed OP wants fading so I added a simple CSS transition and opacity properties to both classes and #bg.
Use toggleClass(). Not sure why you used display:none so I removed it. Also I added the dimensions to html and body so your div has something to relate it's percentage lengths with.
Demo
setInterval(function() {
$('#bg').toggleClass('bg1 bg2');
}, 3000);
html,
body {
height: 100%;
width: 100%
}
#bg {
position: absolute;
width: 100%;
height: 70%;
background-size: cover;
background-position: center;
opacity:1;
transition:all 1s;
}
.bg1 {
background-image: url("http://placehold.it/500x250/00f/eee?text=BG1");
opacity:1;
transition:all 1s;
}
.bg2 {
background-image: url("http://placehold.it/500x250/f00/fff?text=BG2");
opacity:1;
transition:all 1s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bg" class="ShowBG bg1"></div>

Related

setTimeout and display none with a fader timer- How to do it chronologically?

I am sitting with a project in need of an overlay which fades out when hovered upon and goes to display: none (not visibility: hidden, it does need to be display: none).
The setup is a big confusing, but I will try to explain it:
The overlay comes up when I hover a menu point under my mega menu. When I move the cursor to the overlay it should naturally dissapear and the menu close.
This works very well with this code:
var element = document.getElementById("overlayed");
function mouseOver() {
element.classList.add("mystyle");
setTimeout(function() {
element.classList.remove("mystyle");
}, 500);
}
push {
position: absolute;
top: 50%;
}
.overlayerstwo {
position: fixed;
width: 100%;
top: 30%;
left: 0;
right: 0;
bottom: 0;
background: #111;
opacity: 0.5;
z-index: 2;
display: block;
visibility: visible;
}
.mystyle {
display: none;
animation-name: fadeOut;
animation-duration: .5s;
}
#keyframes fadeOut {
0% {
opacity: .5
}
100% {
opacity: 0;
}
}
.mystyler {
display: none;
}
<h1>Here is something. Overlay comes back when hovering me!</h1>
<div class="overlayerstwo" id="overlayed" onmouseover="mouseOver()"></div>
<div class="push">
<p>Here is an item being overlayed</p>
</div>
With this setup the overlay dissapears right away. I am trying to merge it with the fadeOut keyframe animation before it goes black. I have tried different tactics, like adding a second timeout event but all it does is loop through and end up showing the overlay permanently after.
So the order I want to achieve is as follows:
Add a class that fires the keyframe animation fadeOut for .5 sec
Remove keyframe animation class
Add display: block class
Remove display: block class (essentially resetting it, so you can get the overlay up again by hovering its triggerpoint)
So my question is, how do I get all of these to fire every time I hover over the overlay?
One of the things I tried was this:
var element = document.getElementById("overlayed");
element.classList.add("mystyle");
setTimeout(function(){
var element = document.getElementById("overlayed");
element.classList.remove("mystyle");
}, 500);
setTimeout(function(){
var element = document.getElementById("overlayed");
element.classList.add("mystyletwo");
}, 500);
setTimeout(function(){
var element = document.getElementById("overlayed");
element.classList.remove("mystyletwo");
}, 510);
With the css
.mystyle{
animation-name: fadeOut;
animation-duration: .5s;
}
.mystyletwo{
display: block;
}
Which did not work. I hope someone can help me figure out how to get it to work!
if the timeline will be like this: visible -> hover -> animation -> opacity to 0 -> display: none
using CSS with JS logic:
element.addEventListener("mouseover", function() {
element.style.opacity = "0";
element.style.transition = "all 0.3s";
// when finish the animation then call display none
setTimeout(function() {
element.style.display = "none";
}, 300); // put the same number (milliseconds) of duration of transition (or more, not less)
});
using this method you don't need to complex your code...
the trick really is because we use element.style
that is only put the CSS, but technically...
if there is a transition Javascript don't know it,
so it will run the setTimeout() directly after adding styles,
so now CSS will do the animation but javascript will quietly continue the code (which in our case, says that after 300 seconds add display: none;)

Image Carousel with Fade to Black Transition

I need to make a carousel with a fade transition that goes black, or even better some dark grey color like #2B303A. I've found this code on the web that works perfectly, the only problem is that the fade effect is a really bright white that I don't like and it's bothering for the eyes.
How can I make it fade to black between images?
$(document).ready(function() {
//Carousel
var vet_url = ["https://i.imgur.com/Bb39Qpp.jpg", "https://images.wallpaperscraft.com/image/palms_road_marking_123929_1920x1080.jpg"];
var len = vet_url.length;
var i = 0;
function swapBackgrounds() {
$("#background").animate({
opacity: 0
}, 700, function() {
$($("#background")).css('background-image', 'url(' + vet_url[(i + 1) % len] + ')').animate({
opacity: 1
}, 700);
});
i++;
}
setInterval(swapBackgrounds, 10000);
});
#background {
background-color: #2B303A;
position: absolute;
z-index: 1;
min-height: 100%;
min-width: 100%;
background-image: url("https://images.wallpaperscraft.com/image/palms_road_marking_123929_1920x1080.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="background"></div>
View on JSFiddle
you need to do it on the html element, in your test case at least.
html
{
background-color:#2B303A;
}
Setting the opacity to 0 let you see the element underneath the carousel, in this case there's nothing but the body itself. The background-color of the body wasn't set so it was the default white one. Setting the background-color to black solved the problem.
jquery's .animate does not work with background-colors though it can work with:
https://github.com/jquery/jquery-color

Repeat animation by clicking button

I would like to repeat animation every time, when I click my button. I tried to do something like this.
const dist = document.querySelector('.dist');
document.querySelector('button').addEventListener('click', () => {
dist.classList.remove('animation');
dist.classList.add('animation');
});
.dist {
width: 100px;
height: 100px;
background: black;
margin-bottom: 30px;
}
.animation {
transform: scale(1.5);
transition: transform 3s;
}
<div class="dist"></div>
<button type="button">Trigger Animation</button>
But actually, this snippet does it only one time.
dist.classList.remove('animation');
dist.classList.add('animation');
Shouldn't this part remove state and start animating from the beginning?
Updated fiddle.
You should give the remove an extra time before adding the new class animation (just a small Timeout will do the trick) :
dist.classList.remove('animation');
setTimeout(function(){
dist.classList.add('animation');
},10);
Hope this helps.
const dist = document.querySelector('.dist');
document.querySelector('button').addEventListener('click', () => {
dist.classList.remove('animation');
setTimeout(function(){
dist.classList.add('animation');
},10);
});
.dist {
width: 100px;
height: 100px;
background: black;
margin-bottom: 30px;
}
.animation {
transform: scale(1.5);
transition: transform 3s;
}
<div class="dist"></div>
<button type="button">Trigger Animation</button>
The class changes are being batched. You should request an animation frame to add the class back to the element:
window.requestAnimationFrame(function() {
dist.classList.add('animation');
});
const dist = document.querySelector('.dist');
document.querySelector('button').addEventListener('click', () => {
dist.classList.remove('animation');
window.requestAnimationFrame(function() {
dist.classList.add('animation');
});
});
.dist {
width: 100px;
height: 100px;
background: black;
margin-bottom: 30px;
}
.animation {
transform: scale(1.5);
transition: transform 3s;
}
<div class="dist"></div>
<button type="button">Trigger Animation</button>
Docs for requestAnimationFrame
See updated Fiddle
This doesn't work because there is no time there for the animation to happen. Essentially the browser doesn't ever notice the class being removed because the element gains it back immediately after it is removed. There's no time for it to see the change so it doesn't animate. In order to get it to repeat you need to give it some time to notice, a setTimeout is a good choice for this.
Also if you want it to animate returning back to the smaller size you need to change which class has the transition timing. If you have it on the added class, once it's remove you lose the timing so it snaps back to the smaller size.
If you don't care about the animation returning, keep your css the same and change the timeout to something shorter like 100.
Try doing something like:
const dist = document.querySelector('.dist');
document.querySelector('button').addEventListener('click', () => {
if(!dist.classList.contains('animation')){
dist.classList.add('animation');
} else {
dist.classList.remove('animation');
// Add it back after 3 seconds;
setTimeout(function(){
dist.classList.add('animation');
}, 1000 * 3);
}
});
.dist {
width: 100px;
height: 100px;
background: black;
margin-bottom: 30px;
transition: transform 3s;
}
.animation {
transform: scale(1.5);
}
<div class="dist"></div>
<button type="button">Trigger Animation</button>
I had The same issue and the above answers helped me get the solution that worked for me .
the requestAnimationFrame() was adding the class before the animation is complete , and the setInterval()
was keep executing for ever after user clicks and might conflict with the next clicks so , I had tow solutions either using requestAnimationFrame() with time stamp Or use setTimeout() and clearInterval()
with the following steps :
make a separate function for adding class
function addAnimation(){
dist.classList.add('animation');
}
Inside the removing animation function call the addAnimation() inside setTimeout() and assign that into variable so we can use clearInerval() to stop it
document.querySelector('button').addEventListener('click', () => {
dist.classList.remove('animation');
animate = setTimeout(addAnimation,2000)
});
now lets go back to the addAnimation() function and add clearInerval() ,this will stop the extra execution that might cause issues.
function addAnimation(){
dist.classList.add('animation');
clearInerval(animate);
}
this way when user clicks the class is removed and after the setTimeout time the class is added (just once ) since we used clearInerval() after adding the class
NOTE :
in my case I was first adding the class to animate and then removing it .
Hope that is clear and help some one; its too late form the question publish date.
All The best!

Changing the hide show toggle effect?

I have an element that works just fine with the following code. It's an object #obj1 that is hidden when loading the page, but appears when clicking on #obj2.
#obj1{
position:fixed;
width:100px;
bottom:180px;
right:100px;
display:none;
}
$("#obj1").hide();
$("#obj2").show();$('#obj2').toggle(function(){
$("#obj1").slideDown(function(){});
},function(){
$("#obj1").slideUp(function(){});
});
but I would like to have it like this:
$("#obj1").css({"opacity": "0","bottom": "180"})
$("#obj2").toggle(
function () {
$("#obj1").animate({"opacity": "1","bottom": "140"}, "slow");
},function () {
$("#obj1").animate({"opacity": "0","bottom": "180"}, "slow");
});
I would like it to fade in, but how do I add the animation to the first script? (animation ex: .animate({"opacity": "1","bottom": "140"}, "slow");)
Here is a super simple demo of fading in an element using CSS. You can use jQuery to add the class through a click event.
// HTML
<div id="myId" class="hide">
This is div with myId
</div>
// CSS
.hide {
display: none;
}
.myId {
animation: fadein 2s;
}
#keyframes fadein {
from { opacity: 0; }
to { opacity: 1; }
}
// JQUERY
$("#myId").removeClass("hide").addClass("myId");
You can see a working demo here. You'll just have to modify it to trigger on click of obj2 or where you like
EDIT - As per your comment above I have edited the pen, so now the element will be hidden on page load and then the class will be removed and the animation class added.
You would be best keeping the styles within css, and just using js to change the state (add/remove a class). The way you have the javascript is passable, but it'd be better for the class to be toggled based on itself so they can't accidentally get out of sync:
$('#obj2').on('click',function(e){
e.preventDefault();
if($('#obj1').hasClass('js-on'))
$('#obj1').removeClass('js-on');
else
$('#obj1').addClass('js-on');
});
#obj1{
position:absolute;
width:100px;
bottom:10px;
right:20px;
opacity: 0;
background-color: yellow;
padding: 1em;
transition: .5s opacity, .5s bottom;
}
#obj1.js-on {
opacity: 1;
bottom: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="obj2" href="#">Click me</a>
<div id="obj1">Hi</div>
$(document).ready(function() {
$("#obj1").hide();
$("#obj2").show();
});
$('#obj2').toggle(function(){
$("#obj1").slideToggle();
});
This will show obj1 by sliding when obj2 is pressed. To have it fade in instead Try,
$("#obj2").click(function () {
$("#obj1").fadeToggle("slow","swing");
This toggles obj1 fading in and out.
reference:
http://api.jquery.com/fadetoggle/
Slightly confused by the question, but here's my attempt at an answer: hope it helps
$(".obj1").click(function(){
$(".obj2").css('opacity', 0)
.slideDown('slow')
.animate(
{ opacity: 1 },
{ queue: false, duration: 'slow' }
);
});
.obj1 {
display: inline-block;
padding: 10px;
background: lightgrey;
}
.obj2 {
height: 100px;
width: 100px;
background: red;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="obj1">click me</div>
<div class="obj2"></div>

I need to close a gap in this JQuery animation

Here is my Jquery code:
var img = function() {
$(".slider#1").delay(1000).fadeIn(1000);
$(".slider#1").delay(3000).fadeOut(1000);
$(".slider#2").delay(5000).fadeIn(2000);
$(".slider#2").delay(3000).fadeOut(1000);
$(".slider#3").delay(10000).fadeIn(2000);
$(".slider#3").delay(3000).fadeOut(1000);
$(".slider#4").delay(15000).fadeIn(2000);
$(".slider#4").delay(3000).fadeOut(1000, function() { img() });
};
Essentially what I am trying to do is when one image fades out I would like an image to almost be behind it and fade straight into that without being a blank space in between, is this possible?
You could use the jQuery fadeTo function.
Like
$(".slider#1").fadeTo(1000,1);
And make all your sliders overlap each other with opacity 0.
Edit :
You can try this fiddle :
http://jsfiddle.net/8cwA6/22/
It recursively changes the opacity. All the images are on top of each other, then it fades out Level 1, then Level 2, and then fades both of them back (because Level 3 is on the bottom). You'll probably understand better when you see the code.
JavaScript
var max = 3
var min = 1
var showTime = 1500
function fade(num) {
if (num > min) {
$('.' + num).delay(showTime).fadeTo("slow", 0, function() {
fade(num - 1);
});
} else {
$("div").delay(showTime).fadeTo("slow", 1, function() {
fade(max)
});
}
}
fade(3);
HTML
<div id="img1" class="1"></div>
<div id="img2" class="2"></div>
<div id="img3" class="3"></div>
CSS
#img1 {
width:100px;
height:100px;
background-color:red;
position:absolute;
top:0;
left:0;
opacity :1;
z-index :1;
}
#img2 {
width:100px;
height:100px;
background-color:blue;
position:absolute;
top:0;
left:0;
opacity :1;
z-index :2;
}
#img3 {
width:100px;
height:100px;
background-color:green;
position:absolute;
top:0;
left:0;
opacity :1;
z-index :3;
}
You have to queue the animations, or they will get mixed up after some time, since your animations are running asynchronous;
I did stack all images, and all are visible (you could set z-index just to be certain).
Fading out the top most, the next one is showing up.
The bottom most, doesn't have to be faded. I fade in the first one again, before resetting/showing all the other images once again and resetting the recursion.
jsfiddle
http://jsfiddle.net/Drea/hkzbvew4/
js
var images = ['.slider1', '.slider2', '.slider3', '.slider4']; // .slider4 is always visible
var img = function (i, showtime, fadetime) {
$(images[i]).delay(showtime).fadeOut(fadetime).queue(function () {
i++;
if (i < images.length-1) { // run through images
img(i, showtime, fadetime);
$.dequeue(this);
} else { // reset animation
$(images[0]).delay(showtime).fadeIn(fadetime).queue(function () {
$(".slide").fadeIn(0);
img(0, showtime, fadetime);
$.dequeue(this);
});
$.dequeue(this);
}
});
};
img(0, 1000, 1000);
html
<div class="slide slider4"></div>
<div class="slide slider3"></div>
<div class="slide slider2"></div>
<div class="slide slider1"></div>
css
.slide {
width: 50px;
height: 50px;
position: absolute;
top: 50px;
left: 50px;
}
.slider1 {
background-color: black;
}
.slider2 {
background-color: green;
}
.slider3 {
background-color: blue;
}
.slider4 {
background-color: red;
}

Categories

Resources