Thursday, 9 September 2010

JavaScript getBackgroundImage(myDiv)

function getBackgroundImage(myDiv){
  // string to be returned
  var returnString = "";
  // Grab the offending element by id
  obj = document.getElementById(myDiv);
  // IE Opera
  if(obj.currentStyle) {
    returnString = obj.currentStyle.backgroundImage;
  }else{ // Firefox 
    returnString = getComputedStyle(obj,'').getPropertyValue('background-image');
  }
  // this gives is something like: "url(someDomain.com/someImageDirectory/someImage.someFormat)"
  // so we get everything after the last "/" which leaves us with "someImage.someFormat)""
  returnString = returnString.substring(returnString.lastIndexOf('/') + 1);
  // so we get rid of the last 2 characters leaving us with:
  returnString = returnString.substring(0, returnString.length-2);
  // "someImage.someFormat"
  return returnString;
}

With thanks to this post on WebmasterWorld. So much for being a birdbrain!

No comments:

Post a Comment