Mark Mark - 4 months ago 22
jQuery Question

Is it possible to change font color based on background slider image name using jQuery?

I am trying to change the font color of the navigation based on the color of the background image which is an image slider. I'm adding a class to the nav by looking at the end of the image name "dark.png" or "light.png" to change the font color but I don't know how to get it to change the font color every time the slider switches images.

If there is a simpler/better solution already out there please let me know. Also I realize I'm mixing pure JavaScript and jQuery in my example so if anyone has a pure jQuery solution that would be awesome.

Here is my code for a very simplified version for troubleshooting. I also did a jsfiddle example.

HTML:

<body>
<nav>
<ul>
<li>About</li>
</ul>
</nav>
</body>


CSS:

body {
background-repeat: no-repeat;
background-size:cover;
width:300px;
height:300px;
}

.dark {
color:#ffffff;
}


JavaScript:

$(document).ready(function(){

//slideshow:
$(function () {
var slideshow = $('body');
var backgrounds = [
'url(http://markpfaff.com/bk1-dark.png)',
'url(http://markpfaff.com/bk2-light.png)'];
var current = 0;

function nextBackground() {

slideshow.css(
'background-image',
backgrounds[current = ++current % backgrounds.length]);

setTimeout(nextBackground, 5000);
}

setTimeout(nextBackground, 5000);
slideshow.css('background-image', backgrounds[0]);
});

});

(function colorChange(){
var b = $('body').css('background-image');
if(b.match(/-dark.png\)$/)){
$("nav").addClass("dark");
}else if(b.match(/-light.png\)$/)){
$("nav").removeClass("dark");
}
})();

Answer

there are many options and here is one of them. Keep array of the classes with relative index of backgrounds. There is no need of extra color change function.

$(function () {
    var slideshow = $('.body');
    var backgrounds = [
        'url(http://markpfaff.com/bk1-dark.png)', 
        'url(http://markpfaff.com/bk2-light.png)'];
    var colorsClasses = ['dark','light'];
    var current = 0;

    function nextBackground() {
        slideshow.css(
            'background-image',
            backgrounds[current = ++current % backgrounds.length]
        );
        $("nav").attr("class",colorsClasses[current]);
        setTimeout(nextBackground, 5000);
    }

    setTimeout(nextBackground, 5000);
    slideshow.css('background-image', backgrounds[0]);
    slideshow.css("color",color[0]);
});
Comments