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.

2
  • why don't you set an id and pass the function with document get Id? src is not function call attribute. Commented Dec 6, 2017 at 8:21
  • 2
    Maybe you find a answer here: stackoverflow.com/questions/12196435/… Commented Dec 6, 2017 at 8:22

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

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.