1

I want to pass the src url of a image via javascript function.

<head>
<script>
function myFunction() {
    var str1 = "somepictureurl.png";
    return str1;
}
</script>
</head>

<body>
    <img src="myFunction()" alt="notworking">
</body>

Unfortunately it is not working and the alt "notworking" is displaying.

mrk
  • 99
  • 3
  • 12
  • why don't you set an id and pass the function with document get Id? src is not function call attribute. – Son Dang Dec 06 '17 at 08:21
  • 2
    Maybe you find a answer here: https://stackoverflow.com/questions/12196435/javascript-function-return-src-path – Most24 Dec 06 '17 at 08:22

1 Answers1

0

HTML just doesn't work that way. The JavaScript function can not be called from an element that way.

You'll have to add a method call at the bottom of the page, and pass some kind of id:

<html>
  <head>
    <script>
      function myFunction(id) {
        var str1 = "somepictureurl.png";
        document.getElementById(id).src = str1;
      }
    </script>
  </head>
  <body>
    <img id="img1" alt="notworking">
    <script>
      myFunction("img1");
    </script>
  </body>
</html>
beaver
  • 523
  • 1
  • 9
  • 20
Cerbrus
  • 70,800
  • 18
  • 132
  • 147