Changing multiple background images on click with javascript - javascript

So I an trying to have multiple background image changes on click using javascript.
Can anyone help here I am trying to change multiple background images with a click, with this code I am getting 2 image changes but somewhere at the function updateIndex I can't work out how to make it continuous throughout multiple images.
Thanks a lot in advance!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<div id="body" class="imageOne"></div>
<style>
html,
body, {
height: 100%;
width: 100%;
}
#body.imageOne {
background-image: url("first.svg");
}
#body.imageTwo {
background-image: url("2.svg");
}
#body.imageThree {
background-image: url("3.svg");
}
#body.imageFour {
background-image: url("first.svg");
}
</style>
<script>
var bodyObj, className, index;
// all background images, calling them to change
bodyObj = document.getElementById('body');
index = 1;
className = [
'imageOne',
'imageTwo',
'imageThree',
'imageFour',
];
function updateIndex() {
if (index === 0) {
index = 1;
} else {
index = 1;
index = 2;
}
}
bodyObj.onclick = function(e) {
e.currentTarget.className = className[index];
updateIndex();
}
</script>

Set the index to 0
and in order to loop use ++index % className.length
const className = ['imageOne','imageTwo','imageThree','imageFour'];
let index = 0;
function updateClassName() {
this.className = className[++index % className.length];
}
document.getElementById('body').addEventListener("click", updateClassName);
html, body{height: 100%;width: 100%; margin:0;}
#body{ height: calc(100% - 4rem); background: center / cover; }
#body.imageOne {background-image: url("//placehold.co/800x600/0bf/fff");}
#body.imageTwo {background-image: url("//placehold.co/800x600/f0b/fff");}
#body.imageThree {background-image: url("//placehold.co/800x600/b0f/fff");}
#body.imageFour {background-image: url("//placehold.co/800x600/fb0/fff");}
Click the image
<div id="body" class="imageOne"></div>

The issue is due to the logic in the updateIndex() function. You only set the index to 0, or to 1, then for some reason 2 immediately. It doesn't cycle around.
To fix the logic you can simply increment the index on each successive click. Try this:
var bodyObj = document.getElementById('body'),
index = 1,
className = ['imageOne', 'imageTwo', 'imageThree', 'imageFour']; // remove trailing comma here
function updateIndex() {
index = ++index % className.length;
}
bodyObj.addEventListener('click', function(e) {
e.currentTarget.className = className[index];
updateIndex();
});
#body {
height: 250px;
width: 250px;
}
#body.imageOne { background-image: url("https://dummyimage.com/250/000000/ffffff"); }
#body.imageTwo { background-image: url("https://dummyimage.com/250/cc0000/000000"); }
#body.imageThree { background-image: url("https://dummyimage.com/250/00cc00/000000"); }
#body.imageFour { background-image: url("https://dummyimage.com/250/0000cc/000000"); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="body" class="imageOne"></div>
Also note the use of addEventListener() over the outdated onclick.

Related

Simulate 'backspace' in Jquery

I have a simple animation code, looks like a console input.
Originally from: https://codepen.io/atunnecliffe/pen/BaZyLR
I modified the splash screen intro into just a console input in my website:
Code:
<script>
//console
var textarea = $('.term');
var text = 'ping life';
var i = 0;
runner();
function runner() {
textarea.append(text.charAt(i));
i++;
setTimeout(
function () {
runner();
}, Math.floor(Math.random() * 1000) + 50);
}
</script>
Now the effect that I want is a bit complex, for me at least, as my knowledge about JQuery is limited. I wanted the code to enter ping life, then backspace completely, repeat infinitely. I looked up on how to simulate backspace in JQuery, using escape sequence of (8), but I am not sure how to use the escape sequence, nor implement the function into the existing recursive function, for it to repeat infinitely.
Any help would be wonderful :)
Like this?
Counting like this will give a zigzag like counting pattern. I added buffers for start and end of input, and a fixed timeout for deleting letters.
textarea.text(text.substr(0, i)) selects a substring of your text (treated as an array of letters - selecting everything between index 0 and i)
Easier than appending and deleting letters
var direction = 1;
var i = 0;
var textarea = $('.term');
var text = 'ping life';
// NOTE:
// I added the "#dev:~$ " as css:before elem, easier to write the code
function count() {
i += direction;
direction *= (((i % text.length) == 0) ? -1 : 1);
textarea.text(text.substr(0, i));
clearInterval(time);
// direction is 1 if counting up
if (direction === 1) {
if (i === 0) {
// buffer for start
time = setInterval(count, 1000);
} else {
time = setInterval(count, Math.floor(Math.random() * 1000) + 50);
}
} else {
// direction is -1 if counting down
if (i === text.length) {
time = setInterval(count, 1500);
} else {
// buffer for end
time = setInterval(count, 100);
}
}
}
// inital interval
// setTimeout doesn't work well here
var time = setInterval(count, 1000)
html,
body {
margin: 0 auto;
height: 100%;
}
pre {
padding: 0;
margin: 0;
}
pre::before {
content: "#dev:~$ ";
color: white;
}
.load {
margin: 0 auto;
min-height: 100%;
width: 100%;
background: black;
}
.term {
font-family: monospace;
color: #fff;
opacity: 0.8;
font-size: 2em;
overflow-y: auto;
overflow-x: hidden;
padding-top: 10px;
padding-left: 20px;
}
.term:after {
content: "_";
opacity: 1;
animation: cursor 1s infinite;
}
#keyframes cursor {
0% {
opacity: 0;
}
40% {
opacity: 0;
}
50% {
opacity: 1;
}
90% {
opacity: 1;
}
100% {
opacity: 0;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="load">
<pre class="term"></pre>
</div>

Javascript performe action after animation end

I want to change the text after the animation is done but I have a hard time to find something that works. I have tried timers but that dont realy work beacuse the animation time is different every time (will add that later but now it is same every time).
$(document).ready(function () {
$("button").click(function () {
var r = Math.floor(Math.random() * 2) + 1
var moveTime;
if (r == '1') {
moveTime = 5000;
} else if (r == '2') {
moveTime = 4900;
}
var slowDown = 1000;
var $div = $('div').css('left', 0);
while (moveTime > 0) {
slowDown--;
$div.animate({
left: moveTime + "px"
}, 3000);
if (slowDown > 0) {
slowDown--;
moveTime = 0;
}
slowDown--;
moveTime--;
}
document.getElementById("timer").innerHTML = r;
});
});
div {
position: absolute;
float: left;
margin: 200px 0 0 -8400px;
width: 10000px;
height: 125px;
background: repeating-linear-gradient(90deg, #DF0000, #DF0000 125px, #000000 125px, #000000 250px)
}
h1 {
text-align: center;
margin: 130px 0 0 0;
font-size: 90px;
}
body {
overflow: hidden;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Start Animation</button>
<div></div>
<h1 id="timer">|</h1>
</body>
You can use the promise() method to map your animations to an array of promises, then use Promise.all() to do something when all have resolved:
var promisesArr = [];
while (moveTime > 0) {
// ...
promisesArr.push($div.animate({
left: moveTime + "px"
}, 3000).promise());
// ...
}
Promise.all(promisesArr).then(function() {
var r = Math.floor(Math.random() * 2) + 1
document.getElementById("timer").innerHTML = r;
});
See Fiddle
see official api for animate
you should be able to just call $(elem).animate().animate() and the second animate will only start when the first ends...
additionally, animate function takes a 'easing' parameter, something like "easein" will probably do what you want without needing to keep track of time at all.

change background-image of div with animation

I would like to create a little slider to change background-image of my div every seconds.
My code doesn't work for the moment, image is not changed. And ideally, i would like that the script run in infinite mode..
HTML
<div id="slidesPartenairesHome"></div>
CSS
#slidesPartenairesHome {
background-size: contain;
background-position: center center;
width: 300px;
height: 170px;
margin-left: 120px;
}
JS
$( document ).ready(function() {
var arrayOfPartenaires = [
"images/partenaires/a.png",
"images/partenaires/b.jpg",
"images/partenaires/c.jpg",
"images/partenaires/d.png",
"images/partenaires/e.png",
"images/partenaires/f.jpg",
"images/partenaires/g.jpg",
"images/partenaires/h.jpg",
"images/partenaires/i.png",
"images/partenaires/j.jpg",
"images/partenaires/k.jpg",
"images/partenaires/l.jpg"
];
for (var i=0; i<arrayOfPartenaires.length; i++) {
var currentPartenaireImg = arrayOfPartenaires[i];
$('#slidesPartenairesHome').animate({opacity: 0}, 'slow', function() {
$(this).css({'background-image': 'url("'+currentPartenaireImg+')'}).animate({opacity: 1});
});
}
});
You could use window.setinterval, you could also use setTimeout but setinterval is a litle bit more precise.
Example with setinteval:
window.setInterval(function(){
var url = getCurrent();
//start animation
$('#slidesPartenairesHome').delay( 500 ).fadeTo(500, 0.3, function()
{
$(this).css('background-image', 'url(' + url + ')');
}).fadeTo('slow', 1);
}, 1000);
// We start with index of 1 because we want to skip the first image,
// Else we would be replacing it with the same image.
var index = 1;
var arrayOfPartenaires = [
"http://yourdomain.com/images/partenaires/a.png",
"http://yourdomain.com/images/partenaires/b.png",
"http://yourdomain.com/images/partenaires/c.png"
];
function getCurrent(){
// We check if the index is higher than the ammount in the array.
// If thats true set 0 (beginning of array)
if (index > arrayOfPartenaires.length -1){
index = 0;
}
var returnValue = index;
index ++;
return arrayOfPartenaires[returnValue];
}
Note if you really want to change the image every 1 second the background will be changing very fast.
Fiddle
I hope this may help you
html
<div id="slidesPartenairesHome">
<div id="imags">
</div>
</div>
Css
#slidesPartenairesHome
{
margin-left: 120px;
}
#slidesPartenairesHome, #imags
{
background-size: contain;
background-position: center center;
width: 300px;
height: 170px;
}
Js
$(function () {
var arrayOfPartenaires = [
"http://fotos2013.cloud.noticias24.com/animales1.jpg",
"http://www.schnauzi.com/wp-content/uploads/2013/03/animales-en-primavera.jpg",
"https://johannagrandac.files.wordpress.com/2015/01/conejos.jpg",
"http://png-4.findicons.com/files/icons/1035/human_o2/128/face_smile.png",
"http://icons.iconarchive.com/icons/rokey/the-blacy/128/big-smile-icon.png",
"http://simpleicon.com/wp-content/uploads/smile-256x256.png"
];
var loaders = 0;
function cycleImages() {
var element = arrayOfPartenaires[loaders];
$("#imags").css({ 'background-image': 'url(' + element + ')' }).animate({ opacity: 1 }).hide().fadeIn("slow");
if (loaders < arrayOfPartenaires.length) {
loaders = loaders + 1;
if (loaders >= arrayOfPartenaires.length) {
loaders = 0;
}
}
else {
loaders = 0;
}
console.log(loaders, arrayOfPartenaires[loaders]);
}
cycleImages();
setInterval(function () { cycleImages() }, 3000);
});
jsFiddel Demo

How do I make a simple fade effect on an image slider with javascript(only)?

I'm using the following code to run a slider. The function runs well.
How do I make a simple fadein effect with js. No jQuery.
Also setInterval waits 5 seconds before displaying the first image. How do I start with an image and then continue with the 5 second interval?
var i = 0;
var hello = function(){
if(i<image.length)
{document.getElementById('fullscreenImage').src = image[i];
i+=1;
}
else i = 0;
}
setInterval(hello,5000);
#fullscreenImage {
z-index: -999;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background-size: cover;
}
<img id="fullscreenImage"></img>
You can do this by progressively adjusting the opacity style property of an image. Here's a simple example: declare some HTML structure, then wire the sliding behavior, using the makeSlider() function, passing an array containing the target images, as well as fading parameters.
HTML file example (whatever.html) :
<head>
<style type="text/css">
img {
position: absolute;
top: 0;
left: 0;
width: 300px;
visibility: hidden;
}
img:first-child {
visibility: visible;
}
</style>
<script type="text/javascript" src="slider.js"></script>
</head>
<body>
<img src="1.jpg" alt="Alt 1" />
<img src="2.jpg" alt="Alt 2" />
<script type="text/javascript">
var fadeInterval = 3000;
var fadeStep = 20;
setTimeout(function() {
makeSlider([document.images[0], document.images[1]], fadeInterval, fadeStep);
}, fadeInterval);
</script>
</body>
Javascript file (slider.js):
function makeSlider(pictures, fadeInterval, fadeStep) {
var currentIndex = 0;
function show() {
var nextIndex = (currentIndex + 1) % pictures.length;
var current = pictures[currentIndex];
var next = pictures[nextIndex];
fade(current, 1, -0.1, function() {
current.style.visibility = "hidden";
next.style.visibility = "visible";
fade(next, 0, +0.1, function() {
currentIndex = nextIndex;
setTimeout(function() { show(); }, fadeInterval);
});
});
}
function fade(element, origin, step, continuation) {
element.style.opacity = origin;
setTimeout(function () {
var nextOrigin = Math.round((origin + step) * 10) / 10;
if (nextOrigin >= 0 && nextOrigin <= 1) {
fade(element, nextOrigin, step, continuation);
} else {
continuation();
}
}, fadeStep);
}
show();
}
HTH.

JavaScript dymanically change CSS background style

I am trying to dynamically change my background image by continuously looping through an array of image paths. The code works if I log the output to a console, but I cannot get the image to actually change.
Original CSS: (I am overriding the default style from another CSS file)
<style>
.jumbotron {
background: #7da7d8 url('images/rotunda2.jpg') no-repeat center center !important;
}
</style>
JavaScript:
$(document).ready(function () {
var count = -1;
var images=new Array("images/image1.jpg","images/image2.jpg","images/image3.jpg");
setInterval(swap, 5000);
function swap(){
$('.jumbotron').css("background", "#7da7d8 url('"+images[++count % images.length]+"') no-repeat center center !important");
console.log(images[++count % images.length]);
}
});
Any ideas?
You're swap function seems kind of odd. Typically for something like this, you could have a counter that gets incremented and then just resets to 0 and starts over. Also make sure you are running in an onload event handler context.
var count = 0;
var images=new Array("images/image1.jpg","images/image2.jpg","images/image3.jpg");
function swap(){
//get the next image
var nextImage = images[count];
console.log(nextImage);
$('.jumbotron').css("background-image", nextImage);
//increment count
count = count > images.length - 1 ? 0 : count+=1;
}
$(document).ready(function(){
setInterval(swap, 5000);
});
aside from that, make sure to check your error console for errors, and for 404's indicating you might have bad image paths
Try this:
$(document).load(function() {
var count = -1;
var images = ['images/image1.jpg', 'images/image2.jpg', 'images/image3.jpg'];
setInterval(swap, 5000);
function swap() {
var img = images[++count % images.length];
$('.jumbotron').css('background', '#7da7d8 url(' + img + ') no-repeat center center !important');
console.log(img);
}
});
I don't think change css is a good idea, you may define some classes, and dynamically change the classes on the element!
html:
<div class="dynamicBg class1"></div>
<div class="dynamicBg class1"></div>
css:
.dynamicBg {
background-color: #7da7d8;
background-repeat: no-repeat;
background-position: center center;
}
.class1 {
background-image: url('images/image1.jpg');
}
.class2 {
background-image: url('images/rotunda2.jpg');
}
.class3 {
background-image: url('images/rotunda3.jpg');
}
.class4 {
background-image: url('images/rotunda4.jpg');
}
js:
$(function() {
var classStr = 'class1 class2 class3 class4',
classArr = classStr.split(' '), i = 0,
$dynamicBg = $('.dynamicBg');
setInterval(function() {
i = i > 3 ? 0 : i + 1;
$dynamicBg.removeClass(classStr).addClass(classArr[i]);
}, 5000);
});
Wait for the document to load:
$(document).load(function()
{
var count = -1;
var images=new Array("images/image1.jpg","images/image2.jpg","images/image3.jpg");
setInterval(swap, 5000);
function swap(){
$('.jumbotron').css("background", "#7da7d8 url("+images[++count % images.length]+") no-repeat center center !important");
console.log(images[++count % images.length]);
}
});

Categories

Resources