Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Stefan Cutajar
7,747 PointsHow to traverse to the relative path of an image
Hi, I am trying to build a small image gallery image slider. However I am having an issue to get relative path of the img that are clicked. I tried using .src but it returns the absolute path not the relative
1 Answer
Aaron Loften
12,864 PointsThere are several options here depending on how you made this but with no code, Im totally guessing in the dark here...
First off, the best solution, if youre setting the image paths manually, is probably to set the relative path to a data attribute(like "data-rel-path") on the html element. This makes it easier since youre setting the path anyways. In that scenario, you just need to grab that attribute's value and youre done.
Although, since youre not showing any code above, I can assume you may possibly be implementing the src dynamically with js??? In that case, you can alter the src you enter to only be relative or you can parse it(seriously though, dont parse it if youre entering it with js dynamically - just use a relative path there).
If you have to parse it, you can do the following, though its pretty incomplete since I dont see your code...
var urlToParse = do what you did to get the image url again here;
var currentRelToTop = window.location.pathname.replace(/\/(.*?)\//g, "../");
var relPathing = currentRelToTop + urlToParse.replace(window.location.protocol, "").replace("//", "").replace("/","").replace(window.location.hostname, "");
Its not relative though, it just looks like it. It should work but is not the best approach.
Stefan Cutajar
7,747 PointsStefan Cutajar
7,747 PointsThanks alot i used the data attribute and it worked :)
Aaron Loften
12,864 PointsAaron Loften
12,864 PointsGood, Im glad! Data-attributes make my day.