F0xcr4f7 F0xcr4f7 - 2 days ago 5
Javascript Question

JQuery Navbar Background-image shuffling issues

I wanted my Navbar's background-image to shuffle through different images set on a timer. I got it to shuffle but the menu and my logo disappear when the image fades away and comes back when the next image shows up. Another issue I have is that the image doesnt fade into a new image but it goes blank then shows the next image.

Issues:
1) Menu and Logo fade along with background-image.
2) Background-image goes blank when changing to next image.

Tried:
1) I tried using .not on my var element but no joy. I created a class called .ignore for my Logo and Menu.
2) Not sure how to solve this as I am new to JQuery.

JQuery Code:

$(function(){
var i =0;
var images = ['assets/img/storm-ocean-hurricane-florida-beach-coast-travel.jpg','assets/img/arctic_sunset.jpg','assets/img/fallflood.jpg','assets/img/landscape-with-fog-and-chimney-smoke-at-sunset.jpg'];
var image = $('.navbar').not('.ignore');
image.css('background-image', 'url(assets/img/storm-ocean-hurricane-florida-beach-coast-travel.jpg)');
setInterval(function(){
image.fadeOut(1000, function () {
image.css('background-image', 'url(' + images[i] +')');
image.fadeIn(1000);
});
if(i == (images.length - 1)){
i = 0;
} else {
i++;
}
}, 5000);
})


The Menu follows the user down through the site and the logo stays where it is.

Answer

I'm not seeing anything explicitly wrong with your JS, but I think you can solve all of your issues by creating a new HTML element inside your navbar that is meant to only hold the background image, and is positioned behind all other elements to not interfere with them. Markup would just be <div class="navbar__bg"></div>.

CSS for such an element would be like:

.navbar {
    position: relative; /* needed to allow your bg element to properly position */
}

.navbar__bg {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: -1;
}

And you'd change the fourth line of your jQuery to:

var image = $('.navbar__bg');

"Another issue I have is that the image doesnt fade into a new image but it goes blank then shows the next image."

As for this, your code is written to currently fade out completely, change the image, then fade in. Are you saying you want to crossfade two images to blend into one another? This would require overlapping multiple elements as they simultaneously fade in and out. A crossfade cannot be done by changing background-image on one element.

Comments