0

I'm trying to put a line through each ingredient as it is clicked. With the code I have below there is no line shown when I click it.

$(document).ready(function(){
  $(".recipe .ingredients .ing li").click(function(){
    $(this).css("text-decoration", "line-through");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="recipe">
  <div class="ingredients">
    <h3> Ingredients </h3>
    <ul class="ing">
      <li> 1 ripe banana </li>
      <li> 1/2 ripe avocado </li>
      <li> 1 tbsp cocoa powder </li>
      <li> 4 cups chocolate almond milk </li>
      <li> 4 pitted dates </li>
    </ul>
  </div>
</div>

1
  • 2
    I just put your code in a snippet, without changing anything, and it works. Aug 11, 2015 at 15:38

3 Answers 3

1

You probably want the line-through to toggle.

If so, it's simpler to set up a style directive ...

.ing li.linethrough {
    text-decoration: line-through
}

... and use .toggleClass() :

$(document).ready(function(){
    $(".ing li").click(function() {
        $(this).toggleClass('linethrough');
    });
});

Even if you don't want a toggle action, it's still advantageous to restyle using a CSS directive.

And fix the HTML as others have said

0

Change your code to this:

$(document).ready(function () {
    $(".ing>li").click(function () {
        $(this).css("text-decoration", "line-through");
    });
});

Here is the JSFiddle demo

6
  • OP's code already does this. Although your selector is likely to be faster. Aug 11, 2015 at 15:39
  • @evolutionxbox I agree. The most likely cause is the invalid html code where the closing div tag was missing, so .recipe class was not found
    – Ahs N
    Aug 11, 2015 at 15:40
  • But there is a closing div... Aug 11, 2015 at 15:41
  • Also, why link of to jsbin, when stackoverflow has a snippet function, which does the same? Aug 11, 2015 at 15:44
  • But its the closing div of ".ingredients" ...
    – Ahs N
    Aug 11, 2015 at 15:44
0

Your code works once you make the html valid for me.

(JSFiddle)

$(document).ready(function(){
  $(".recipe .ingredients .ing li").click(function(){
    $(this).css("text-decoration", "line-through");
  });
});
<div class="recipe">
    <div class="ingredients">
        <h3> Ingredients </h3>
        <ul class="ing">
            <li> 1 ripe banana </li>
            <li> 1/2 ripe avocado </li>
            <li> 1 tbsp cocoa powder </li>
            <li> 4 cups chocolate almond milk </li>
            <li> 4 pitted dates </li>
        </ul>
    </div>
</div>                                                                                                                                                        <!-- jQuery --><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.