CompMike
CompMike

Reputation: 37

Background image change on click of to url of clicked image

I'm trying to change the background image on click. Instead of using a set value for the bg image to change to, I want the image to be the changed to the url of the image clicked.

I've created a jsfiddle with an example of what I have in mind. It's shows where I'm stuck at currently. It is located here: http://jsfiddle.net/CompMike/j8JZ3/27/

The is the jQuery I tried, but it's not working. I'm fairly new to this. switchfg is a div with a transparent image inside of it. It has a background image set to a default value. switchbg is a list of images that are on the same page. When one of those is clicked I need that image to be set to the background of the div switchfg. Any help would be greatly appreciated. http://jsfiddle.net/CompMike/j8JZ3/27/

jQuery(document).ready(function() {

var switchfg = jQuery('.light-switch');
var switchbg = jQuery('.switchbg img');

switchbg.on("click", function() {
    var img = $(this).attr('src');
    switchfg.css('background-image', function() {
        'url(' + img + ');' 
    });
   });
});​

Upvotes: 2

Views: 420

Answers (2)

Adam Lukaszczyk
Adam Lukaszczyk

Reputation: 4926

I made update for your script:

http://jsfiddle.net/j8JZ3/35/

1st of all there was some mess in code - function() inside $.css(). Just removed it.

But the real problem was that in your CSS file you declared

background: url(....)

and in JavaScript you wanted to change:

background-image: .....

So I changed both to background: url(....) and it worked.

Upvotes: 1

Michele Bertoli
Michele Bertoli

Reputation: 1030

You havo to set the background directly (without a function) like this:

switchfg.css('background-image', 'url(' + img + ')');

To see the background you also need to give a width and a height to the .light-switch div.

Upvotes: 2

Related Questions