Change Background Image Multiple Times JS - javascript

Everytime I click on body the background-image should change and repeat when the images are over. I tried this but doesn't work:
HTML
<body id="change-image">
</body>
JS
var images = ['../img/1.jpg', '../img/2.jpg', '../img/3.jpg', '../img/4.jpg'],
i = 0;
$("#change-image").click(function(){
$("body").css("background-image", images[i]);
i = (i==images.length-1) ? 0 : (i+1);
});
I think that code should work, but it doesn't. I tried with backgroudColor and it works perfectly, but with images is not happening. I would love if u help me please!

At some point you'll be increasing the counter out of the available number of background images so... (also by using properly url() like background-image:"url(image.jpg)")
do like:
var images = [
'http://placehold.it/500x320/07f',
'http://placehold.it/500x320/f70',
'http://placehold.it/500x320/7f0',
'http://placehold.it/500x320/0f7'
],
i = 0,
n = images.length;
$("#change-image").click(function(){
$("body").css({backgroundImage: "url("+ images[i++ % n] +")" });
});
html, body{height:100%;}
body{
background: red none 50% / cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="change-image">CHANGE</button>
The i++ % n will increment and loop-back your counter

You should use this
$("body").css("background-image", "url:('" + images[i] + "')");

background-image needs url like this:
$("#change-image").click(function(){
$("body").css("background-image", "url("+ images[i]+")");
i = (i==images.length-1) ? 0 : (i+1);
});

Related

Why aren't my images being updated as expected?

was trying to follow a guide that seemed to me very straightforward and simple that i found here:
Change css background-Image using javascript
however in my implementation it doesn't work. the image does not get displayed or changed. any hints?
EDIT: not the same as suggested duplicate. now that parenthesis after changeImage has been removed, the function gets repeated but the problem of not displaying any of the background images persists.
2ND EDIT: i also tried removing the parenthesis after buildImage, with the same result (no background images displayed)
<div id="pupa">
</div>
<script>
var images = ['file:///Users/karin/PROJECTS/PORTFOLIO/pupal%20stage/img/stage12.jpg',
'file:///Users/karin/PROJECTS/PORTFOLIO/pupal%20stage/img/stage34.jpg',
'file:///Users/karin/PROJECTS/PORTFOLIO/pupal%20stage/img/stage56.jpg'];
var index = 0;
function buildImage() {
console.log("setting image");
document.getElementById('pupa').style.backgroundImage = 'url(' + images[index] + ')';
}
function changeImage() {
index++;
if (index >= images.length) index = 0;
console.log("changing image");
document.getElementById('pupa').style.backgroundImage = 'url(' + images[index] + ')';
}
buildImage();
setInterval(changeImage, 3000);
</script>
This code will work if you add your images in a folder called img in the same folder where the html page is.
<html>
<head>
<style>
#pupa
{
width:300px;
height:300px;
background-position:center;
background-repeat:no-repeat;
background-size:cover;
}
</style>
</head>
<body>
<div id="pupa"></div>
<script>
var images = ['img/stage12.jpg',
'img/stage34.jpg',
'img/stage56.jpg'];
var index = 0;
document.getElementById('pupa').style.backgroundImage = `url(${images[index]})`;
setInterval(function(){
index=(++index >= images.length)?0:index;
console.log(`changing image of index : ${index}`);
document.getElementById('pupa').style.backgroundImage = `url(${images[index]})`;
},3000);
</script>
</body>
</html>
This is the same code tweaked a bit, and you don't need another function buildImage() to set image first, it works (make sure to check path of images)
Make sure to change width, height, background-size, image name, path etc according to your need.

Smooth Sliding background image

I am having a PhP page where i would like to set the background image as follows.
body id="indexbody" background="<?php echo base_url(); ?>images/Images03.png"
style="background-repeat:no-repeat;background-size:cover;position: relative;
background-size:100% 100vh;"
Now, this shows the background image well. I want the background image to smoothly keep fading in and out one after the other.
<script>
window.onload = function() {
var images = [
"http://images/Images01.png",
"http://images/Images02.png",
"http://images/Images03.png"
]
var imageHead = document.getElementById("indexbody");
var i = 0;
$('#indexbody').fadeTo('slow', 0.3, function()
{
$(this).css('background-image', 'url(' + images[i] + ')');
i = i + 1;
if (i == images.length) {
i = 0;
}
}).delay(1000).fadeTo('slow', 1);
</script>
This is not working. Can anyone suggest how to accomplish this. Either fadein fadeout or left to right sliding
mind using plugin?
this plugin worked for me

Animate background image javascript not working

I want to achieve a background animate image, that moves from right to left, but the image won´t animate, could you help me verify my code?
<body>
<div id="background-container"></div>
<script> type="text/javascipt">
function animateBackground(elem, speed) {
var x = 0 ;
var y = -50;
elem.style.backgroundPosition = x + 'px' + ' ' + y + 'px';
var timer = setInterval (function(speed) {
elem.style.backgroundPosition = x + 'px' + ' ' + y + 'px';
x--;
if (x == -600) {
clearInterval(timer);
}
},speed)
}
document.addEventListener("DOMContentLoaded", animateBackground(document.getElementById('background-container'), 15), false);
</script>
</body>
Your code is quite ugly but actually it looks fine. What is definitely wrong is how you are adding the event handler. Instead of adding a handler function, you call your handler function inline, so it actually doesn't add any listener. You should pass the function itself, for example like this, using an anonymous function inline.
document.addEventListener("DOMContentLoaded", function() { animateBackground(document.getElementById('background-container'), 15); }, false);
You could have provided a jsfiddle link, which would have made it easy. By the way here is the working jsfiddle, https://jsfiddle.net/pmankar/4o88z0tt/
I added a css background to the div tag using
div{
background-image: url("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png");
height: 100px;
width: 600px;
border: 2px solid green;
}
Rest assured, I didn't do any changes to your js code or the html code. It worked fine for me.

Image rotate background js jumps to top of the page

I have a problem with javascript that I don't know how to solve. First of all I am a total newb in this. I found a code that loads random images in div element and tweaked it a little bit (original code loaded images in order - I inserted a type of algorithm for randomness (pretty clumsy but it somehow works and rarely repeats the same image one after another).
Now the code works just fine, but when I scroll for e.g. to the bottom of my page the instant moment that script loads a new image into div element browser jumps to the top of the page.
How to stop this from happening? Please help me with a 'child language'(because as I told, I'm a total newb in js).
Thank you all in advance for your time!
<script src="js_vrt/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function() {
var images = ['img_vrt/pozadine/1p.jpg', 'img_vrt/pozadine/2p.jpg', 'img_vrt/pozadine/3p.jpg', 'img_vrt/pozadine/4p.jpg'];
var image = $('#pozad');
var i = Math.floor((Math.random() * images.length) + 0);
var ist;
//Initial Background image setup
image.css('background-image', 'url(' + images[i++] + ')');
//Change image at regular intervals
setInterval(function() {
image.fadeOut(1500, function() {
image.css('background-image', 'url(' + images[i++] + ')');
image.fadeIn(1500);
});
if (i == images.length)
i = Math.floor((Math.random() * (images.length - 1)) + 0);
else i = Math.floor((Math.random() * (images.length)) + 0);
}, 5000);
});
</script>
Solution I figured out:
Problem is not in the js code. It is in HTML structure.
If someone has the same problem where screen jumps to top of the page while loading images do the following:
The div element that has the changing background MUST be contained in another wrapping div (which has the same height).
<div id="wrap_element">
<div id="div_that_loads_the_images"></div>
</div>

How to increment jQuery variable?

I'm trying to browse through a picture gallery with jquery, so I have a button which is supposed to increment a variable by 1 and then use that to load the next picture.
Using the top answer on this SO question, I thought this would be the solution:
<div id="pic"></div>
<div id="browse-right">NEXT</div>
<%= image_tag("/1.JPG", id:"1") %>
<%= image_tag("/2.JPG", id:"2") %>
<%= image_tag("/3.JPG", id:"3") %>
$("#1").click(function() {
var x = 1;
$("#pic").html('<img src="/' + x + '.JPG" />');
});
$("#2").click(function() {
var x = 2;
$("#pic").html('<img src="/' + x + '.JPG" />');
});
$("#3").click(function() {
var x = 3;
$("#pic").html('<img src="/' + x + '.JPG" />');
});
//...
$("#browse-right").click(function() {
x = x + 1;
$("#pic").html('<img src="/' + x + '.JPG" />');
});
But it just reloads the same picture, which means var x doesn't change. Anyone know the proper syntax?
UPDATE: Okay, I think I've figured out the problem. x is set when a picture is clicked on, and apparently it isn't persisting after the function is complete. I didn't include that part in the original code because I thought it would make the whole thing more complicated to read.....lesson learned. How can I get x to persist after the function it is set in?
How can I get x to persist after the function it is set in?
Try defining x outside of and before click handler
var x = 1;
$("body").on("click", function() {
x = x + 1;
$(this).html(x)
})
body {
width: 300px;
height: 300px;
border: 1px solid purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
click
Your code looks ok. and here's a working version https://jsfiddle.net/a50nz178/1/
A couple of things you could check:
check that the image is actually there /1.JPGas well
check that images are not all named as jpg all lower case?
If I had to guess, looking at your previous You've updated. Turns out I was right. Your x was out of scope. correct code, I'd bet your problem is scope. Scope Tutorial
I'm willing to bet, somewhere else in your code your using something like for(x in ; ... Which is reassigning x. If that's not the case, I'd still bet on either scope, or the image is src isn't correct. You should use your developer console to check if a bad image source is being pulled. Your using / at the begining of your img src which will go back to base path. If you images are in an images folder you need to include the proper directory path.
You could easily shorten the scope of this by attaching your increment variable to your element object like so:
$("#browse-right").click(function(e) {
// the following is a simple inline `if` statement
// what it says is (this is your element)
// if this.i does not exist, create it equal to one,
// else count it up once
!this['i'] ? this.i=1: this.i++;
$("#pic").html('<img src="/' + this.i + '.JPG" />');
// the following simply shows what `i` currently is
$('h3').text(this.i);
});
p { cursor: pointer; background: #aabb00; padding: 1em .5em; text-align: center; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p id="browse-right">Browse Right</p>
<h3></h3>
<div id="pic">
IMG HERE
</div>

Categories

Resources