Today I learned the difference between the on("click")
and click()
methods in jQuery.
click()
only adds listeners for existing elements, so it will completely ignore any dynamically added items. So, in the example below only the <li>
declared in the <li>
elements added to the
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<link rel="stylesheet" type="text/css" media="screen" href="assets/css/style.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr"
crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</head>
<body>
<div id="container">
<h1>To-Do List</h1>
<input type="text" name="" id="">
<ul>
<li><span>X</span> Go to potions class</li>
<li><span>X</span> Buy a new broom</li>
<li><span>X</span> Visit Hagrid</li>
</ul>
</div>
<script type="text/javascript" src="assets/js/script.js" charset="utf-8"></script>
</body>
</html>
// check off specific todos by clicking
$( "li" ).click( function () {
$( this ).toggleClass( "completed" );
} );
// click on x to delete todo item
$( "span" ).click( function ( event ) {
$( this ).parent().fadeOut( 300, function () {
$( this ).remove();
} );
event.stopPropagation();
} );
// add new item to todo list on keypress
$( "input[type='text']" ).keypress( function ( event ) {
if ( event.which === 13 ) {
var todoItem = $( this ).val();
$( this ).val( "" );
$( "ul" ).append( "<li><span>X</span> " + todoItem + "</li>" );
}
} );
To get around this, instead of using click()
we use on("click")
. Unlike click()
, on("click")
will add listeners for all potential future elements on the page. This makes all the dynamic content, like the new items in our to-do list app, work flawlessly. So the updated code would look like this:
// check off specific todos by clicking
$( "ul" ).on( "click", "li", function () {
$( this ).toggleClass( "completed" );
} );
// click on x to delete todo item
$( "ul" ).on( "click", "span", function ( event ) {
$( this ).parent().fadeOut( 300, function () {
$( this ).remove();
} );
event.stopPropagation();
} );
// add new item to todo list on keypress
$( "input[type='text']" ).keypress( function ( event ) {
if ( event.which === 13 ) {
var todoItem = $( this ).val();
$( this ).val( "" );
$( "ul" ).append( "<li><span>X</span> " + todoItem + "</li>" );
}
} );
jQuery has some excellent documentation. So, if you need to drill into the specifics of any particular method (like on() or click()) be sure to RTFM.