Syd
Syd

Reputation: 51

Image Swap in Javascript?

How can I swap an image in JavaScript? Specifically I want to: get a new URL from the text box and use it to update the image src attribute.

This is what I have tried:

  <h2>Image Swap</h2>
  <img id="kitten" src="http://placekitten.com/g/300/200" title="A kitten" alt="A kitten"><br>
  <input type="text" id="get-img" placeholder="Enter image url here">
  <button id="update-img">Update</button>
  <p>Some possible test examples:</p>
  <ul>
    <li>http://placekitten.com/g/400/320</li>
    <li>http://www.nd.edu/assets/features/2012/features/laetare-2015/standard.jpg</li>
    <li>http://place-hoff.com/400/350</li>
    <li>http://www.placecage.com/c/200/300</li>
  </ul>

  <script>
  var imgchange = document.getElementById("kitten");
  var updateimg = document.getElementById("update-img");
  updateimg.addEventListener("click", myFunction);
  function myFunction(){
      imgchange.setAttribute("src", "document.getElementById("get-img").value");
  }
  </script>

Upvotes: 0

Views: 234

Answers (1)

robbmj
robbmj

Reputation: 16516

You are so close.

The only thing that needs to change is: "document.getElementById("get-img").value" to document.getElementById("get-img").value.

window.onload = function() {
  var imgchange = document.getElementById("kitten"),
      updateimg = document.getElementById("update-img"),
      imgSelector = document.getElementById("get-img");

  updateimg.addEventListener("click", myFunction);

  function myFunction() {
    imgchange.setAttribute("src", imgSelector.value);
  };
};
<h2>Image Swap</h2>
<img id="kitten" src="http://placekitten.com/g/300/200" title="A kitten" alt="A kitten">
<br>
<input type="text" id="get-img" placeholder="Enter image url here">
<button id="update-img">Update</button>
<p>Some possible test examples:</p>
<ul>
  <li>http://placekitten.com/g/400/320</li>
  <li>http://www.nd.edu/assets/features/2012/features/laetare-2015/standard.jpg</li>
  <li>http://place-hoff.com/400/350</li>
  <li>http://www.placecage.com/c/200/300</li>
</ul>

Upvotes: 2

Related Questions