0

I want to assign content of the src tag of image to a variable on clicking on the image through JS: Eg-

HTML

<div id="img">
<img src="image1.jpg">
<img src="image2.jpg">
</div>
<span id="source"/>

JS ???

I want to assign the image source of the clicked image to a variable and then display the source on HTML through span. This all should happen when I click the image. And the source that is going to be assigned to variable should be of the clicked image.

How can I do it?

Thanks in advance.

2
  • This is more likely a JavaScript question. please don't tag Java Commented Mar 8, 2017 at 15:58
  • You should at least provide a little bit of javascript code, try something before asking here. Commented Mar 8, 2017 at 20:21

2 Answers 2

1

try the following:

<html>
  <head>

  <script>
      function setImage(id){
         var element = document.getElementById(id).src;
         document.getElementById("source").innerHTML = "<img src='" +   element + "' />";
      }

  </script>

  </head>

  <body>
         <div id="img">
           <img id="img1" src="image1.jpg" onclick="setImage(this.id)" >
           <img id="img2" src="image2.jpg" onclick="setImage(this.id)" >
         </div>
        <span id="source"></span>
   </body>
  </html>
Sign up to request clarification or add additional context in comments.

2 Comments

But i need that this should happen when I click the image!
in this example, when you click on an image (image1 or image2), that particular image will be shown in span... isn't it you want?
0

you can try this,

<img ng-src="{{myVar}}">

3 Comments

What will this do?
from angular controller you can assing value to myvar.
At no point does the question asker state that they are using AngularJS. Please ready the question thoroughly before providing an answer, and provide some context surrounding your answer to state how your code should be implemented (such as that it requires AngularJS in this case). I also recommend reviewing the help article on how to write great answers :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.