Reputation: 5
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");
}
Upvotes: 0
Views: 51
Reputation: 2837
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);
});
Upvotes: 1
Reputation: 1579
Here is a complete example:
$( document ).ready(function() {
var correctAnser = 'a'; // you need to set this to what you need the answer to be
$('ul li').on('click', function () {
$('ul li').removeClass('correct').removeClass('wrong'); // remove both classes on list elements
var classToAdd = $(this).attr('id') == correctAnser ? 'correct' : 'wrong';
$(this).addClass(classToAdd);
});
});
.correct {
background:#2bb539;
color:#ffffff;
}
.wrong {
background:#c00;
color:#ffffff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
Upvotes: 0
Reputation: 53674
If I'm understanding your end goal, you want to do something to indicate that an answer is the "right" answer or not, then you want to assign class .correct
or .wrong
if they get the "right" answer or not.
I would assign data-right="right"
to the "right" answer. Then when someone clicks on an li
, look for that attribute and assign .correct
if they chose the "right" answer, and assign .wrong
if not.
$('li').on('click',function() {
var right = $(this).data('right');
$(this).siblings().removeClass('correct wrong');
if (right == "right") {
$(this).addClass('correct');
} else {
$(this).addClass('wrong');
}
})
.correct {
color: green;
}
.correct:after {
content: '\2713';
}
.wrong {
color: red;
}
.wrong:after {
content: '\2613';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li id="a" data-right="right">A) Lucy</li>
<li id="b">B) Bonnie</li>
<li id="c">C) Sheila</li>
<li id="d">D) Kai</li>
</ul>
Upvotes: 1