Julia
Julia

Reputation: 1399

Jquery: Link text color to random background image

I'm using jQuery to randomly assign a background-image to my webpage every time the window is refreshed. I would like to assign a corresponding text-color to each background.

I'm trying with this code but having no luck:

$(document).ready(function () {
    var images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg'];

    $('body').css({
        'background-image': 'url(img/' + images[Math.floor(Math.random() * images.length)] + ')'
    });

    if ($('body').css('background-image') === 'img/5.jpg') {
        $('#intro').css('color', 'red!important');
    };
});

Upvotes: 1

Views: 372

Answers (4)

Barmar
Barmar

Reputation: 781848

Here's how I would do it:

var styles = [
    { image: '1.jpg', color: 'blue' },
    { image: '2.jpg', color: 'green' },
    ...
];

var style = styles[Math.floor(Math.random() * styles.length)];
$(body).css{ 'background-image': 'url(img/' + style.image + ')',
             'color': style.color + '!important' });

However, the basic problem with your code is that you're forgot url(...) when you compared to the existing style, it should be:

if ($('body').css('background-image') === 'url(img/5.jpg)') {

Upvotes: 0

Aguardientico
Aguardientico

Reputation: 7779

try putting console.log($('body').css('background-image')) to see what is returning this. I think that is returning something like url(img/5.jpg) instead of img/5.jpg

also probably is easier if set the random thing into a variable and then do the compare with that variable instead of css attribute

Upvotes: 0

Blender
Blender

Reputation: 298392

.css('background-image') returns an image URL wrapped with url(). I would use an array of objects instead:

var themes = [{
    image: '1.jpg',
    color: 'red'
}, {
    image: '2.jpg',
    color: 'orange'
}];

Now, you can do:

var theme = themes[Math.floor(Math.random() * themes.length)];

$('body').css({
    'background-image': 'url("img/' + theme.image + '")',
    'color': theme.color
});

Upvotes: 2

Ian Clark
Ian Clark

Reputation: 9347

Why not update your images array so that each element is actually an array of `background/text-color' - like this:

var images = [['1.jpg', '#000'], ['2.jpg', '#111'], ['3.jpg', '#222'], ['4.jpg', '#333'], ['5.jpg', '#444'], ['6.jpg', '#555']];
var random = Math.floor(Math.random() * images.length)]
$(body).css({
    'background-image': 'url(img/' + images[random][0] + ')',
    'color':            images[random][1]
});

Upvotes: 0

Related Questions