0

Is there a way to change the background-image style with javascript? i currently have:

if($(".stLarge").attr.backgroundImage = "http://w.sharethis.com/images/facebook_32.png") {

      console.log('hello');
      $('.stLarge[backgroundImage="http://w.sharethis.com/images/facebook_32.png"]').attr("backgroundImage", "url(/images/facebook.png)";
    } 

It's getting inside the if statement but not executing the image change. Any idea what i have done wrong? Thanks in advance

Alex Murray
  • 265
  • 6
  • 21

3 Answers3

2

BackgroundImage is a property of the style object within Element Objects and not an attribute. You can change and read css properties with jQuery .css() method.

var imgUrls = ['http://w.sharethis.com/images/facebook_32.png', '/images/facebook.png']
var $jq = $(".stLarge");
if($jq.css('background-image').indexOf(imgUrls[0]) > -1){
   $jq.css('background-image', 'url("' + imgUrls[1] + '")');
}
MinusFour
  • 13,913
  • 3
  • 30
  • 39
0

I do not think there is an atribute backgroundImage, you need to use css

$('.stLarge[style*="background-image: url(http://w.sharethis.com/images/facebook_32.png)"]').css("background-image", "url(/images/facebook.png)");

jQuery - css() Method

COLD TOLD
  • 13,513
  • 3
  • 35
  • 52
0

Syntax errors and misuse of jQuery. Do this:

$('.stLarge').each(i, e){
  if($(e).css('backgroundImage').match(/url\(('|")?https?\:\/\/w\.sharethis\.com\/images\/facebook_32\.png(\1)?\)/)){
    $(e).css('backgroundImage', "url('/images/facebook.png')");
  }
} 
StackSlave
  • 10,613
  • 2
  • 18
  • 35