1

Here is my HTML. This is going to be a fortune cookie that you can click and open. I have images stacked on top of each other that I animate to "reveal" the fortune inside.

<div id="cookie" class="cookie">
    <img id="cookie-left" class="cookie-left" src="media/cookie-left.png">
    <img onclick="cookieOpen()" id="cookie-right" class="cookie-right" src="media/cookie-right.png">
    <div id="blackbox"></div>
    <div id="fortune"><span>No snowflake feels responsible in an avalanche.</span></div>
</div>

Here is my JavaScript function. I am targeting multiple IDs in divs inside of the parent #cookie div to add/remove multiple animations at once.

function cookieOpen() {
    var element = document.getElementById("cookie-right");
    element.classList.add("cookie-open"); /* adds the animation to #cookie-right to "open" the fortune cookie*/

    var element = document.getElementById("cookie");
    element.classList.remove("cookie"); /* removes the wiggle animation from the whole div after it has been opened*/

    var element = document.getElementById("fortune");
    element.classList.add("fortune-open"); /* animation to reveal the fortune inside of the cookie*/
}

My problem is that when I duplicate my HTML code, I can't click both cookies to open them. I want to have multiple cookies on the page that you need to open individually. What am I doing wrong? I've been looking into event listeners, but I haven't had much success since I am new to JavaScript.

Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
Hippo
  • 11
  • 2
  • 3
    Change your logic to be based on classes, not ids, and use contextual lookups. Ids are expected to unique per page. Related: https://stackoverflow.com/questions/59887834/getting-the-value-of-the-input-field-using-jquery/59888053#59888053 – Taplar Jan 15 '21 at 22:12
  • What's the reason of having ids and classes with same name? – AbsoluteBeginner Jan 15 '21 at 23:56

0 Answers0