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

What is the best way to ensure that my drop down select menu consistently displays the same data even after performing a query with the menu?

Hey there! I'm facing a little hiccup with a drop-down selection box. Here's what I'm trying to do - get someone to log into a database, and then display all available tables in the selection box. Once they choose a table, they hit select an ...

Animation of active chat list items on Whatsapp

Has anyone figured out a simple method to create an animation like the one in Whatsapp? For example, when you are on a chat screen and go back to the chat list, have you noticed how an active element is briefly highlighted in gray (to indicate which chat ...

Angularjs displays an error message stating, "Unable to assign value to property that is undefined"

Whenever I try to set a property, I encounter an error message stating "cannot set property of undefined". vm.dtr1 = {}; // Could it be that I have incorrectly initialized this? vm.dtr1.date1 = {}; // Could it be that I have incorrectly initialized this ...

Dynamic HTML gallery that supports the addition of fresh images

Looking to showcase images from a local folder in a slideshow on a simple web page? The page should automatically update when new images are added or removed from the folder. I am not an expert and prefer a minimalist design with perhaps just a transitio ...

Issue with buttons not being properly localized in mvc4 application

After successfully localizing labels, titles and error messages in my application, I encountered an issue with the localization of buttons within a jtable. Despite defining the messages property in the jtable.js file, the buttons were not getting localized ...

Adjusting the view of an OpenLayers3 map to encompass various vector layers

My OpenLayers3 map includes an OSM Tile layer and one or more Vector layers. I have a function that allows me to zoom into a single layer successfully: vector.addEventListener("change", function() { map.getView().fitExtent(vectorSource.getExtent(), ma ...

Issues with CSS rendering have been observed following an ajax update when using the <ui:repeat> tag

This scenario is a bit intricate. Essentially, I am utilizing Material Design Lite CSS provided by Google and triggering an AJAX request to dynamically add input fields using PrimeFaces. <h:commandLink value="+ Add something> <f:ajax listener ...

Trouble with Styling React-Toastify in TypeScript: struggling to adjust z-index in Toast Container

Currently in the process of developing a React application utilizing TypeScript, I have incorporated the React-Toastify library to handle notifications. However, encountering some challenges with the styling of the ToastContainer component. Specifically, ...

Transferring information to the controller and refreshing the interface (Single-page design)

I'm stuck on a personal project and could really use some help. If anyone has any feedback, it would be greatly appreciated. Thanks in advance. In my index.php file, I have a div with the id main-container. Inside this container, there are two separa ...

Employing bootstrap to include oversized images within a compact, fixed div

I am facing an issue with image responsiveness in the middle row of my layout. Despite using Bootstrap 4 and applying classes like img-fluid, the images in my #fullColumn area do not resize properly. The images are dragged into this area by users and are ...

Implementing jQuery to dynamically add a class when the value of a jQuery spinner is changed

The task I have completed: $( function() { var spinner = $( '#spinner' ).spinner({ min : -1, max : 1, spin : function( event, ui ) { console.log( ui.value ); } }); }); <input id= ...

html interactive/expandable tree

I've come across this code which generates an HTML tree, but I'm facing an issue where the tree expands every time I refresh the page. What I want to achieve is to have certain branches expanded and others collapsed when the page is opened, depe ...

Creating Secure JWT Tokens

Hello there! I'm currently in need of assistance with generating JWT tokens that include three headers: alg, kid, and typ. The format I am looking for is as follows: { "alg": "RS256", "kid": "vpaas-magic-cookie-1 ...

Pass along computed style data to the parent component in Vue.js

I am relatively new to VueJS and currently in the process of exploring its features. One specific issue I am facing on my website involves a TopBar component that includes both the logo and the menu. <template> <div id="topBar"> <div ...

Managing component composition in React/TypeScript: What's the best way to approach it?

I am brand new to the world of typescript, so please be patient with me. My objective is to transform this react component: interface ButtonProps {...} const Button: React.FC<ButtonProps> = ({ children, href, value as = 'button', ...

In AngularJS, how can you filter the ng-repeat value by clicking on a checkbox field?

Hey there, I'm looking to filter the ng-repeat value when a checkbox is clicked. Check out my Plunker here. By checking the checkbox labeled Role block, it should only show elements with roles value of "block". Similarly, by checking the checkbo ...

Elevate the value within a function and refresh the said function

I'm currently facing a challenge with this particular piece of code, let spin = new TimelineMax(); spin.to($('.particle'), 150, { rotation: 360, repeat: -1, transformOrigin: '50% 50%', ease: Linear.easeNone }); Th ...

Error: Material-UI prop type validation failed - Please specify either `children`, `image`, `src`, or `component` prop

Despite having an image prop in CardMedia, I kept encountering this error. Here is a snippet of the code: Error description: const Post = ({ post, setter }) => { const classes = useStyles(); return( <Card className={classes.card} ...

Issue with breakpoints functionality in MUI v5 and React project

I've been attempting to utilize breakpoints for responsive design on my website, but unfortunately, it doesn't seem to be working correctly. Every time I implement a breakpoint, the entire page goes blank. Below is the code snippet I am working w ...

A Guide to Configuring jQuery UI Slider with Three Distinct Colors

I'm currently implementing the UI Slider on my website. However, I would like to customize the slider with three different colors: Handle Color Previous portion of Handle Next portion of Handle I want it to look something like this: Currently, I h ...