how to display same image multiple times using same image in javascript
Solution 1
yes you can use this :
var image = new Image();
image.src = 'image src';
document.body.appendChild(image);
then you can call image where ever you want without load it again every time .
Solution 2
You can add the for loop and create the object of image then append it to the body.
var img = new Image();
img.src = "./ImageName.png"
for (var i = 0; i < 10; i++) {
document.body.appendChild(img)
}
Note: It will give the image 10 times because I added the condition to display the images 10 times.
Solution 3
Firoza Shaikh's answer is correct but in that the id of the image is not changing, it will be the same for every appended image. The OP needs different id for each image.
Here I added 10, so 10 copies will be made. Choose the number you want.
check the below snippet:
$(document).ready(function(){
for (var i = 0; i < 10; i++) {
var img = "<img src ='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRVliqjZDiZE5E_BBJhDZFxoUPY3YS3c3s3t41G9N0fIFHC1APS' id='myid"+i+"'/>";
$("body #myimg").append(img);
}
})
<body>
<div id="myimg"></div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
shadman_264
Updated on June 28, 2022Comments
-
shadman_264 almost 2 years
I want to display an image (for example: balloon) multiple times on a single page. I know I can do it by adding this
<img id="101" src="balloons.png" >
in .html as many images as I need using different id for each image. But all of their src will be same. Is there any other way around so that I can load the image only one time but can use as many copies of the same image as I want?
-
ndugger about 8 years
while
is not a function, it's a loop. -
shadman_264 about 8 years<img id="101" src="balloons.png" > If I id the image, then i can call it using the id, but in your case, how can i reffer them?
-
David Wilkinson about 8 years@ndugger, Erm, Mark isn't trying writing a function?!?!?
-
ndugger about 8 years@DavidWilkinson maybe you should be more attentive, and read the text above his code; "[...] create a while function [...]".
-
Mark about 8 years@shadman_264 not sure what you are asking? just hardcode the image right in the JS.
-
David Wilkinson about 8 years@ndugger, Yes fair enough, but you can see what Mark is trying to say. Maybe edit his answer for him, I'm sure he would've accepted a typo / wrong word correction.
-
ndugger about 8 years@DavidWilkinson I commented about his inaccuracy; Whether or not he decides to take the advice is his own prerogative; I'm not a babysitter.