user4110586
user4110586

Reputation:

CSS/JS Checked checkbox should "line out" an <li> element in a To Do List Application

Im creating a classic To Do list application in html/JS/CSS, where i have the following functionality :

How can i solve the following problem, using ONLY css :

When the user checks the checkbox, the task on the corresponding line should be "lined out" so that it becomes clear that its completed.

I made a jsfiddle, but i cant make it run there, anyway here it is: https://jsfiddle.net/fm6cbuu9/2/

What i have so far :

JS :

var tasks = {}


function addTask(){
var task = document.getElementById("inn").value
var ol = document.getElementById("ol")
var li = document.createElement("li")
var d = new Date()
var box = document.createElement("input")
        box.type = "checkbox"
        box.id = "box"

li.appendChild(box)
li.appendChild(document.createTextNode(task))
ol.insertBefore(li, ol.childNodes[0])

tasks[d.getTime()] = task
console.log(tasks)

}

CSS:

input[type=checkbox] + li {
text-decoration: overline;

}

HTML:

<body>
<div id="container">
    <div id="inner">
        <h1> To Do List </h1>

        <form id="skjema">
        Enter Task: <input type="text" id="inn" required="true">
                    <button type="button" onclick="addTask()"> Submit Task       </button> <br>
        Count task: <input type="text" id="ut" disabled="true">
        </form>

        <ol id="ol">

        </ol>
    </div>
</div>

Upvotes: 1

Views: 787

Answers (1)

Kodie Grantham
Kodie Grantham

Reputation: 2041

Rather than creating a text node for the task name, put it inside of a label for the checkbox. Then you just target the label next to the checked box in your CSS:

var tasks = {}

window.addTask = function(){
	var task = document.getElementById("inn").value;
	var ol = document.getElementById("ol");
	var li = document.createElement("li");
	var d = new Date();
	var taskId = d.getTime();
	var box = document.createElement("input"); 
		box.type = "checkbox";
		box.id = "box-" + taskId;
	var label = document.createElement("label");
		label.setAttribute("for", "box-" + taskId);
		label.innerHTML = task;

	li.appendChild(box);
	li.appendChild(label);
	ol.insertBefore(li, ol.childNodes[0]);
	
	tasks[taskId] = task;
	console.log(tasks);
}
#container {
	display: block;
	margin-right: auto;
	margin-left: auto;
	background-color: lightgray;
	border-radius: 10px;
	width: 800px;
	height: auto;
	z-index: 0;
	padding: 20px;
}

input[type=checkbox]:checked + label {
	text-decoration: line-through;
} 
	<title>To do list</title>

<body>
	<div id="container">
		<div id="inner">
			<h1> To Do List </h1>
			
			<form id="skjema">
			Enter Task:	<input type="text" id="inn" required="true">
						<button type="button" onclick="addTask()"> Submit Task </button> <br>
			Count task:	<input type="text" id="ut" disabled="true">
			</form>

			<ol id="ol">
			
			</ol>
		</div>
	</div>
</body>

Upvotes: 1

Related Questions