Home > Back-end >  Successfully generated new pictures, removed them, but can't generate again
Successfully generated new pictures, removed them, but can't generate again

Time:10-18

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 >
        <h2>Challenge 2: Cat Generator</h2>
        <button  id="cat-generator" onclick="generateCat()">Generate Cat</button>
    
        <div  id="flex-cat-gen">
          
            
        </div>
        <div>
        <button  id="cat-remover" onclick="removeCat()">Remove Cat</button>
        </div><
    </div>

CodePudding user response:

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 >
        <h2>Challenge 2: Cat Generator</h2>
        <button  id="cat-generator" onclick="generateCat()">Generate Cat</button>
    
        <div  id="flex-cat-gen">
          
            
        </div>
        <div>
        <button  id="cat-remover" onclick="removeCat()">Remove Cat</button>
        </div><
    </div>

CodePudding user response:

when you remove element from dom, you didn't remove img but you removed parent div so next time when you try to add img to div with flex-cat-gen id its fail because its remove already!

solution:

add id to img element when you generate img. on remove function get img element by id then remove img

  • Related