Search code examples
clickcreateelementsetattributeevent-listener

How does one make createElement('IMG') clickable?


My goal is to make the bottom Queen, a created element, clickable the same as the top Queen. How does one accomplish that?

<!DOCTYPE html>
<html>
<body>
<p><button onclick='createAnImg()'>Create Card</button></p>
<img src='Card Deck/QueenHearts.png' onclick='alert("You picked the Queen of Hearts!")'>
<p id='card_holder'></p>

<script>
function createAnImg() {
x = document.createElement('IMG');
x.setAttribute('id', 'Queen_of_Hearts');
x.setAttribute('src', 'Card Deck/QueenHearts.png');
x.setAttribute('width', '72');
x.setAttribute('alt', 'Card Face');
document.getElementById('card_holder').appendChild(x);
}
</script>

</body>
</html>

Solution

  • Just add:

    x.setAttribute('onclick', 'alert("You picked the Queen of Hearts!")');
    

    to your attributes.

        <!DOCTYPE html>
        <html>
        <body>
        <p><button onclick='createAnImg()'>Create Card</button></p>
        <img src='https://lh3.googleusercontent.com/-KBSwW1xXPt4/VY12U034XEI/AAAAAAAAASE/5C_uZ_o64QE/s96/23.png' onclick='alert("You picked the Queen of Hearts!")'>
        <p id='card_holder'></p>
        
        <script>
        function createAnImg() {
        x = document.createElement('IMG');
        x.setAttribute('id', 'Queen_of_Hearts');
        x.setAttribute('src', 'https://lh3.googleusercontent.com/-KBSwW1xXPt4/VY12U034XEI/AAAAAAAAASE/5C_uZ_o64QE/s96/23.png');
        x.setAttribute('width', '72');
        x.setAttribute('alt', 'Card Face');
        x.setAttribute('onclick', 'alert("You picked the Queen of Hearts!")');
        document.getElementById('card_holder').appendChild(x);
        }
        </script>
        
        </body>
        </html>