F0xcr4f7 F0xcr4f7 - 1 year ago 90
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.

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

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:

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)');
image.fadeOut(1000, function () {
image.css('background-image', 'url(' + images[i] +')');
if(i == (images.length - 1)){
i = 0;
} else {
}, 5000);

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download