I have a button of which when I click it I want to alert the background-image
URL of #div1
.
Is it possible?
This question is related to
jquery
url
html
background-image
Using just one call to replace
(regex version):
var bgUrl = $('#element-id').css('background-image').replace(/url\(("|')(.+)("|')\)/gi, '$2');
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
}
I think that using a regular expression for this is faulty mainly due to
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);
});
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"
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, "");
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);
})
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);
});
Source: Stackoverflow.com