Jakub Svoboda Jakub Svoboda - 2 years ago 123
Javascript Question

JQuery - change multiple background images

I have a CSS code that creates a frame using 8 images:

background-image: url(images/blue/tl.png), url(images/blue/tr.png), url(images/blue/bl.png), url(images/blue/br.png), url(images/blue/t.png),url(images/blue/b.png),url(images/blue/l.png),url(images/blue/r.png);
background-position: top left, right top, bottom left, bottom right, top, bottom, left,right;
background-repeat: no-repeat,no-repeat,no-repeat,no-repeat,repeat-x,repeat-x,repeat-y,repeat-y;

My goal is to make a JQuery program, that can change the sources to different images. I have a problem defining the change in JQuery for multiple background images. I always end up with only one image changing.

JQuery code:

$(document).ready(function() {
$("#red").on("click", function(){
$("#outer-frame").css({'background-image': "url(images/red/tl.png)", 'background-image': "url(images/red/tr.png)"});
$("#outer-frame").css({'background-position': "top left", 'background-image': "top right"});

I would really appreciate if somebody who knows how to do this would help me.
Thank you for advice.

Answer Source

To set multiple background images with javascript, you set the style only once, but with the string of multiple backgrounds as the value, otherwise each resetting of the style overwrites the previous etc.

    'background-position' : 'top left',
    'background-image'    : 'url(images/red/tl.png), url(images/red/tr.png)'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download