Emily
Emily

Reputation: 11

Button in if loop

I'm working on a trivia code in javascript/html for a class i am taking, and when you press the correct button, i want an image of a check mark to show up. Right now, for my check mark i am using the "opacity" trait:

<img id="checkOne" src="check.jpg" style="opacity: 0">

and then later i wanted to add that if you click the right button, the opacity would change from O to 1 (if you know a better way than this that's fine, I'm totally okay with changing that).

My question: How can i say "if this button is clicked, then change the opacity to 1/put this image on the webpage. else console log try again." Help? Also, here is an example of the html i have right now:

<p> where is the atacama desert located? </p>
<button class="southAmerica" data-image="checkOne">South America</button>
<button >Africa</button>
<button >Canada</button>
<button >Russia</button>

Upvotes: 0

Views: 91

Answers (1)

Barmar
Barmar

Reputation: 781096

In the button, add an attribute that says which image it's associated with, e.g.

<button class="answerButton" data-image="checkOne">Button text</button>

Then in the click handler, you can get the value of this attribute and use it to modify the corresponding image:

var answerButtons = document.getElementsByClassName('answerButton');
for (var i = 0; i < answerButtons.length; i++) {
    answerButtons[i].addEventListener('click', function() {
        var imageId = this.getAttribute('data-image');
        document.getElementById(imageId).style.opacity = 1;
    });
}

Upvotes: 1

Related Questions