Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strike through on specific list item - jQuery

So I'm very new to using jQuery. I've made a very basic shopping list with an add item and clear all function. But I'd like to add in a strike through function, so that when someone clicks on a specific item they've added it strikes through like it's completed. I've tried using

<body>
    <div id="header">
        <h1>Shopping List.</h1>
    </div>
    <div id="header2">
        <h2>What I need:</h2>
    </div>
    <div id="list">
        <ul></ul>
    </div>
        <input id="name" type="text">
        <button id="addOne">Add</button>
        <button id="clear">Clear</button>


    <div id="footer">2016</div>

    <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>"
    <script>
        $("#addOne").click(function() {
            var value = $("#name").val();
            $("ul").append("<li>" + value + "</li>");
            });
        $("#clear").click(function(){
            $("ul").empty();
        });

        $("#list").click(function(){
            $(this).wrap("<strike>");
        });
    </script>
</body>

but all the list items will strike through. Would is be better in JavaScript? And how would I write it so that on click, if it has a strike through, it will un-strike?


2 Answers

The problem is because the items are added later so you need to handle the "li" like this (see below)

$("#list").on("click", "li", function(){
    $(this).wrap("<strike>");
});
like image 144
Vitaliy Terziev Avatar answered Oct 21 '25 23:10

Vitaliy Terziev


Use text-decoration: line-through;, Defines a line through the text

You can use .toggleClass if you want to toggle the style or .css(STYLE) will do, Add or remove one or more classes from each element in the set of matched elements

HTML <strike> Tag. Not Supported in HTML5.

Note: Use event-delegation for li(dynamic) elements as those are your target elements not parent UL element.

$("#addOne").click(function() {
  var value = $("#name").val();
  $("ul").append("<li>" + value + "</li>");
});
$("#clear").click(function() {
  $("ul").empty();
});

$("#list").on('click', 'li', function() {
  //-------^^---------^^^^^ // .on method is used to bind the event on dynamic elements
  $(this).toggleClass('strike');
});
.strike {
  text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="header">
  <h1>Shopping List.</h1>
</div>
<div id="header2">
  <h2>What I need:</h2>
</div>
<div id="list">
  <ul></ul>
</div>
<input id="name" type="text">
<button id="addOne">Add</button>
<button id="clear">Clear</button>


<div id="footer">2016</div>
like image 38
Rayon Avatar answered Oct 21 '25 23:10

Rayon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!