The function $(this).addClass() seems to be malfunctioning

While trying to follow a tutorial, I noticed that the style sheet isn't being applied to the clicked element in the list. What could be causing this issue?

In the example provided, when a string is added to the text box and the button is clicked, a new item is added to the list. If an item in the list is clicked, it should have a strikethrough effect.

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#taskText').keydown(function (evt) {  
                if (evt.keyCode == 13) {
                    addTask(this, evt);
                }
            });

            $('#addTask').click(function (evt) {
                addTask(document.getElementById('taskText'), evt);
            });

            // The following statements are not working 

            $('#tasks li').live('click', function(evt) {
                $(this).addClass('done');

            });});

        function addTask(textBox, evt) {
            evt.preventDefault();
            var taskText = textBox.value;
            $('<li>').text(taskText).appendTo('#tasks'); 
            textBox.value = "";
        };
    </script>
    <style type="text/css">
        .done{
            text-decoration:line-through;
        }
    </style>
</head>
<body>
   <ul id="tasks">
   </ul>
    <input type="text" id="taskText" />
    <input type="submit" id="addTask"/>

</body>
</html>

Answer №1

The live() method has been deprecated in jQuery 1.7 and completely removed in jQuery 2.x.

If you inspect your browser's developer console, it is likely that you will encounter an error message related to this change.

Answer №2

 $(document).ready(function() {
   $('#addTask').click(function() {
     var taskText = $('#taskText').val();
     var li = $('<li>' + taskText + '</li>');
     $('ul#tasks').append(li);
     $('#taskText').val('');
     $(li).click(function() {
     $(this).toggleClass('done');
     });
   });
 });
li {
  font-family: arial;
  -webkit-font-smoothing: antialiased;
  -moz-font-smoothing: antialiased;
}

.done{
   text-decoration: line-through;
   color: red;
}
<!DOCTYPE html>    
<html lang="en">
  <head>
    <meta charset="utf-8>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  
</head>    
<body>
  <ul id="tasks">
    <!-- List Goes Here... -->
  </ul>

  <!-- Textbox / Input Buttons -->  
   <input type="text" id="taskText" />
   <input type="submit" id="addTask"/>

</body>
</html>

Answer №3

$('.items-container div').on('click', function(){
     $(this).addClass('active');
});

This code should be effective. Double-check your syntax to ensure there are no unnecessary semicolons or errors.

Answer №4

ceejayoz pointed out that the live() function was deprecated in jQuery 1.7 and completely removed in jQuery 2.x.

If you're having trouble with your list click event, you can find a more detailed explanation on this post: Click event on dynamically generated list items using jquery

Here's an example of how your code could be structured:

$(document).ready(function() {
  $('#taskText').keydown(function(evt) {
    if (evt.keyCode == 13) {
      addTask(this, evt);
    }
  });

  $('#addTask').click(function(evt) {
    addTask($('#taskText'), evt);
  });


  $('#tasks').on('click', 'li', function(evt) {
    $(this).addClass('done');
  });
});

function addTask(textBox, evt) {
  evt.preventDefault();
  var taskText = textBox.val();
  $('<li>').text(taskText).appendTo('#tasks');
  textBox.val("");
};
.done {
  text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="tasks">
</ul>
<input type="text" id="taskText" />
<input type="submit" id="addTask" />

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

Performing several asynchronous requests using jQuery based on the number of child div elements within the current-items class div

HTML CODE <form id="product_form" action="" method="post"> <input type="hidden" name="wpsc_ajax_action" value="add_to_cart"> <input type="hidden" name="product_id" value="8191"> <div class="current-items" ...

When it comes to using brackets and HTML, I keep receiving an error message indicating that there is no index file

I'm having trouble with this code - it works fine in Code Academy, but I am new to HTML and trying to practice outside of the platform. Every time I try to live preview in Brackets, I get an error message saying "make sure there is an html file or tha ...

Delivering compressed files in a React server

Having some trouble serving a gzip compression of my bundle.js file in React. Have tried reducing the size with uglify and dedupe, but only saw a small decrease from 2.9mb to 2.6mb. Using the compression plugin now outputs a gzip file, however, still servi ...

How to programmatically unselect an ng-checkbox in AngularJS when it is removed from an array

Utilizing checkboxes to gather values and store them in an array for dataset filtering purposes. The objectives are as follows: Show child filters when parent category is selected. Unselect all children if parent is unselected (otherwise they will ...

Reformat an array containing objects so that their structure is changed to a different format

Imagine a scenario where the data needs to be manipulated into a specific format called 'result' for easier display on the user interface. In this 'result', the month numbers are used as keys, representing each month's quantity. co ...

IE8 not displaying background-image in Zen Subtheme of Drupal 7

I've been struggling to get my website to display properly across all browsers. Everything looks great except for IE8 and below. I'm not sure if it's a problem with Drupal, Zen, IE, or CSS (although the CSS code seems correct). Here is the C ...

What is the best way to insert an <image> tag into the SVG DOM?

Currently, I am facing an issue with adding a background image to the generated SVG DOM in my web page. The user interacts by drawing an SVG doodle on top of a jpg image using Raphael. After the user is done with their drawing, I want to enable them to sa ...

In what way can you establish a boundary for a border?

My goal is to create a 10x10 grid with randomly placed black boxes, but I am facing an issue in my game setup: Currently, the 5 black boxes are generated randomly in a row, sometimes exceeding the border and breaking the continuity. I would like to establ ...

What is the method to exhibit the outcome of a promise on a web page within a React component?

In my search for information about promises, I have noticed that most articles provide examples using console.log. However, I am faced with a different scenario. I am working with AWS Athena and I need to display the result on a webpage in my React export. ...

Guide to incorporating flash into a form similar to the method used on http://www.mediafire.com

I'm looking to integrate a flash upload feature into my index file, but I'm not sure how to do it. Here is the link to the flash uploader: . I want it to work similar to how uploading works on when you click on UPLOAD. Thank you for any assistan ...

Laravel error message for unresolved symbolic link

Previously, I had developed a form for uploading profile pictures using the code snippet below, $image = $request->file('avatar'); $pass = Hash::make($request->password); if($image!=null){ $avatar_na ...

What steps can be taken to enhance the responsiveness of this Bootstrap 4 code?

I've been trying to make this code more responsive, but I haven't found a suitable solution yet. When the browser window shrinks to mobile sizes, the list becomes too narrow and the picture/video items on the right end up small and aesthetically ...

What is the best way to send the totalAmount data from one child component to its parent, and then pass it on to another

I am facing an issue with passing the totalAmount data from cart.js to the parent component (app.js) and then further to another child component (info.js). Despite my attempts, it seems like I am unable to pass it correctly as I encounter the following err ...

Is there a way to divide text in half while preserving the HTML structure?

I am in need of setting up an RSS feed where only a portion (or a specified number of characters) of the article's text is displayed, while keeping all HTML tags intact (such as images or YouTube videos). For instance, what should happen if the chara ...

How can you use JavaScript to create hyperlinks for every occurrence of $WORD in a text without altering the original content?

I've hit a bit of a roadblock. I'm currently working with StockTwits data and their API requires linking 'cashtags' (similar to hashtags but using $ instead of #). The input data I have is This is my amazing message with a stock $sym ...

How can I position a form next to a title when utilizing the Bootstrap Panel feature?

I have experimented with multiple solutions found on various sources, but unfortunately none have been successful. I came close to achieving the desired result, but encountered an issue with the panel's default background color not displaying properly ...

Navigating through various features in nodejs / expressjs

Managing multiple functions in nodejs/expressjs can be a bit confusing for those used to PHP. In PHP, you simply call one function after another, but in node, things work differently with callbacks and potential errors related to undefined variables. Her ...

Using .attr() to change the 'id' in jQuery will not be effective

Initially, the code has been streamlined to include only the necessary components. Here is the HTML file (single_lesson.html) in question: <tr class="my_lessons"> <td> <select name="my_von" id="my_von"></select> &l ...

Discover the steps for dynamically adding a new row in an Angular application

I am trying to add new rows to a table in Angular, but I'm having some trouble. Initially, there is one empty row, and when I click on the "add new" button after entering details, a new row should be added. I was able to do this using jQuery, but I&ap ...

Tips for passing an array between components in Angular 2

My goal is to create a to-do list with multiple components. Initially, I have 2 components and plan to add more later. I will be sharing an array of tasks using the Tache class. Navbar Component import { Component } from '@angular/core'; impor ...