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.
Related
I'm changing background of a div when the user scrolls to the end of that div. Since its a fixed background, I am not using HTML <img> tag, instead I am using the CSS background-image:. With the following JavaScript function, it successfully changes the background when i need it, and reverts back when user scrolls back to top.
function transimg(divid,imgurl1,imgurl2) {
$(window).scroll(function(){
var st = $(this).scrollTop();
var dist = $(divid).offset().top - 50;
if(st > dist) {
$(divid).css("background-image", "url(" + imgurl1 +")");
}
else{
$(divid).css("background-image", "url(" + imgurl2 +")");
}
});
}
My Question is:
Obviously this loads the image when user scrolls to that offset. Which makes it slow when i host the site and a user has slow connection. So i need the 2nd image to be loaded when the page starts loading. Kind of the opposite of Lazy Load. How can i achieve this ?
I really don't want to use any plugins.
Any help is appreciated, thanks in advance !
You can load them in the before body is load. (Add the script at the end of your body).
Explanation: When you create an Image and set is the src property the image file download to your browser.
var images = ['img1', 'img2'];
for (var i = 0; i < images.length; i++) {
var img = new Image();
img.src = images[i];
}
you could add 2 background-images to the divid and so they are both loaded at page refresh and then with your JQ toggle between background-images depending on scroll.
see snippet below. let me know if it helps ( i check in Network and both images are loaded when page refresh )
$(window).scroll(function(){
var st = $(this).scrollTop();
var dist = $("#container").offset().top - 50;
if(st > dist) {
$("#container").css("background-image", "url(" + "http://i.imgur.com/AsqlqnG.jpg" +")");
}
else{
$("#container").css("background-image", "url(" + "http://i.imgur.com/I8170KA.jpg" +")");
}
});
#container {
background-image : url("http://i.imgur.com/I8170KA.jpg"),url("http://i.imgur.com/AsqlqnG.jpg");
background-size:contain;
background-repeat:no-repeat;
height:800px;
width:100%;
margin-top:50px;
position:relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id ="container">
</div>
This isn't working, can anyone help?
I am trying to build a website where the images slide to the right. I have tried the solution from a previous post but that still didnt work.
(function () {
var imgLen = document.getElementById('imgGallary');
var images = imgLen.getElementsByTagName('img');
var counter = 1;
if (counter <= images.length) {
setInterval(function () {
images[0].src = images[counter].src;
console.log(images[counter].src);
counter++;
if (counter === images.length) {
counter = 1;
}
}, 4000);
}
})();
.container{
position:relative;
width:600px;
height:330px;
border-radius:5px;
border:4px solid black;
overflow:hidden;
margin-left:320px;
}
#imgGallary > img
{
width:700px;
height:330px;
}
<div id="imgGallary" class="container">
<img src="image/lake-louise-51543_960_720.jpg" />
<img src="image/snow-in-pine-tree-1265118__340.jpg" />
<img src="image/winter-385640_960_720.jpg"/>
</div>
This should fix the issue you're having with the first image not coming in correctly. Keep the HTML and CSS the same. Change the JavaScript. Here I use window.onload, but I think your self invoking method would work, too. As for sliding it to the right, the way you have things set up is very prohibitive. I tried creating a clone and sliding the clone, but there are conflicts that make it not worth while.
If you want to slide the image, I would actually go a different route. Rather than changing the src attribute, why don't you just stack the images on top of each other using absolute positioning and z-indexes? Then you can get rid of that overflow property and just apply the border to the image, or better yet set those images as div background images (ie. background: url('lake.jpg') center center no-repeat), that way you don't even have to worry about sizing them, and they won't get distorted. In CSS, give each div a transition of "transform 0.25s" (or something to that effect). Then you can just apply a transform to them in javascript to slide them to the right. To bring them back, simply get rid of the transition value and assign a transform value of 0 to the image, but make sure the z-index is lower than the currently displayed image. If you do go the transform route, remember to add your -ms- and -webkit- prefixes to be accessible to older browsers: http://caniuse.com/#search=transform
Anyway, that's just one thought. Here's the code to fix your issue with loading the wrong image. By the way, I would consider using jQuery next time for complicated css rulings (if you decide to go my route). Good luck!
JS
window.onload = function () {
var imgLen = document.getElementById('imgGallary');
var images = imgLen.getElementsByTagName('img');
var counter = 1;
//Store the src attributes in an array
var src = [];
for (var i = 0; i < images.length; i++) {
src[i] = images[i].src;
}
console.log(src);
setInterval(function () {
if (counter < images.length) {
images[0].src = src[counter];
console.log(src[counter]);
counter++;
}
// Here we're saying if the counter is equal to the length of images, go back to the first images
// and reset the counter.
else {
images[0].src = src[0];
console.log(src[0]);
counter = 1;
}
}, 4000);
}
Once you assign a new src value to the first image tag, you can't get back the original src value of that tag.
You need to make an empty img tag withour src attribute, so that you can assign the src value to that tag.
(function () {
var imgLen = document.getElementById('imgGallary');
var images = imgLen.getElementsByTagName('img');
var counter = 1;
if (counter <= images.length) {
setInterval(function () {
images[0].src = images[counter].src;
console.log(images[counter].src);
counter++;
if (counter === images.length) {
counter = 1;
}
}, 1000);
}
})();
.container{
position:relative;
width:600px;
height:330px;
border-radius:5px;
border:4px solid black;
overflow:hidden;
margin-left:320px;
}
#imgGallary > img
{
width:700px;
height:330px;
}
<div id="imgGallary" class="container">
<img />
<img src="http://placehold.it/350?text=img1" />
<img src="http://placehold.it/350?text=img2" />
<img src="http://placehold.it/350?text=img3"/>
</div>
I want to create a website with background images that change over time with a fade in/fade out effect, but I don't want to use the existing jQuery fade in/fade out effect because with when one image faded out, a white background appeared before other image faded in. I found a plugin named Maximage that suits my request but it uses img tags while I want to work with background-image CSS (I have a good reason for doing this). Does anyone know how to do this?
Here's my HTML code:
<div id="wrapper">
//My contain here
</div>
Here's my JavaScript code so far:
//Auto change Background Image over time
$(window).load(function() {
var images = ['img/top/bg-1.jpg','img/top/bg-2.jpg','img/top/bg-3.jpg'];
var i = 0;
function changeBackground() {
$('#wrapper').fadeOut(500, function(){
$('#wrapper').css('background-image', function () {
if (i >= images.length) {
i = 0;
}
return 'url(' + images[i++] + ')';
});
$('#wrapper').fadeIn(500);
})
}
changeBackground();
setInterval(changeBackground, 3000);
});
Example: http://www.aaronvanderzwan.com/maximage/examples/basic.html
AHH ! Finally ! I found a nice technique ! I'm using a double wrapper.
The problem in your code is a bit logical. You can't fadeOut and fadeIn at the same time a single wrapper.
So the idea is to create two wrapper and to switch between them back and forth. We have one wrapper called: "wrapper_top" that encapsulate the second wrapper called: "wrapper_bottom". And the magic was to put beside the second wrapper: your content.
Thus having the structure ready which is the following:
<div id='wrapper_top'>
<div id='content'>YOUR CONTENT</div>
<div id='wrapper_bottom'></div>
</div>
Then a bit of JS+CSS and voilĂ ! It will be dynamic with any amount of images !!!
Here is the implementation: http://jsbin.com/wisofeqetu/1/
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function() {
var i =0;
var images = ['image2.png','image3.png','image1.png'];
var image = $('#slideit');
//Initial Background image setup
image.css('background-image', 'url(image1.png)');
//Change image at regular intervals
setInterval(function(){
image.fadeOut(1000, function () {
image.css('background-image', 'url(' + images [i++] +')');
image.fadeIn(1000);
});
if(i == images.length)
i = 0;
}, 5000);
});
</script>
</head>
<body>
<div id="slideit" style="width:700px;height:391px;">
</div>
</body>
</html>
If it doesn't have to be background-image, you can place all the images in your #wrapper, in <img>, it will work like a charm:
<div id="wrapper">
<img src="firstImage" class="imageClass"></img>
<img src="secoundImage" class="imageClass"></img>
<img src="thirdImage" class="imageClass"></img>
</div>
then some style. Every image has to be in same spot, so add position relative to #wrapper, and position absolute to .imageClass:
#wrapper{
position: relative;
}
.imageClass{
position: absolute;
top: 0;
left: 0;
display: none;
}
display: none; will hide every image.
Now some JQuery. To appear first image when window load write this:
$(window).load(function() {
$('.imageClass').eq(0).show();
});
by the .eq() "command" you can specify which one element with class '.imageClass' you want to use exactly. Starts with 0. After that just do something like that:
function changeBackground() {
var current = 0;
//tells which image is currently shown
if(current<$('.imageClass').length){
//loop that will show first image again after it will show the last one
$('.imageClass').eq(current).fadeOut(500);
current++;
$('.imageClass').eq(current).fadeIn(500);
} else {
$('.imageClass').eq(current).fadeOut(500);
current=0;
$('.imageClass').eq(current).fadeIn(500);
}
}
changeBackground();
setInterval(changeBackground, 3000);
});
That should work, hope you will like it.
You may also use jQuery plugin backstretch.
I have the following code for changing a divs background image with jquery, i need help to add a fade to the code so the image change with some effect
this is the code
jQuery(window).load(function(){
var images = ['blured/1.jpg','blured/2.jpg'];
var i = 0;
var timeoutVar;
function changeBackground() {
clearTimeout(timeoutVar); // just to be sure it will run only once at a time
jQuery('#maincont').css('background-image', function() {
if (i >= images.length) {
i=0;
}
return 'url(' + images[i++] + ')';
});
// call the setTimeout every time to repeat the function
timeoutVar = setTimeout(changeBackground, 6000);
}
// Call it on the first time and it will repeat
changeBackground();
});
Any help will be great!
i need to just change the background image, without fading the inside divs, this is the html
<div class="maincont" id="maincont">
<div class="containersrch">
<h1 class="lagro">some title</h1>
<div class="joinus">
<span>JOIN</span>
</div>
</div>
Maybe this is what you want?
$(function(){
var imgId = $('#maincont'), imgCount = 1, imgLast = 2;
setInterval(function(){
imgId.fadeOut('slow', function(){
if(++imgCount > imgLast)imgCount = 1;
imgId.css('background', "url('blured/"+imgCount+".jpg')");
imgId.fadeIn('slow');
});
}, 6000);
});
Now you can have multiple images, just change imgLast to the last number and make sure they have the correct URLs in your blured folder. Of course, the code above assumes you are using .jpg. I actually recommend the lossless compression of .png, but it won't matter if it's the image was taken as a .jpg.
I have some simple code to replace an image src. It is working correctly but everytime the image is updated, the browser skips right back to the top of the page.
I have several image tags in my page. All of which hidden, except for the first one. The script just iterates through them and uses the src attribute to update the first image.
Here is the code I am using:
var j = jQuery.noConflict();
var count = 1;
var img;
function update_main_image()
{
count++;
if (j('#main_image_picture_'+count).length > 0)
{
img = j('#main_image_picture_'+count).attr('src');
}
else
{
count = 1;
img = j('#main_image_picture_'+count).attr('src');
}
j(".main_image_picture_auto").fadeOut(1500, function() {
j(this).fadeIn();
j(this).attr("src", img);
});
}
j(document).ready(function()
{
setInterval(update_main_image, 6000);
});
Any ideas what might be causing it?
Any advice appreciated.
Thanks.
Try to add DIV around your IMG.main_image_picture_auto with width and height style properties setted to maximum posible image size, for example:
<div style='width:400px; height:400px; border: 0px; background: transparent; '>
<img class='main_image_picture_auto' src=''/>
</div>
<!-- Where width:400px and height:400px is maximum allowed image size -->
And I think, that is better to use setTimeout instead of setInterval
function update_main_image() {
// ....
setTimeout(update_main_image, 6000);
}
j(document).ready(function() {
setTimeout(update_main_image, 6000);
});
http://jsfiddle.net/UBEWS/