Javascript code won't crossfade - javascript

I have some Javascript code that I got from codepen.io. But I'm having a tough time executing it, although it is the same exact code. I'm just learning Javascript so I am a beginner. I didn't use HTML, I just used CSS & Javascript. The background image does shuffle through, but the fade does not work.
Here is my CSS snippet:
body {
margin: 0;
background-image: url(/image1.jpg) no-repeat center center fixed;
background-size: cover;
margin: 0;
width: 100%;
height: 100%;
transition: 1s;
}
Here is the JS that goes with it.
var bgImageArray = ["image2.jpg", "image3.jpg", "image4.jpg"],
base = "/",
secs = 4;
bgImageArray.forEach(function(img){
new Image().src = base + img;
// caches images, avoiding white flash between background replacements
});
function backgroundSequence() {
window.clearTimeout();
var k = 0;
for (i = 0; i < bgImageArray.length; i++) {
setTimeout(function(){
document.documentElement.style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center fixed";
document.documentElement.style.backgroundSize ="cover";
if ((k + 1) === bgImageArray.length) { setTimeout(function() { backgroundSequence() }, (secs * 1000))} else { k++; }
}, (secs * 1000) * i)
}
}
backgroundSequence();
Any help would be greatly appreciated!

I think the problem is that you defined the CSS rules to the body but in your JavaScript, the new images are attached to documentElement, which is equal to html tag and not to body tag.
Try changing these lines:
document.documentElement.style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center fixed";
document.documentElement.style.backgroundSize ="cover";
to this:
document.body.style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center fixed";
document.body.style.backgroundSize ="cover";
Just changed documentElement with body

You should change document.documentElement to document.body and you can remove window.clearTimeout
You can see this demo for working:
http://codepen.io/dangvanthanh/pen/NGpqYr

Related

JavaScript Background Slider to target a div ID

I am fairly new to JS and fumbling my way through it.
Does anyone know how to target a specific div ID in order to apply the crossfading background images to just that specific div?
Any help is greatly appreciated!
My HTML:
<div id="header-background-slider"></div>
My CSS:
#header-background-slider{
background-size: cover;
background: url("/image001.jpg") no-repeat center center fixed;
background-blend-mode: darken;
transition: 3s;
}
My JS:
var bgImageArray = ["image001.jpg", "image002.jpg", "image003.jpg"],
base = "/",
secs = 4;
bgImageArray.forEach(function(img){
new Image().src = base + img;
});
function backgroundSequence() {
window.clearTimeout();
var k = 0;
for (i = 0; i < bgImageArray.length; i++) {
setTimeout(function(){
document.documentElement.style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center fixed";
document.documentElement.style.backgroundSize ="cover";
if ((k + 1) === bgImageArray.length) { setTimeout(function() { backgroundSequence() }, (secs * 1000))} else { k++; }
}, (secs * 1000) * i)
}
}
backgroundSequence();
If what I think is correct, then replace document.documentElement with document.getElementById("header-background-slider"). Keep the stuff after it. :)
document.documentElement targets what is called the "root node". Since you want to target something specific, you can select it from your DOM (Document Object Model) with document.getElementById.

Change Background image url of div

i have a div for which i want to show multiple images in the background as a fade in fade out by changing the css background image am unable to find the best way.
JSFiddle
My HTML:
<div id="background"></div>
Jquery
var bgArr = ["http://malsup.github.io/images/p1.jpg", "http://malsup.github.io/images/p1.jpg", "images/TopImage-03.jpg"];
var i = 0;
// Start the slide show
var interval = self.setInterval("swapBkgnd()", 5000)
function swapBkgnd() {
if (i > (bgArr.length - 1)) {
i = 0
$("#background").css("background-image", "url(" + bgArr[i] + ")");
} else {
$("#background").css("background-image", "url(" + bgArr[i] + ")");
}
i++;
};
CSS:
#background {
position: absolute;
min-height: 100%;
width: 100%;
height: auto;
top: 0;
left: 0;
background: url(http://2.bp.blogspot.com/-ayEwJpMGTPQ/USqliwPWo1I/AAAAAAAAHtI/ab6NHVy0Q48/s1600/tree.jpg) no-repeat center center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Use:
Jsfiddle: http://jsfiddle.net/ook3ah4p/
var interval = self.setInterval(swapBkgnd, 5000) // true syntax
instead of:
var interval = self.setInterval("swapBkgnd()", 5000) // wrong syntax
for animation:
$('#background')
.animate({opacity: 0}, 'slow', function() {
$(this)
.css({'background-image': "url(" + bgArr[i] + ")"})
.animate({opacity: 1});
});
Set it up like this:
function swapBkgnd() {
if (i > (bgArr.length - 1)) {
i = 0;
}
$("#background").fadeOut("slow", function () {
$(this).css("background-image", "url(" + bgArr[i] + ")");
$(this).fadeIn("slow");
});
i++;
};
Refering to this answer How to fade changing background image
var interval = self.setInterval(swapBkgnd, 5000)
function swapBkgnd() {
if (i > (bgArr.length - 1)) {
i = 0
$('#background').fadeTo('slow', 0.3, function(){
$(this).css('background-image', 'url(' + bgArr[i] + ')');
}).fadeTo('slow', 1);
} else {
$('#background').fadeTo('slow', 0.3, function(){
$(this).css('background-image', 'url(' + bgArr[i] + ')');
}).fadeTo('slow', 1);
}
i++;
};

setAttribute background-image can't be changed. Stuck at default value

function showHome() {
removeSlideShow();
var homeHeader = document.createElement("div");
homeHeader.setAttribute("id", "homeHeader");
document.getElementById("window").insertBefore(homeHeader, document.getElementById("content"));
var slideShowDiv = document.createElement("div");
var images = ["slideShow/slideShow-1.jpg", "slideShow/slideShow-2.jpg", "slideShow/slideShow-3.jpg", "slideShow/slideShow-4.jpg", "slideShow/slideShow-5.jpg", "slideShow/slideShow-6.jpg", "slideShow/slideShow-7.jpg"];
homeHeader.appendChild(slideShowDiv);
startSlideShow(slideShowDiv, images);
content.innerHTML = "";
}
function startSlideShow(element, images) {
var iterator = 0;
element.setAttribute("id", "slideShowDiv");
element.setAttribute("style", "background-image: url(" + images[0] + ")");
var startInterval = setInterval(function() {
iterator++;
if (iterator == images.length) iterator = 0;
element.setAttribute("style", "background-image: url(" + images[iterator] + ")");
element.style = "background-image: url(" + images[iterator] + ")";
transition(element);
}, 3000);
}
function removeSlideShow() {
if (document.getElementById("homeHeader")) {
document.getElementById("window").removeChild(document.getElementById("homeHeader"));
}
}
function transition(element) {
element.setAttribute("style", "opacity:0.01;");
var i = 0;
var set = setInterval(function() {
i += 0.01;
element.setAttribute("style", "opacity:" + i + ";");
}, 4);
setTimeout(function() {
clearInterval(set);
element.setAttribute("style", "opacity:1;");
}, 500);
}
div#homeHeader {
background-color: #FFF;
width: 900px;
height: 280px;
border: solid 2px #F00;
border-radius: 20px;
}
div#slideShowDiv {
background-image: url(slideShow/slideShow-1.jpg);
background-color: #FFF;
width: 898px;
height: 278px;
border: solid 1px #FFF;
border-radius: 20px;
background-size: 100% 100%;
}
What i want to do is change the background image every 3 seconds. The code work but it's not changing the image, stays at 'slideShow-1.jpg'. If i remove the transition(element); part, the image rotate just fine. What should i do to get it work? Im still beginner in Javascript, will learn jquery when i got better. Sorry for my grammar.
If i remove the transition(element); part, the image rotate just fine.
The transition part sets a new value for the style attribute.
Setting a new value for the attribute replaces the old value.
You are removing the style for the background image. (So the one from the stylesheet is applied again instead).
What should i do to get it work?
Don't use setAttribute(..., ...) to modify styles.
Use .style.cssPropertyName = ... instead.

jQuery Image Slices

I've an image slider, in which I want to slice the image to create some kind of 3D-Effekt. I created the slider, but now I'm struggling with the responsive behavior of the slider.
In px values, everything is working finde, but I want the slider to be responsive.
Could somebody look at my code and give me a solution to solve the problem?
Here is my code:
The SCSS:
/*Variables & Helper*/
*{
box-sizing: border-box;
}
%clearfix {
&:after {
content: "";
display: table;
clear: both;
}
}
body, html{
margin: 0;
padding: 0;
background: url('../img/bg.png');
}
img{
max-width: 100%;
height: auto;
}
.article{
width: 80%;
margin: 2rem auto;
background: #fff;
#extend %clearfix;
padding: .8rem;
}
.img__container {
float: left;
width: 100%;
margin: 0;
}
.slice{
float: left;
}
And here is the JavaScript:
$(function(){
$( window ).on('resize',function() {
calcDimensions();
bgPosition();
});
/*Variables*/
var $imgContainer = $('.img__container'),
$img = $imgContainer.children('img'),
slices = 5,
percentage = 100 / slices + '%',
imgWidth = $imgContainer.width(),
imgHeight = $imgContainer.height();
/**/
sliceImg();
/*Functions*/
function calcDimensions(){
imgWidth = $imgContainer.width();
imgHeight = $imgContainer.height();
};
function bgPosition(){
for (var i = 0; i < slices; i++){
$('#slice' + i).css({
'background-position' : - ( (imgWidth / slices) * i ) + 'px 0%',
});
};
}
function sliceImg(){
var imgLink = $img.attr('src');
/* Delete the image */
$img.remove();
/*Loop*/
/*Create new divs*/
for (var i = 0; i < slices; i++){
var newDiv = $('<div></div>').addClass('slice').attr('id', 'slice' + i);
$imgContainer.append(newDiv);
};
/**/
bgPosition();
$('.slice').css({
'background-image' : 'url(' + imgLink + ')',
'width' : percentage,
'height' : imgHeight ,
'background-size' : 'cover',
});
};
});
So, if i resize the window, it's kind of responsive. But not as great as a real responsive experience.
I also tried something like that, which should be the right mathematic operation. But in jQuery i can't do mathematic operations with %, or am I wrong? Because I'm always getting errors....
$('.slice').css({
'background-image' : 'url(' + imgLink + ')',
'width' : (imgWidth / slices / 100 * 1%) ,
'height' : imgHeight ,
'background-size' : 'cover',
});
I'm looking forward to get a solution.
Thanks!
Best regards,
You said you used 'px', so I think everything will go well if you use 'em' instead of 'px'. And correct me If I am wrong, but I think you might want to use Dootstrap for responsive design.

Image overlapping a span in another li element

EDIT: I have created a JS-Fiddle that shows you the code in action and you can see how the caption's text is being overlapped. https://jsfiddle.net/wj76sv1h/
So I have a list of divs that display images obtained from a Database. This list is created by PHP, but when I have attempted to add a caption, as you can see from the image (sorry I can't include the image directly in the post), it is being overlapped by another Li element's image. The caption is a span tag.
I have attempted to change the z-index of the images and the divs, however it seems like it has no effect. I am also using this code in order to create the grid system using the lis.
function createListStyles(rulePattern, rows, cols) {
var rules = [], index = 0;
for (var rowIndex = 0; rowIndex < rows; rowIndex++) {
for (var colIndex = 0; colIndex < cols; colIndex++) {
var x = (colIndex * 100) + "%",
y = (rowIndex * 100) + "%",
transforms = "{ -webkit-transform: translate3d(" + x + ", " + y + ", 0); transform: translate3d(" + x + ", " + y + ", 0); }";
rules.push(rulePattern.replace("{0}", ++index) + transforms);
}
}
var headElem = document.getElementsByTagName("head")[0],
styleElem = $("<style>").attr("type", "text/css").appendTo(headElem)[0];
if (styleElem.styleSheet) {
styleElem.styleSheet.cssText = rules.join("\n");
} else {
styleElem.textContent = rules.join("\n");
}
}
If anyone could help me, that would be great. Thanks. This is the html used for the item/caption.
<div class="item" id="item-covert"><span>Caption</span> <div id="item-price"> $54.36</div><img class="item-image" src="image.url"></div>
Css:
.item {
position: relative
}
.item span {
display: none;
position: absolute;
bottom: 0;
padding: 10px;
background: rgba(255,255,255,0.99);
/*top: 20px;
width: 300px;
height: 50px;*/
font-family: Open Sans;
/*margin-left: 110px;*/
left: 110px;
}
.item:hover span {
display: block
}
Your positioning of the span moves it onto the image. Move it ten pixels farther to the right, and it looks fine. https://jsfiddle.net/yak613/5p3uuzfg/
I've taken some liberties with the caption text :)
And some suggestions for cool caption colors :)
Live Example

Categories