Jquery click event if statement

I'm adding trivia as a main component to my webpage. I'm trying to the class of "correct" when it's right, and "wrong" when it's wrong. I have no idea what I'm doing. lol. Any help would be greatly appreciated.

    <ul>
        <li id="a">A) Lucy</li>
        <li id="b">B) Bonnie</li>
        <li id="c">C) Sheila</li>
        <li id="d">D) Kai</li>
    </ul>

JQuery

I tried to make the correct one a variable in Jquery

 var right = $( "ul li#a" ).on(click, function() {});

 if (click === right){
     $("ul li#a").addClass("correct");
 } else {
     $("li").addClass("wrong");
 }  

Answers 1

  • This solution relies on giving the right answers a class called "correctAnswer", then binding a click event handler that sets the class of the clicked li based on whether or not it has that class. I think that does what you're looking for:

    <ul>
        <li id="a" class="correctAnswer">A) Lucy</li>
        <li id="b">B) Bonnie</li>
        <li id="c">C) Sheila</li>
        <li id="d">D) Kai</li>
    </ul>
    
    $('li').on('click', function () {
        var classToAdd = $(this).is('.correctAnswer') ? 'correct' : 'wrong';
        $(this).addClass(classToAdd);
    });
    

Related Articles