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
  • 197,815
  • 30
  • 248
  • 265
frazzle
  • 105
  • 1
  • 1
  • 8

3 Answers3

9

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
  • 994,864
  • 265
  • 3,241
  • 2,902
  • 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
5

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

$(function(){
$('body').css({backgroundImage : 'url(/media/bill.jpg)'});
});
AndrewSmiley
  • 1,845
  • 19
  • 31
  • 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,290
  • 12
  • 55
  • 83