7

I am trying to change the background image of an element through jquery like this;

$j(this).css('background-image','url(images/client_box_grad.gif)');

However when it renders it seems to drop speech marks around the the url, eg

$j(this).css('background-image','url("images/client_box_grad.gif")');

And this means the image isn't visible - if I remove the speech marks in Firebug then the image shows up.

Any ideas ?

j08691
  • 204,283
  • 31
  • 260
  • 272
frazzle
  • 115
  • 1
  • 1
  • 8

3 Answers3

10

The double quotes are not necessary:

$(this).css('background-image', 'url(/images/client_box_grad.gif)');

You should make sure that you have specified a valid image url. Here's a demo.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    Cheers Darin - it works when I stick the absolute path on, I'd like to use relative pathing if possible, as it's sat in a wordpress install where everything has been made relative so nothing broke when I stuck it live from my dev area. I can live with that if I can't use any form of relative pathing though. Also it seems to add in the double quotes as part of the replacement - they are not there in any of the code. – frazzle Feb 02 '11 at 12:41
6

This is what I had to do to get it to work:

$(function(){
$('body').css({backgroundImage : 'url(/media/bill.jpg)'});
});
AndrewSmiley
  • 1,933
  • 20
  • 32
  • 1
    I have tried all other ways that are mentioned in other answers. No one worked form me. But your solution is worked like a charm for me. – Akshay Pethani Feb 05 '18 at 10:13
2

Try these:

$(this).css('background-image','url(images/client_box_grad.gif)');

// OR
$(this).css('background', 'url("images/client_box_grad.gif")');
Harold Sota
  • 7,490
  • 12
  • 58
  • 84