Background image won't change - javascript

I want to change div's background image inside setInvterval, but can't figure out how. Here's the code:
$('.thumbnail').on({
'mouseenter': function(){
var thumbs = $(this).attr('data-num-thumbs');
var thumb_url = $(this).css('background-image');
console.log(thumb_url);
var i = 1;
setInterval(function(){
var new_thumb_url = thumb_url.replace(/\d{1,2}\.jpg/gi, i + '.jpg');
console.log(new_thumb_url);
$(this).css('background-image', new_thumb_url);
i++;
if(i > 10) i = 1;
}, 3000);
});
});
This is how div looks like:
<div data-num-thumbs="17" class="thumbnail" style="background: url('http://site/img/11.jpg') no-repeat;"></div>

It looks like $(this) inside setInterval() is mapping to something else , try this
$('.thumbnail').on({
'mouseenter': function(){
$this=$(this); //store $(this) in a local var
var thumbs = $(this).attr('data-num-thumbs');
var thumb_url = $(this).css('background-image');
console.log(thumb_url);
var i = 1;
setInterval(function(){
var new_thumb_url = thumb_url.replace(/\d{1,2}\.jpg/gi, i + '.jpg');
console.log(new_thumb_url);
//$(this).css('background-image', new_thumb_url);
$this.css('background-image', new_thumb_url);
i++;
if(i > 10) i = 1;
}, 3000);
}
});
Happy Coding:)

Related

Change Background Image in Div using JS

I have a div with an id of "imgArea" and I am trying to use JS to change the background image every 3 seconds. Below is the JS. No images are being displayed. What am I missing. Thank you.
imgArea = document.getElementById("picArea");
var images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/Garmisch-Partenkirchen.JPG/1200px-Garmisch-Partenkirchen.JPG", "https://www.reisenaktuell.com/.imaging/mte/atlas-theme/atlas-gallery/dam/hotels/eigenanreisen/v/hotel-vier-jahreszeiten-garmisch-partenkirchen/bilder/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg/jcr:content/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg", "https://www.alpenferienwohnungen.de/assets/images/a/Garmisch-Partenkirchen-08-6335188a.jpg", "http://www.garmisch-partenkirchen-info.de/header/garmisch-partenkirchen.jpg" ];
var currentImage = 0;
function changeImage() {
currentImage++;
if (currentImage > images.length - 1) {
currentImage = 0;
}
imgArea.style.backgroundImage = "url(" + images[currentImage] + ")";
}
The div and code can be seen at this codepen:
https://codepen.io/centem/pen/rdjrLy
Please use this fiddle
imgArea = document.getElementById("picArea");
var images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/Garmisch-Partenkirchen.JPG/1200px-Garmisch-Partenkirchen.JPG", "https://www.reisenaktuell.com/.imaging/mte/atlas-theme/atlas-gallery/dam/hotels/eigenanreisen/v/hotel-vier-jahreszeiten-garmisch-partenkirchen/bilder/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg/jcr:content/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg", "https://www.alpenferienwohnungen.de/assets/images/a/Garmisch-Partenkirchen-08-6335188a.jpg", "http://www.garmisch-partenkirchen-info.de/header/garmisch-partenkirchen.jpg" ];
var currentImage = 0;
function changeImage() {
currentImage++;
if (currentImage > images.length - 1) {
currentImage = 0;
}
imgArea.style.backgroundImage = "url(' "+ images[currentImage] + "')";
}
setInterval(function(){
changeImage();
}, 3000);
#picArea{
width:500px;
height:500px;
}
<div id="picArea" ></div>
<div id="imgArea" style="min-width:50px;min-height:50px;"></div>
imgArea = document.getElementById("imgArea");
var images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/Garmisch-Partenkirchen.JPG/1200px-Garmisch-Partenkirchen.JPG", "https://www.reisenaktuell.com/.imaging/mte/atlas-theme/atlas-gallery/dam/hotels/eigenanreisen/v/hotel-vier-jahreszeiten-garmisch-partenkirchen/bilder/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg/jcr:content/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg", "https://www.alpenferienwohnungen.de/assets/images/a/Garmisch-Partenkirchen-08-6335188a.jpg", "http://www.garmisch-partenkirchen-info.de/header/garmisch-partenkirchen.jpg" ];
var currentImage = 0;
function changeImage() {
currentImage++;
if (currentImage > images.length - 1) {
currentImage = 0;
}
imgArea.style.backgroundImage = "url(" + images[currentImage] + ")";
}
//call first time
changeImage();
setInterval(changeImage, 3000);
<div id="imgArea" style="min-width:500px;min-height:500px;"></div>
Firstly the selector is wrong, you selected 'picArea' while your element name is 'imgArea' and then also you are not calling the function, you only declared it.
You should call changeImage()
imgArea = document.getElementById("picArea");
var images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/Garmisch-Partenkirchen.JPG/1200px-Garmisch-Partenkirchen.JPG", "https://www.reisenaktuell.com/.imaging/mte/atlas-theme/atlas-gallery/dam/hotels/eigenanreisen/v/hotel-vier-jahreszeiten-garmisch-partenkirchen/bilder/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg/jcr:content/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg", "https://www.alpenferienwohnungen.de/assets/images/a/Garmisch-Partenkirchen-08-6335188a.jpg", "http://www.garmisch-partenkirchen-info.de/header/garmisch-partenkirchen.jpg" ];
var currentImage = 0;
function changeImage() {
currentImage++;
if (currentImage > images.length - 1) {
currentImage = 0;
}
imgArea = document.getElementById("#urid");
}

Change the background of a div with jquery easing the process

I was looking for a way to change the background of a div using jQuery and I found this question:
change background image jquery
I made it and it's working. But, there's a way to ease the process? Like an fade-in/out?
Sorry for my english. And thank you for your time.
UPDATE:
.branding{
min-height:530px;
background-image:url(../images/brandings-0.jpg);
background-repeat:no-repeat;
background-position:center;
}
var newBg = [
'site/assets/images/brandings-1.jpg',
'site/assets/images/brandings-2.jpg',
'site/assets/images/brandings-3.jpg'];
var i = 0;
var rotateBg = setInterval(function(){
i++;
if(i > 2)
i=0;
$('.branding').css({backgroundImage : 'url(' + newBg[i] + ')'});
}, 5000);
<div class="branding"></div>
Try the following fiddle I created for you.
http://jsfiddle.net/ujyjcfea/1/
var i = 0;
var newBg = [
'http://lorempixel.com/output/animals-q-c-640-480-2.jpg',
'http://lorempixel.com/output/animals-q-c-640-480-1.jpg',
'http://lorempixel.com/output/animals-q-c-640-480-4.jpg'];
var image = $('.branding');
image.css('background-image', 'url(http://lorempixel.com/output/animals-q-c-640-480-2.jpg)');
setInterval(function () {
image.fadeOut(1000, function () {
image.css('background-image', 'url(' + newBg[i++] + ')');
image.fadeIn(1000);
});
if (i == newBg.length)
i = 0;
}, 5000);
http://www.programming-free.com/2013/12/change-background-image-jquery.html
demo - http://jsfiddle.net/victor_007/RyGKV/643/
var i = 0;
var images = ['http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-5.jpg', 'http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-2.jpg', 'http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-1.jpg'];
var image = $('#slideit');
image.css('background-image', 'url(http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-5.jpg)'); //Initial Background image setup
setInterval(function () {
image.fadeOut(1000, function () {
image.css('background-image', 'url(' + images[i++] + ')');
image.fadeIn(1000);
});
if (i == images.length) i = 0;
}, 5000);

8 image change on mouse hover and return to default when left

i have an 8 img elements in my page -
<img onmouseover="mousehover(this)" onmouseout="defaultImg(this)" src = "images/1_1.jpg" height="96" width="156" style="margin-right:12px;"/>
<img onmouseover="mousehover(this)" onmouseout="defaultImg(this)" src = "images/2_1.jpg" height="96" width="156" style="margin-right:12px;"/>
On hover it should change from 1_1 to 1_2 till 1_8 and then 1_1 again. On mouse out it should show the default pic i.e 1_1. Like this i have 2_1, 3_1 till 8_1.
The javascript function for mousehover is -
function mousehover(x){
for(var i=2; i<9; i++){
x.src = x.src.replace('images/rotator/1_' + i + '.jpg');
}
}
function defaultImg(x){
x.src = x.src.replace("images/rotator/1_1.jpg");
}
Somehow this mouse hover func does not work. And how do i get the defaultImg for all the images on mouse out. I am stuck here. Any ideas?
Try the following.Should work:
var timer;
var i=2;
function mousehover(x){
x.src = 'images/rotator/1_' + i + '.jpg';
i++;
timer = setTimeout(function(){mousehover(x)},2000);
}
function defaultImg(x){
i=2;
clearTimeout(timer);
x.src = "images/rotator/1_1.jpg";
}
You can pass the first number as parameter in the function calls.
<img onmouseover="mousehover(this, 1)" onmouseout="defaultImg(this, 1)" src = "images/1_1.jpg" height="96" width="156" style="margin-right:12px;"/>
<img onmouseover="mousehover(this, 2)" onmouseout="defaultImg(this, 2)" src = "images/2_1.jpg" height="96" width="156" style="margin-right:12px;"/>
And the JavaScript would be:
var interval;
function mousehover(x, y) {
var i = 1;
interval = setInterval(function() {
i++;
if (i > 8) {
clearInterval(interval);
i = 1;
}
x.src = 'images/rotator/' + y + '_' + i + '.jpg';
}, 500);
}
function defaultImg(x, y) {
clearInterval(interval);
x.src = 'images/rotator/' + y + '_1.jpg';
}
For more performance, I would combine all images into one big sprite, and play with the background-position instead of loading a new image each time.
Something in these lines should work:
var element = document.querySelector("#switch");
element.addEventListener('mouseover', function() {
this.src = "http://placehold.it/400x300";
});
element.addEventListener('mouseout', function() {
this.src = "http://placehold.it/200x300";
});
Fiddle
You need something like this:
//TIP: Insert listeners with javascript, NOT html
x.addEventListener('mouseover', function () {
var count = 1,
that = this,
timer;
timer = setInterval(function () {
if (count < 8) {
count++;
} else {
count = 1;
}
that.src = 'images/rotator/1_' + count + '.jpg';
}, 500);
function onMouseOut() {
that.src = 'images/rotator/1_1.jpg';
that.removeEventListener('mouseout', onMouseOut)
}
this.addEventListener('mouseout', onMouseOut);
});

Slideshow - make a jQuery Plugin from working code fails

I've created a little slideshow with images out of a folder with jQuery and with help from stackoverflow and other snippets.
Images are named 1.jpg, 2.jpg ... 1-b.jpg, 2-b.jpg...The special thing is, that every image-change 3 images are loaded. The first time the images in the HTML (3 images too) are replaced.
2 of the 3 new images are blurred, to have a fade from current to - blurred current - into blurred next - next. Works fine and looks really great.
Now I want to make a real jQuery plugin out of that, because I want to change the startup (image Nr.) and imageLast (here go back to startup) on every site. Well I don't know if there are problems with the logic of the original code to make a plugin. My trials failed. Please have a look.
Original working code:
// slideshow ----------------------------------------------------------------------------
(function() {
var pauseTime = 7000;
function slideShow(index) {
var imagePath = "slider-team";
var startup = 1;
var startindex = index+startup-1;
var index1 = startindex+1;
var lastImage = 6;
var fadeTime = 700;
var fadeTime2 = 500;
var fadeTime3 = 1000;
var theImage1 = new Image();
var theImage2 = new Image();
var theImage3 = new Image();
var url = imagePath + "/" + startindex + ".jpg";
var urlb = imagePath + "/" + startindex + "-b.jpg";
var url2b = imagePath + "/" + index1 + "-b.jpg";
$(theImage1, theImage2, theImage3).load(function () {
$(theImage1).prependTo("#slider");
$(theImage2).prependTo("#slider");
$(theImage3).prependTo("#slider");
$("#slider img:last").fadeOut(fadeTime, function() {
$(this).remove();
$("#slider img:last").fadeOut(fadeTime2, function() {
$(this).remove();
$("#slider img:last").fadeOut(fadeTime3, function() {
$(this).remove();
setTimeout(function() {
slideShow((index % (lastImage-startup)) + 1)
}, pauseTime);
});
});
});
});
theImage1.src = url;
theImage2.src = urlb;
if(startup+index === lastImage) {
theImage3.src = "slider/" + startup + "-b.jpg";
} else {
theImage3.src = url2b;
};
}
$(document).ready(function() {
// Img 1 is already showing, so we call 2
setTimeout(function() { slideShow(2); }, pauseTime);
});
})();
Trial to make a plugin:
// slideshow ----------------------------------------------------------------------------
(function($) {
$.blurSlider = function(index, settings){
var config = {
'startup':1;
'lastImage':17;
};
if(settings){$.extend(config, settings);}
var pauseTime = 7000;
//function slideShow(index) {
var imagePath = "slider-opt";
//var startup = 1;
var startindex = index+startup-1;
var index1 = startindex+1;
//var lastImage = 17;
var fadeTime = 700;
var fadeTime2 = 500;
var fadeTime3 = 1000;
var theImage1 = new Image();
var theImage2 = new Image();
var theImage3 = new Image();
var url = imagePath + "/" + startindex + ".jpg";
var urlb = imagePath + "/" + startindex + "-b.jpg";
var url2b = imagePath + "/" + index1 + "-b.jpg";
$(theImage1, theImage2, theImage3).load(function () {
$(theImage1).prependTo("#slider");
$(theImage2).prependTo("#slider");
$(theImage3).prependTo("#slider");
$("#slider img:last").fadeOut(fadeTime, function() {
$(this).remove();
$("#slider img:last").fadeOut(fadeTime2, function() {
$(this).remove();
$("#slider img:last").fadeOut(fadeTime3, function() {
$(this).remove();
setTimeout(function() {
slideShow((index % (config.lastImage-config.startup)) + 1)
}, pauseTime);
});
});
});
});
theImage1.src = url;
theImage2.src = urlb;
if(config.startup+index === config.lastImage) {
theImage3.src = "slider/" + config.startup + "-b.jpg";
} else {
theImage3.src = url2b;
};
// }
};
return this;
$(document).ready(function() {
// Img 1 is already showing, so we call 2
setTimeout(function() { $.blurSlider(2); }, pauseTime);
});
})(jQuery);
I don't know if in plugins you need to set up the selector. Here I don't, because the selector didn't change. The call of document.ready inside the plugin is the other thing that might cause problems.

Jquery - Animate innerHTML possible?

I'm trying to have a function that does setTimeout, then changes the innerHTML:
<script type="text/javascript">
$(document).ready(function(){
setTimeout(function(){
document.getElementById("middlecolor").innerHTML='new text new text';
}, 1000);
});
</script>
Question: How could I animate the new text that appears, i.e. line by line as opposed to being written all at once?
Thanks for any suggestions!!
Try something like this:
<div id="text">
</div>
$(document).ready(function () {
var interval = setInterval(function () {
$('#text').append('<p style="display: none;">new text</p>');
$('#text p:last').fadeIn('slow');
}, 5000);
});
See the example here
If you want to kill the interval, can be doing this:
clearInterval(interval);
Greatings.
Line-by-line is a bit tricky, but possible.
var ps = document.getElementById("text").children;
var i = 0;
var $p = $(ps[i]);
setTimeout(function newline(){
$p.css("height", function(index, h){
h = parseInt(h);
h += parseInt($p.css("line-height"));
console.log(h, ps[i].scrollHeight);
if (h > ps[i].scrollHeight)
$p = $(ps[++i]);
return h;
});
if (i < ps.length)
setTimeout(newline, 200);
}, 200);​
I'd suggest to use a typewriter effect, which is also very likable: http://jsfiddle.net/pZb8W/1/
var ps = document.getElementById("text").children;
var i = 0;
var $p, text;
var speed = 20;
setTimeout(function newchar(){
if (!text) {
$p = $(ps[i++]);
text = $p.text();
$p.empty().show();
}
$p.append(document.createTextNode(text.charAt(0)));
text = text.slice(1);
if (text.length || i < ps.length)
setTimeout(newchar, Math.random()*speed+speed);
}, 3*speed);​
Here's a function that would animate in multiple lines of text, one after the other:
<script type="text/javascript">
$(document).ready(function(){
function animateAddText(id, text, delta) {
var lines = text.split("\n");
var lineCntr = 0;
var target = $("#" + id);
function addLine() {
if (lineCntr < lines.length) {
var nextLine = "";
if (lineCntr != 0) {
nextLine = "<br>";
}
nextLine += lines[lineCntr++];
$("<span>" + nextLine + "</span>").hide().appendTo(target).fadeIn(1000);
setTimeout(addLine, delta);
}
}
addLine();
}
var multilineText = "First line\nSecond Line\nThird Line\nFourth Line\nFifth Line";
animateAddText("middlecolor", multilineText, 1000);
});
</script>
And a working demo: http://jsfiddle.net/jfriend00/Gcg5T/

Categories

Resources