Reputation: 1017
I was wondering if there is any way to add images from within the script. For example, the reason I want to do this is so I can add an Image every time the user clicks. I could add a ton of images in the Body and the hide them all and show them one by one when someone clicks, but it seems like there aught to be a better way. (In case you didn't get it, I'm Very new to JavaScript) :).
Upvotes: 1
Views: 4793
Reputation: 544
You can do it by follow these steps:
<div id='maker'></div>
<button onclick='addImg()'>Add</button>
then write these codes to your script tag or your .js file. Here is the code:
function addImg()
{
var maker = document.getElementById('maker');
var image = document.createElement('img');
image.src = '/image/path/with/extension.jpg';
maker.appendChild(image);
}
Upvotes: 0
Reputation: 4615
To dynamically add a photo, use code like this:
<div id="holder"></div>
<script type="text/javascript">
var img = new Image();
img.src = 'path/to/image.jpg';
var holder = document.getElementById('holder');
holder.appendChild(img);
</script>
The Image
object corresponds to the <img>
element. To learn more about the Image
(aka HTMLImageElement
) object, see here. To learn more about the appendChild
method, see here.
Upvotes: 1