Ad

$(this).addClass Is Not Working

- 1 answer

While following a tutorial, I see style sheet is not applied to clicked element in the list. What Could be the possible reason?

The following sample works this way if some string is added to text box and then button is clicked, a new item gets added to list. If item in the list is clicked it should be stroked through.

<!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);
            });

            // following statements 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>
Ad

Answer

As mentioned by ceejayoz . The live() function was removed in jQuery 1.7 and does not exist at all in jQuery 2.x.

The reason your click on the list was not working is better explained on this question: Click event on dynamically generated list items using jquery

here's what the code could look like for you

$(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" />

Ad
source: stackoverflow.com
Ad