Reputation: 85
I want to make a page where the user can insert a url and when they click the button their image will appear on the page. But as the code stands now, when a user inserts their url, it displays the url and not the image. Any ideas on what I'm doing wrong? Thank you!
<script>
function start() {
var button = document.getElementById("addButton");
button.onclick = buttonClick;
}
window.onload = start;
function buttonClick() {
var imageLinkInput = document.getElementById("imageInput");
var imageLink = imageLinkInput.value;
if (imageLink == "") {
alert("Please enter an image");
}
else {
var li = document.createElement("li");
li.innerHTML = imageLink;
var ul = document.getElementById("images");
ul.appendChild(li);
imageInput.value = "";
}
}
</script>
<body>
<input type="text" id="imageInput" size="40" placeholder="Enter Image">
<input type="button" id="addButton" value="Add Image">
<ul id="images"></ul>
</body>
Upvotes: 0
Views: 51
Reputation: 1332
You should create a new Image element ("img") and add it to the unordered list:
<script>
function start() {
var button = document.getElementById("addButton");
button.onclick = buttonClick;
}
window.onload = start;
function buttonClick() {
var imageLinkInput = document.getElementById("imageInput");
var imageLink = imageLinkInput.value;
if (imageLink == "") {
alert("Please enter an image");
}
else {
var ul = document.getElementById( 'images' );
var li = document.createElement( 'li' );
// create image tag here and set source
var img = document.createElement( 'img' );
img.src = imageLink;
li.appendChild( img );
ul.appendChild( li );
imageInput.value = '';
}
}
</script>
<body>
<input type="text" id="imageInput" size="40" placeholder="Enter Image">
<input type="button" id="addButton" value="Add Image">
<ul id="images"></ul>
</body>
Please see this Fiddle: http://jsfiddle.net/kukiwon/HDWzz/
Upvotes: 1
Reputation: 5148
Instead of setting the innerHtml of the li
, create a new img
element and set it's source and append that to your li
.
var ul = document.getElementById( 'images' );
var li = document.createElement( 'li' );
var img = document.createElement( 'img' );
img.src = imageLink;
li.appendChild( img );
ul.appendChild( li );
imageInput.value = '';
Upvotes: 0