GigiNicaragua
GigiNicaragua

Reputation: 25

Changing background-image with jQuery CSS property is not working

I tried the most voted answer on this thread but it isn't working for me.

Most voted answer said:

You probably want this (to make it like a normal CSS background-image declaration):

$('myOjbect').css('background-image', 'url(' + imageUrl + ')');

Here's the JS code:

$('.icon-menuoption').click(function() {

$('.menu').animate({
  left: "-285px"
}, 200);


$('body').animate({
  left: "0px"
}, 200);

$('jumbotron').css('background-image', 'url(' + /images/bg_v3.png + ')');

});

The menu and body move like they are supposed to but the jumbotron's background-image doesn't. I do have the bg_v3.png image in the images directory, which is in the same directory as this JS code.

Without this part:

$('jumbotron').css('background-image', 'url(' + /images/bg_v3.png + ')');

It does what it is supposed to but I also want to change the background-image.

Note: I am a complete noob. I am learning through codeacademy and have very little knowledge of JS, jQuery and CSS so please be as detailed as possible.

Thank you!

Upvotes: 0

Views: 2190

Answers (1)

Nguyen Tuan Anh
Nguyen Tuan Anh

Reputation: 1035

There are two things you need to correct in this line of code:

$('jumbotron').css('background-image', 'url(' + /images/bg_v3.png + ')');

First, the selector $('jumbotron') is not going to select any element. It returns null, hence calling the .css function will cause an error. If your targeting element has ID = 'jumbotron', then the selector should be changed to $('#jumbotron'). If that element has CSS class of .jumbotron, then the selector should be $('.jumbotron').

Secondly, your 'url(' + /images/bg_v3.png + ')' part also causes another error. This should be 'url(/images/bg_v3.png)'.

Upvotes: 2

Related Questions