Zock77
Zock77

Reputation: 1017

Adding images within the script

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

Answers (2)

Visal Chhourm
Visal Chhourm

Reputation: 544

You can do it by follow these steps:

  1. Choose the element in your html that you want to add image to. Example: <div id='maker'></div>
  2. add an event to your button in your html. Example: <button onclick='addImg()'>Add</button>
  3. 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

N Rohler
N Rohler

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

Related Questions