1

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) :).

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);
    }
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.