ben_aaron ben_aaron - 7 months ago 31
HTML Question

Change word color and counter with each click Jquery

I have white text in 10 divs that should become blue once the user clicks on them and the total number of "selected" divs is 5. I did it like this:

<div id="sen1" class="sentences">Text1</div>
<div id="sen2" class="sentences">Text2</div>
<div id="sen3" class="sentences">Text1</div>
<div id="sen4" class="sentences">Text2</div>
...

$(".sentences").click(function() {
count++
$(this).css("color", "blue")
selected_true.push($(this).text())
if (count == 5){
$(".sentences").off("click")
//go to next page
}
});


Now I want the text to become white again if a blue text is clicked again and want to decrease the
count
variable by one. So ideally I want to increase the counter each time a sentence is selected and decrease it again once it is un-selected.
I thought about
toggle
but how would I incorporate the counter in the toggle method?

Answer

Doing it this way might make more sense:

css

.sentences {
   color: #fff;
}
.sentences.turnedon { 
   color: blue;
}

javascript

$(".sentences").click(function() {

    if( $(this).hasClass('turnedon') ) {

       $(this).removeClass('turnedon');
       count-1;

    } else {

       $(this).addClass('turnedon');
       count++;
   }
Comments