0

I'm trying to build a very basic image carousel. I have an array of photos, a few of which will be stored locally, but I want to be able to add other pictures from around the web. I have it so clicking a button adds the URL of an image the user puts in a text box to an array. The URL gets added but in the console, when I examine the array it's not storing the URL, instead it stores image#url. How can I get this to store the URL? Thanks!

var images = ['images/earth.jpg', 'images/shark.jpg', 'images/trolltunga.jpg'];
var blankWarning = document.getElementById("hidden");
var previousButton = document.querySelector('#previousButton');
var nextButton = document.querySelector('#nextButton');
var addImage = document.querySelector('#addImage');
var image = document.querySelector('img');
var url = document.getElementById('url');
var x = 0;

previousButton.addEventListener('click', function() {
  x--;
  if (x < 0) {
    x = (images.length - 1);
  }
  image.src = images[x];
});

nextButton.addEventListener('click', function() {
  x++;
  if (x === images.length) {
    x = 0;
  }
  image.src = images[x];
});

addImage.addEventListener('click', function() {
  if (url === '') {
    blankWarning.style.display = 'inline';
    blankWarning.style.color = 'red';
  } else {
    images.push(url);
  }
});
#image-wrapper img {
  width: 100px;
  height: 100px;
}

#hidden {
  display: none;
}
<div id="image-wrapper">
  <img src='http://placehold.it/100x100' />
</div>

<div id="button-wrapper">
  <button id="previousButton">Previous</button>
  <button id="nextButton">Next</button>
</div>

<div id="add-image">
  URL: <input type="text" id="url">
  <button id="addImage">Add an image</button><br>
  <p id="hidden">Image URL field cannot be blank</p>
</div>
domsson
  • 4,553
  • 2
  • 22
  • 40
Garrett Pe
  • 31
  • 1
  • 3
  • 10
  • Possible duplicate of [JavaScript: how to get value of text input field?](http://stackoverflow.com/questions/11563638/javascript-how-to-get-value-of-text-input-field) – domsson Apr 06 '17 at 11:53
  • 1
    Your "url" variable is the whole element (from `var url = document.getElementById('url');`), not the url part. You probabably want to use `images.push(url.value);` – ADyson Apr 06 '17 at 11:56
  • That was it! Thank you! – Garrett Pe Apr 06 '17 at 13:10

0 Answers0