Reputation: 355
I have a script that picks a random background image for the body
element of my document from a directory called bg-images
. If the chosen background image has "_dark" in the image file name, I would like to add a special class to the body element.
Here is the jQuery I'm using. It works great in Chrome & Safari, but does nothing in Firefox:
var backgroundImage = $('body').css('background');
var isitdark = "_dark";
if (backgroundImage.indexOf( isitdark ) != -1 ) {
$('body').addClass("dark");
} else {
$('body').removeClass("dark");
}
How come this doesn't do anything in Firefox? Is there a better way of writing it?
I've tried adding "type=text/javascript"
to all my script tags but that doesn't seem to help and the rest of the jQuery on my site works correctly in all browsers.
Upvotes: 1
Views: 2441
Reputation: 1074276
background
is a shorthand property. Shorthand properties are not guaranteed to be retrieved correctly with css
:
Retrieval of shorthand CSS properties (e.g.,
margin
,background
,border
), although functional with some browsers, is not guaranteed.
If you specifically want to get background-image
, get background-image
:
var backgroundImage = $('body').css('background-image');
Upvotes: 4
Reputation: 28409
You're not getting the background image with $('body').css('background');
Use .css('background-image')
var backgroundImage = $('body').css('background-image');
It's not necessary because the string _dark will or will not be there but if you want to you can remove the url()
or url("")
var backgroundImage = /url\(\s*(['"]?)(.*?)\1\s*\)/g.exec($('body').css('background-image'))[2];
Works fine in FF
Upvotes: 4