views:

110

answers:

2

Lets say I have two divs

How do I use .find to get div1's background image, than apply that background image to div2, and replace ".jpg" with "_highlighted.jpg" ?

var div2bg = $('.div1').find('div').attr('background-image'??)//how to assigned the background image as a variable?

$('.div2').css("background-image", "url(" + div2bg + ")");
$('.div2').css("background-image").replace(".jpg", "_highlighted.jpg");
+4  A: 

Close but replace returns a string, it doesn't change the source.

I think you want this instead:

var div2bg = $('.div1').css('background-image');

$('.div2').css("background-image", div2bg.replace(".jpg", "_highlighted.jpg"));
Joel Potter
+1 - I didn't test, but that looks correct and exactly like the solution I was going to post.
Topher Fangio
Much cleaner than mine, thank you!
Jared
+1  A: 

You an accomplish this with the following code:

// Get the first background image
var bg = $(".div1").css("background-image");
// Assign a modified version to another DIV
$(".div2").css("background-image", bg.replace(".jpg", "_highlighted.jpg"));

Whether or not the following is applicable to your project, you decide: I would like to point out this type of stuff is generally best handled with classes, and using jQuery methods like:

$(".div2").addClass("highlighted");
$(".div2").removeClass("highlighted");

It greatly reduces the verbosity of your scripts, and allows you to keep visual styles maintained in your CSS, rather than being partially-dependent upon values and strings within scripts.

Jonathan Sampson