How can I get the img.src back by clicking on the image using javascript?

I am trying to create a function with javascript where the user, by clicking on the image, can get these src images as url. I am very new to javascript and my attempts so far to create a function activated by the "onclick" of an image is this:

var showsrc = function(imageurl)
var img = new Image();
img.src = imageurl
return img.src

      

to trigger the results I was trying to embed image.src in my html using

document.getElementById("x").innerHTML=imageurl; 

      

I have very little success. Any help would be greatly appreciated. Thank.

+3


source to share


4 answers


I've tested this in IE9 and Chrome 17. Add an onclick handler to the body (or the closest container for all your images) and then check if the clicked element is an image. If so, please include the URL.

http://jsfiddle.net/JbHdP/



var body = document.getElementsByTagName('body')[0];
body.onclick = function(e) {
    if (e.srcElement.tagName == 'IMG')    alert(e.srcElement.src);  
};​

      

+3


source


I think you want something like this: http://jsfiddle.net/dLAkL/

See the code here:

HTML:



<div id="urldiv">KEINE URL</div>
<div>
    <img src="http://www.scstattegg.at/images/netz-auge.jpg" onclick="picurl(this);">
    <img src="http://www.pictokon.net/bilder/2007-06-g/sonnenhut-bestimmung-pflege-bilder.jpg.jpg" onclick="picurl(this);">
</div>
      

JAVASCRIPT

picurl = function(imgtag) {
    document.getElementById("urldiv").innerHTML = imgtag.getAttribute("src");
}​

      

+2


source


Image tags do not have "innerHTML" as they are single dot tags - they cannot have children. If your x

id is the image tag itself, then:

 alert(document.getElementById('x').src);

      

spits out src images.

0


source


Here's a naive solution with javascript only (possibly not cross-browser compatible):

<!doctype html>
<html>
  <head>
    <script>
      function init() {
        var images = document.getElementsByTagName('img');

        for(var i = 0, len = images.length; i < len; i++) {
          images[i].addEventListener('click', showImageSrc);
        }
      }

      function showImageSrc(e) {
        alert(e.target.src);
      }
    </script>
  </head>
  <body onload="init()">
    <img src="http://placekitten.com/300/300">
  </body>
</html>

      

0


source







All Articles