Search code examples
javascriptonclickvisibilityeventhandler

How do I make my images disappear when clicked using the code I have?


I'm overlaying images on top of each other and want to make it so when you click each one it disappears, revealing the image underneath. This is what I have in the script tag:

function attach_eventhandler(d){
    d.onclick = function(){
        this.style.visibility = "hidden";
    }
}
var myArray = document.getElementsByTagName("heart");
for(var d of myArray){
  attach_eventhandler(d);
}

And these are the two images I have right now. I want "heart" to disappear, then "pig".

<img id="pig"src="pig.jpg" alt= height="700 px" width="500 px">

<img id="heart"src="heart.jpg" alt= height="700 px" width="500 px">

Solution

  • As it is, your images don't seem to overlay, unless you are applying css. To make them overlay you should use position:absolute. Like this:

    <div>
        <img id="pig"src="pig.jpg" alt= height="700 px" width="500 px" style="position:absolute;top:0;left:0">
        <img id="heart"src="heart.jpg" alt= height="700 px" width="500 px" style="position:absolute;top:0;left:0">
    </div>
    

    Also, you want to call getElementsByTagName() with "img" instead of "heart", like this:

    var myArray = document.getElementsByTagName("img");``
    

    This is the complete page:

    <html>
    <head>
    </head>
    <body>
    <div>
        
        <img id="pig"src="pig.jpg" alt= height="700 px" width="500 px" style="position:absolute;top:0;left:0">
    <img id="heart"src="heart.jpg" alt= height="700 px" width="500 px" style="position:absolute;top:0;left:0">  
    </div>  
    <script>
    function attach_eventhandler(d){
        d.onclick = function(){
            this.style.visibility = "hidden";
        }
    }
    var myArray = document.getElementsByTagName("img");
    for(var d of myArray){
      attach_eventhandler(d);
    }
    </script>
    
    </body>
    </html>
    

    EDIT: Oh and, actually, maybe you're doing it, but you should run the script using the DOMContentLoaded event, like this:

    <script>
        window.addEventListener('DOMContentLoaded', function() {
            var myArray = document.getElementsByTagName("img");
            for(var d of myArray){
              attach_eventhandler(d);
            }
        });
        function attach_eventhandler(d){
            d.onclick = function(){
                this.style.visibility = "hidden";
            };
        }
    
    </script>