Thursday, December 11, 2014

Making Lists into To-Do Lists with jQuery

I have a folder containing several procedures that are in written with HTML lists. I wanted a way to quickly modify them so that I could check off each line item as I went through the procedure. And as I checked off the line items, I wanted it to strike through the text to make it clearer that that step had been done.

The first thing I did was define a CSS class:

.strikethrough {
    text-decoration: line-through;
}

Then I added this JavaScript to my header file:

function strikethrough(element) {
    var $checkbox = $(element);
    if ($checkbox.prop("checked")) {
        $checkbox.parent().addClass("strikethrough");
    }
    else {
       $checkbox.parent().removeClass("strikethrough");
    }
}
$(function() {
    var checkboxCode = "<input type='checkbox' onclick='strikethrough(this)' style='margin-right: 10px' title='Mark this item done' />";
    $("li").each(function() {
        $(this).html(checkboxCode + $(this).html());
    });
});
Here is a demo on CodePen along with the source.
 
Blogger Templates