jQuerybeast
jQuerybeast

Reputation: 14490

Can I get div's background-image url?

I have a button of which when I click it I want to alert the background-image URL of #div1.

Is it possible?

Upvotes: 98

Views: 163365

Answers (9)

Alexandru Burca
Alexandru Burca

Reputation: 427

My two cents.
None of these solutions work if the background-image property is overwritten in CSS by the background property.
Let's say you have the background-image property set and you don't want to see it in the browser, you just need to get the value in jQuery for some purpose. So, if you have something like this:

<div class="myDivWithBackground">
 <p>Lorem Ipsum</p>
</div>
<style>
.myDivWithBackground{
 background-image: URL('url-here.jpg')
}
div.myDivWithBackground{
 background: #fff!important
}
</style>

Then $('div').css('background-image'); returns none instead the URL.

If you need to keep background white and also to get the background-image URL value in jQuery then replace the background with pseudo-element, like this:

<style>
    .myDivWithBackground{
     background-image: URL('url-here.jpg')
    }
    div.myDivWithBackground:after{
      content: '';
      display: block;
      width: 100%;
      height: 100%;
      background: #fff;
      top: 0;
      position: absolute;
    }
    div.myDivWithBackground p{
      position: relative;
      z-index: 9999;
    }
</style>

Now $('div').css('background-image'); returns URL('url-here.jpg') instead none.

Upvotes: 0

Here is a simple regex which will remove the url(" and ") from the returned string.

var css = $("#myElem").css("background-image");
var img = css.replace(/(?:^url\(["']?|["']?\)$)/g, "");

Upvotes: 4

Ogg
Ogg

Reputation: 59

Using just one call to replace (regex version): var bgUrl = $('#element-id').css('background-image').replace(/url\(("|')(.+)("|')\)/gi, '$2');

Upvotes: 1

Middletone
Middletone

Reputation: 4270

I think that using a regular expression for this is faulty mainly due to

  • The simplicity of the task
  • Running a regular expression is always more cpu intensive/longer than cutting a string.

Since the url(" and ") components are constant, trim your string like so:

$("#id").click(function() {
     var bg = $(this).css('background-image').trim();
     var res = bg.substring(5, bg.length - 2);
     alert(res);
});

Upvotes: 7

Blazemonger
Blazemonger

Reputation: 92893

I usually prefer .replace() to regular expressions when possible, since it's often easier to read: http://jsfiddle.net/mblase75/z2jKA/2

    $("div").click(function() {
        var bg = $(this).css('background-image');
        bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
        alert(bg);
    });

Upvotes: 206

Berty
Berty

Reputation: 1178

I'm using this one

  function getBackgroundImageUrl($element) {
    if (!($element instanceof jQuery)) {
      $element = $($element);
    }

    var imageUrl = $element.css('background-image');
    return imageUrl.replace(/(url\(|\)|'|")/gi, ''); // Strip everything but the url itself
  }

Upvotes: 6

Michael Spector
Michael Spector

Reputation: 36999

I have slightly improved answer, which handles extended CSS definitions like:

background-image: url(http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png), -webkit-linear-gradient(top, rgb(81, 127, 164), rgb(48, 96, 136))

JavaScript code:

var bg = $("div").css("background-image")
bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')

Result:

"http://d36xtkk24g8jdx.cloudfront.net/bluebar/359de8f/images/shared/noise-1.png"

Upvotes: 22

Alexander Presber
Alexander Presber

Reputation: 6625

As mentioned already, Blazemongers solution is failing to remove quotes (e.g. returned by Firefox). Since I find Rob Ws solution to be rather complicated, adding my 2 cents here:

$('#div1').click (function(){
  url = $(this).css('background-image').replace(/^url\(['"]?/,'').replace(/['"]?\)$/,'');
  alert(url);
})

Upvotes: 11

Rob W
Rob W

Reputation: 348992

Yes, that's possible:

$("#id-of-button").click(function() {
    var bg_url = $('#div1').css('background-image');
    // ^ Either "none" or url("...urlhere..")
    bg_url = /^url\((['"]?)(.*)\1\)$/.exec(bg_url);
    bg_url = bg_url ? bg_url[2] : ""; // If matched, retrieve url, otherwise ""
    alert(bg_url);
});

Upvotes: 55

Related Questions