bluebomber Posted December 21, 2010 Share Posted December 21, 2010 Does anyone know if it would be possible to take the filename (src) of an image in an image-link and pass it over to a javascript variable when the user clicks on the image-link itself?Thanks. Link to comment Share on other sites More sharing options...
ShadowMage Posted December 21, 2010 Share Posted December 21, 2010 By image link you mean something like this:<a href='#'><img src='image.jpg' /></a>?It is by all means possible to get the src of that image. You'd need to pass the anchor tag to your function, and then you could use getElementsByTagName or childNodes to get a reference to the image. function getImgSrc(anchor) { var image = anchor.getElementsByTagName('img')[0]; var imgSrc = image.src; alert(imgSrc); return false;} With accompanying HTML:<a href='#' onclick='return getImgSrc(this);'><img src='image.jpg' /></a>The return statements are there to prevent the default action (following the link) from occurring.The use of the 'this' keyword passes a reference to the <a> tag that was clicked to the getImgSrc function. Link to comment Share on other sites More sharing options...
bluebomber Posted December 21, 2010 Author Share Posted December 21, 2010 Exactly what I was after, thank you! Link to comment Share on other sites More sharing options...
bluebomber Posted December 30, 2010 Author Share Posted December 30, 2010 Just wanted to come back to this thread for a moment.Is it possible to extract only the filename of the image itself when clicked and not obtain the full path to where the images is located? Link to comment Share on other sites More sharing options...
jeffman Posted December 30, 2010 Share Posted December 30, 2010 Lots of ways. Here's one:The file path is a string. Use it's split function, passing "/" as the delimiter. The return value will be an array. The last element of the array is your plain filename. Link to comment Share on other sites More sharing options...
bluebomber Posted December 30, 2010 Author Share Posted December 30, 2010 Lots of ways. Here's one:The file path is a string. Use it's split function, passing "/" as the delimiter. The return value will be an array. The last element of the array is your plain filename.I'm going to have to do quite a bit of reading before I understand this :)Update - Ok, I've just read about split functions and delimiters - I will give this a go - thanks.2nd Update - I've split the string and accessed the final entry in the array with stringsplit[stringsplit.length-1] - thanks! Link to comment Share on other sites More sharing options...
jeffman Posted December 30, 2010 Share Posted December 30, 2010 Yeah, I was hoping you'd figure out the last bit. It's pretty much the normal way to do it. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.