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

1
  • Are you basing your changes on background image to begin with? Commented Dec 17, 2015 at 1:41

3 Answers 3

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] + '")');
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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')");
  }
} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.