I am a total beginner into Javascript. I am following a tutorial of Clever Programmer on Youtube. The reason why there are generated gifs is because I was using this API thingy.
What seen in the tutorial is him generating some random cat pictures when you click generate.
I was already successful in that part but he didnt make a remove button for the generated pictures. So that is what I tried to do. After generating the images successfully I clicked the Remove button, they were deleted so that’s good so then I tried to generate more but after that I couldnt generate any. The only way I could generate new images now is by refreshing the page and hitting the generate button.
function generateCat(){
var image=document.createElement('img');
var div=document.getElementById('flex-cat-gen');
image.src="https://thecatapi.com/api/images/get?format=src&type=gif&size=small";
div.appendChild(image);
}
function removeCat(){
document.getElementById('flex-cat-gen').remove();
}
<div class="container-2">
<h2>Challenge 2: Cat Generator</h2>
<button class="btn btn-success" id="cat-generator" onclick="generateCat()">Generate Cat</button>
<div class="flex-box-container-2" id="flex-cat-gen">
</div>
<div>
<button class="btn btn-danger" id="cat-remover" onclick="removeCat()">Remove Cat</button>
</div><
</div>
>Solution :
Just give an Id to the image, below the code
function generateCat(){
var image=document.createElement('img');
image.setAttribute("id","myCatImage");
var div=document.getElementById('flex-cat-gen');
image.src="https://thecatapi.com/api/images/get?format=src&type=gif&size=small";
div.appendChild(image);
}
function removeCat(){
var img=document.getElementById('myCatImage').remove();
}
<div class="container-2">
<h2>Challenge 2: Cat Generator</h2>
<button class="btn btn-success" id="cat-generator" onclick="generateCat()">Generate Cat</button>
<div class="flex-box-container-2" id="flex-cat-gen">
</div>
<div>
<button class="btn btn-danger" id="cat-remover" onclick="removeCat()">Remove Cat</button>
</div><
</div>