1

OK to preface I am new to javascript so this may not be the optimal way of doing this...

I am trying to change the color of a material icon when it is clicked. basically I am trying to turn it on and off. The problem is my code while it does find the icon does not read the class...I have tried adding a class, using an id, even a name and it fails to read it. I have see other responses where images are swapped and have tried with the image swap but I just want the color to change.

JAVASCRIPT:

function updateFavorites()
{
if($(this).find($("#staricon")).hasClass('text-warning'))
{
 $(this).find($("#staricon")).addClass('text-warning');

}
else
{                     
$(this).find($("#staricon")).removeClass('text-warning');
} 
}

HTML:

<a  class=" stats pull-right " href="javacript:void" ><span 
onclick="updateFavorites()"><i id="staricon" class="text-warning material-
icons " title="Favorite" >star</i></span></a>
Cesar
  • 13
  • 6

2 Answers2

0

Below is a code which will add class to #staricon whenever you click on it, and it will check if it already has that class. In CSS, you can define the color for that class.

Of course, you can add class or remove class or do other actions. Hope this code helps you.

$(".stats").on('click', function() {
  if (!$(this).find("#staricon").hasClass('SOME_CLASS'))
    $(this).find("#staricon").addClass('SOME_CLASS');
})
.SOME_CLASS {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class=" stats pull-right " href="javacript:void"><span><i id="staricon" class="text-warning material-
    icons " title="Favorite" >star</i></span></a>
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35
0

thank you all for the help...i got it to work using the following:

JAVASCRIPT

updateFavorites(id){
if($(this).find('#staricon'+id)){
    if($('#staricon'+id).hasClass('star-color')) { 
        $('#staricon'+id).removeClass('star-color');
    }
    else {
        $('#staricon'+id).addClass('star-color');
    }
}
}

HTML:

<a  class=" stats pull-right " href="javacript:void" ><span id="staricon' . $story_id .'"   onclick="updateFavorites(' . $story_id . ')"><i  class=" material-icons " title="Favorite" >star</i></span></a>
Cesar
  • 13
  • 6