Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using jQuery to change a background image

Tags:

jquery

css

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?

like image 384
LucyViolet Avatar asked Feb 08 '16 09:02

LucyViolet


People also ask

How to replace image using jQuery?

Answer: Use the jQuery attr() Method You can use the attr() method to change the image source (i.e. the src attribute of the <img> tag) in jQuery. The following example will change the image src when you clicks on the image.

What is the correct jQuery code to set the background color?

To add the background color, we use css() method. The css() method in JQuery is used to change style property of the selected element. The css() in JQuery can be used in different ways. The css() method can be used to check the present value of the property for the selected element.

Can you put a background image in a div?

One way is to use the background-image CSS property. This property applies one or more background images to an element, like a <div> , as the documentation explains. Use it for aesthetic reasons, such as adding a textured background to your webpage.


1 Answers

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.

like image 192
Praveen Kumar Purushothaman Avatar answered Sep 29 '22 06:09

Praveen Kumar Purushothaman