Reputation: 395
Ive been working on an image gallery ive been creating myself and im adding a "Zoom in" feature to it.
I know im very close to succeeding but i have just one tiny issue.
In Javascript i managed to get the background property of the image that will be enlarged but it grabs the image including the url()
. I want to only get the URL (http:.../) EXCLUDING the url()
.
I hope this isn't very confusing but if you are, this is the link to my project. Click on the image to Zoom in, but it actually alerts the background-image
property because i wanted to see what it fetches first.
Is this possible?
Upvotes: 0
Views: 252
Reputation: 1
Try
var url = $(el).css("backgroundImage").split(/\s|url\(|\)/).filter(Boolean)[0];
var url = $("body").css("backgroundImage").split(/\s|url\(|\)/).filter(Boolean)[0];
console.log(url);
body {
width:300px;
height:200px;
background-image: url('http://lorempixel.com/300/200/technics/')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body></body>
Upvotes: 0
Reputation:
UPDATED
You can use a regular expression to take off the url(
and the )
like this:
var sourceimg = document.getElementById("image");
var url = window.getComputedStyle(sourceimg, null).getPropertyValue("background-image");
var urlWithoutUrl = url.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '')
alert(urlWithoutUrl);
:)
Upvotes: 1
Reputation: 4051
It would be better to just take the string inside the url()
rather than using regular expressions or other stuff.
var url = "url(somefile.gif)";
var final_url = url.substr(4, url.length - 4 - 1);
Arguments: The initial position (starting from 0
, that means fourth character is "s") and the number of characters that will create the new string (that is, the length of the original string minus 4 -the url(
stuff- and minus 1 -the )
stuff-).
The result will be:
somefile.gif
Using it in your problem:
var url = window.getComputedStyle(sourceimg,null).getPropertyValue("background-image");
var final_url = url.substr(4, url.length - 4 - 1);
alert(final_url);
Upvotes: 1
Reputation: 2924
The most simple solution is the slice method. The first parameter specifies where to start the selection, the second specifies the end the selection from end of string if it's negative. So, your code should be:
var bkImg = window.getComputedStyle(sourceimg,null).getPropertyValue("background-image");
var bkImgUrl = bkImg.slice(4, -1);
Upvotes: 1
Reputation: 969
here is the change you need to make in code:
alert(window.getComputedStyle(sourceimg,null).getPropertyValue("background-image").replace(/^url\((http.+)\)$/g, '$1'));
Upvotes: 0
Reputation: 1670
Use a regular expression, or substring from the position of
s.IndexOf("(")) + 1;
Thake everything after the "URL(" and then trim the last character to remove the ")".
Upvotes: 0