bigdaze bigdaze - 6 months ago 21
HTML Question

Toggle Text Color with Javascript

I am creating a menu in php running off of input from a JSON file. The issue i'm running into is that i want the title to change color to green once they click anywhere in the div class "menu-item". Once the color is green I would also like for them to be able to click it and have it return to it's original state. I understand i need to utilize javascript or Jquery for this option but couldn't find it in any documentation. I feel like I'm missing something small and have looked all over but haven't been able to figure it out. any help is appreciated.

foreach ($obj as $menu_item) {
echo '<div class="menu-item">';
echo '<img class="food-item" src="'.$menu_item->{'image-url'}.'"><br/>';
echo '<p class="title" onclick="changeColor("title"); return false;">'.$menu_item->name.'</p><br/>';
echo '$'.$menu_item->price.'<br/>';
echo $menu_item->Description.'<br/>';
echo '</div>';
}

Answer

Jquery toggle will do it for you, see fiddle: https://jsfiddle.net/c259LrpL/24/

  $(".menu-item").click(function() {
    $(this).toggleClass("red");
  });

CSS example:

.menu-item {
  background-color: blue;
  color: white;
}

.menu-item.red {
  background-color: red;
  color: blue;
}
Comments