Replacing background image javascript

- 1 answer

Ad

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

Ad

Answer

Ad

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] + '")');
}
Ad
source: stackoverflow.com
Ad