Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting relative image src with jQuery

I've got image tags that look like this:

<img src="/path/to/my/image.jpg" />

But when I access the src bit using jQuery, jQuery gives me back:

http://example.com/path/to/my/image.jpg

This is causing problems in some comparisons I'm doing. I don't want to change my image paths to use absolute URLs.

Any ideas as to how I can either get the absolute URL from the image path (this might not be as simple as concatenating the domain - since the URLs may occasionally be absolute), or get the path I provided in the HTML? Either way I need them to match up.

Edit per comment from activa

There's not really a lot of jQuery code to post, I'm using the cycle plugin, and in the onbefore function, I'm just calling next.src. My jQuery and JavaScript foo isn't sufficient to really understand what the cycle plugin is doing to generate next - I think it's the DOM element for the next image being cycled in, if you're familiar with what cycle does.

My image tag is actually this:

<img src="/site_media/photologue/photos/cache/6927d406810ee9750a754606dcb61d28.jpg" alt="" class="landscape slideshow-image-1" />

and in my onbefore function this code:

alert(next.src);

results in an alert with:

http://127.0.0.1:8000/site_media/photologue/photos/cache/6927d406810ee9750a754606dcb61d28.jpg
like image 405
Dominic Rodger Avatar asked Jun 04 '09 06:06

Dominic Rodger


People also ask

How to get image src path in jQuery?

When you are using jQuery, you can easily get the absolute path of the image using 'src' attribute. With jQuery 1.6 or higher version, a new method called 'prop()' was introduced. So using prop(), one can get value of src. $(document).

How add src attribute in jQuery?

Answer: Use the jQuery attr() Method You can use the attr() method to change the image source (i.e. the src attribute of the <img> tag) in jQuery. The following example will change the image src when you clicks on the image.


1 Answers

$("img").attr("src") gives back the actual value of the src attribute (tried in FF3 and IE7)

So when you have

<img src="http://example.com/path/to/my/image.jpg" />

it will return

http://example.com/path/to/my/image.jpg

And when you have

<img src="/path/to/my/image.jpg" />

it will return

/path/to/my/image.jpg

Edit after edit of question

Sounds like you may want to try

$(next).attr("src")
like image 68
Mario Menger Avatar answered Sep 20 '22 12:09

Mario Menger