Strikethrough function not activating on list item when clicked

I have been tasked with a web development exercise as part of my course. The goal is to modify the provided files so that list items are given a strikethrough when clicked, and clicking them again removes the strikethrough effect. The "done" class in the code snippet below is meant to be used for this purpose. I have carefully reviewed my solution against the provided solutions, but despite following one of them, it doesn't seem to work. Could someone identify what might be causing the issue?

Additionally, I am aware that 'var' is considered deprecated in favor of 'let/const', but I am sticking to the course guidelines.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
    <title>Javascript + DOM</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <h1>Shopping List</h1>
    <p id="first">Get it done today</p>
    <input id="userinput" type="text" placeholder="enter items">
    <button id="enter">Enter</button>
    <ul>
        <li>Notebook</li>
        <li>Jello</li>
        <li>Spinach</li>
        <li>Rice</li>
        <li>Birthday Cake</li>
        <li>Candles</li>
    </ul>
    <script type="text/javascript" src="script.js"></script>
</body>
</html>

style.css

.coolTitle {
  text-align: center;
  font-family: 'Oswald', Helvetica, sans-serif;
  font-size: 40px;
  transform: skewY(-10deg);
  letter-spacing: 4px;
  word-spacing: -8px;
  color: tomato;
  text-shadow: 
    -1px -1px 0 firebrick,
    -2px -2px 0 firebrick,
    -3px -3px 0 firebrick,
    -4px -4px 0 firebrick,
    -5px -5px 0 firebrick,
    -6px -6px 0 firebrick,
    -7px -7px 0 firebrick,
    -8px -8px 0 firebrick,
    -30px 20px 40px dimgrey;
}

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

script.js

let button = document.getElementById("enter");
let input = document.getElementById("userinput");
let ul = document.querySelector("ul");
let li = document.getElementsByTagName("li");

function inputLength() {
    return input.value.length;
}

function createListElement() {
    let li = document.createElement("li");
    li.appendChild(document.createTextNode(input.value));
    ul.appendChild(li);
    input.value = "";
}

function addListAfterClick() {
    if (inputLength() > 0) {
        createListElement();
    }
}

function addListAfterKeypress(event) {
    if (inputLength() > 0 && event.keyCode === 13) {
        createListElement();
    }
}

button.addEventListener("click", addListAfterClick);

input.addEventListener("keypress", addListAfterKeypress);

//make item strikethough on click using CSS class
function strikeThough () {
    if (target.tagname === "li") {
        target.className.toggle("done");
    }
}

li.addEventListener('click', strikeThough);

Answer №1

It's important to develop a habit of checking the console for errors and printing out your queries for troubleshooting purposes. In regards to your question, consider that your var li is an array that contains all the elements you intend to add a click event to. You can try the following approach:

for(let i = 0; i < li.length; i ++){
  li[i].addEventListener("click", function(){
    if(li[i].classList.contains('done')){
        li[i].classList.remove('done');
    }else{
        li[i].classList.add('done');
    }
});

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting a JSON object to a string and replacing specific text can be achieved by following

I have a JSON object that I need to convert to a string and then perform substring replacements using JQuery var data = JSON.stringify(object); data = data.replace("meat", "vegetables"); console.log(data); However, when I attempt to run this code, I enco ...

Where should you position the $watch function in Angular?

Suppose I have a promise object that my page uses to retrieve data, like so: promise.then(function (data) { $scope.myData = data; }); In addition to this, I have watches on objects located elsewhere on the page. When it comes to watching data provide ...

Using useRef to update the input value

I utilized the useRef hook from React to capture an element. When I use console.log(this.inputRef), I receive this output: <input aria-invalid="false" autocomplete="off" class="MuiInputBase-input-409 MuiInput-input-394" placeholder="Type ItemCode or ...

What is the best way to make my page headers resize with a responsive layout?

Currently, I am working on a website that needs to be fully functional on both mobile devices and computers. I have successfully implemented Bootstrap-responsive to make many elements work, but now I am focusing on the hero-unit for the homepage. Specifica ...

Displaying text on an image when hovering with CSS

Exploring a tutorial on creating hover effects for images, where text appears and the background darkens. The tutorial can be found here. Encountering an issue with the hover effect - when hovering over the image, I want the entire image to darken and be ...

Tips for transferring a column in an array to an object field within an array

I have a piece of code where I need to pass values from the 'dataList' array into this.data object's 'labels' and 'datasets'-> data. When I try to directly set the values, I get an undefined result. So I created a var ...

Adjust the dimensions of all images using JavaScript

Is there a way to resize images using javascript? I attempted the following: var images = document.getElementByTagName('img') images.max_width = '100px' images.max_height = '100px' Unfortunately, it did not have the desired e ...

"Exploring the process of transferring an ID from one service to another using the select feature in Angular

I need to store the ID I receive from one service into another using the select element. Here is my approach: <select class="form-control" id="select_fac" [(ngModel)]="rep.idfac"> <option selected disa ...

``There seems to be an issue with the redirect header function in the PHP

Setting up my test site on a local host, I included an ajax request in one of my java-script files to a php script. if(hIF == "true"){ $.ajax({ type: "POST", url: "log_in/login.php", data: {name: userName, pwd: password}, ...

What techniques can I use to maximize efficiency in my code by consolidating common styles across multiple cards?

I have included my css and html code below. I am trying to apply certain styles to all the cards, while changing only the color of the top border individually for each card. I am struggling to find a way to select multiple classes at the same time. My curr ...

Exploring CouchDB through Ajax to interact with a static website

Is it feasible for my HTML static website to interact with CouchDB using AJAX and retrieve the data without relying on server-side languages like PHP or Python? The CouchDB might be hosted on a different server/domain, so JSONP would need to be utilized. ...

Modifying the 'child' node within a JSON object

Exploring the implementation of d3s Collapsible tree using a custom node hierarchy. My dataset structure deviates from the norm, for example: http://jsfiddle.net/Nszmg/2/ var flare = { "Name": "Example", "members": [ { "BName":"Ja", ...

Exploring the different pages in React js

I am currently working on implementing a button in React Js that, when clicked, should navigate to another screen. However, I keep encountering an error: TypeError: Cannot read property 'push' of undefined. I have tried various solutions but noth ...

Enhancing Image Quality upon Hovering

Is there a way to prevent the content of the article from moving when an image becomes absolutely positioned? The issue I am facing is that the image overlaps its container with overflow: hidden only when the img is absolute positioned. article { back ...

Utilizing AJAX and JavaScript to create a countdown timer for a targeted HTML element

Here's a question broken down into two parts: I am looking to incorporate some JavaScript that triggers the #refresh function in order to display a count-up timer in text format. This timer should start at 0 seconds and run up to 3 minutes before ref ...

The float right attribute doesn't stay contained within the box; instead, it drifts outside the box

I've been struggling to keep this box fixed at the top of the browser, but I'm facing an issue with the positioning on the right side. I can't seem to figure out how to solve it, so I'm reaching out for some help. #StickyBar #RightSide ...

Restoring the style on <a> renders it ineffective

Recently, I encountered an issue where the functionality of the <a> tag is lost when using this CSS code: a {all:unset;}. Does anyone have any suggestions on how to address this problem without completely avoiding the use of that particular code sn ...

What could be the reason for receiving an undefined user ID when trying to pass it through my URL?

Currently, I am in the process of constructing a profile page and aiming to display authenticated user data on it. The API call functions correctly with the user's ID, and manually entering the ID into the URL on the front end also works. However, wh ...

Managing memory in UIWebView when rendering THREE.js scenes

I am currently working on a game using THREE.js that will be embedded into a UIWebView within an iOS8 app. After analyzing the application in Chrome's developer tools, I have confirmed that there are no memory leaks present. The memory usage reaches ...

Italian calendar conversion for the react-multi-date-picker library

I recently integrated the react-multi-date-picker into my project, utilizing the multiple mode feature. However, I encountered an issue when trying to display the Italian calendar based on the language setting. Despite using locale="it", the calendar was n ...