7

I am trying to use jQuery to change the background image in a table cell, the table cell has its own class of ".active". I am using jQuery to change other elements in the same place and they all work fine so i think i must have something wrong in the syntax. the function i am using executes after a button is clicked. my code:

function vehicle(arg){
  $(".active").css("color", "blue");  
  $(".active").css("background-image", "url(../img/car.png)");
};

css:

.active{
  background-size: 10px 10px;
  background-repeat: no-repeat;
  border-right: 1px solid none;

the first line executes fine, i have tried the following code plus changed the picture size in every way i can think of :

   $(".active").css("background-image", "../img/car.png");
   $(".active").css("background-image", "url('../img/car.png')");

can anyone point out what i did wrong?

Praveen Kumar Purushothaman
  • 160,666
  • 24
  • 190
  • 242
LucyViolet
  • 951
  • 3
  • 10
  • 16
  • Possible duplicate of [Switching a DIV background image with jQuery](http://stackoverflow.com/questions/253689/switching-a-div-background-image-with-jquery) – miguelmpn Feb 08 '16 at 10:03
  • @miguelmpn How can that be a dupe? Not dupe. – Praveen Kumar Purushothaman Feb 08 '16 at 10:10
  • If your problem is solved now, consider accepting the answer that helped you to that end the most with the green Checkmark symbol next to the vote count. Please [accept the answer](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) to signify that this is solved. You also get 2 reputation points for doing so. – Praveen Kumar Purushothaman Feb 09 '16 at 11:33

3 Answers3

9

You need to put the .css() relative to the page. So try:

$(".active").css("background-image", "url('img/car.png')");

Assuming the img/ is in the same directory as the page, this should work. Else use the relative paths to the root.

Praveen Kumar Purushothaman
  • 160,666
  • 24
  • 190
  • 242
5

You can also try the below syntax to set the background image dynamically

$(".active").attr("style", "background-image: url('your url')");
Praveen Kumar Purushothaman
  • 160,666
  • 24
  • 190
  • 242
-1

You can set a CSS class to change the image.

CSS:

.img1{
    background-image:img/car1.png;
}

.img2{
    background-image:img/car2.png;
}

jQUERY:

$(".active").removeClass('img1').addClass('img2');
Tushar
  • 82,599
  • 19
  • 151
  • 169
Ganya
  • 9
  • 2
  • 2
    That's not the question. first u can't add a background-image like that, and create a class per image is not a good way. he just want to have the good url. – Alexis Feb 08 '16 at 10:08