on() click()

Today I learnt the different 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 html file will be clickable. All of the new <li> elements added to the todo list won’t be clickable:

<!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 todo 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.

Selection

One thing I notice about jQuery is how it simplifies common tasks. A good example is something you do all the time with JavaScript, select DOM elements. In JavaScript selecting all li elements would look something like this:

document.querySelectorAll( "li" );

The same selection using jQuery is like this:

$("li")

At this stage of my learning, I can’t say I see the above as a major advantage. Yes, it’s shorter but you could argue it’s also less descriptive for the reader. Brevity isn’t always a net win in code. This is especially true when tools like Emmet and other text editor tricks auto-complete a lot of code. So it’s not 100% clear to me what the advantage is.

It will be interesting as my jQuery knowledge grows if my feelings toward it change. At this early stage, I can’t help feeling sceptical. Especially when I keep hearing about frameworks like Angular and React. I guess we will see.

jQuery

What is jQuery?

jQuery is a JavaScript library designed to simplify front end web development. It is the most widely deployed JavaScript library by an insanely large margin.

Why use jQuery

There are quite a few reasons you’d want to use jQuery, or a library like it, in your project rather than vanilla JavaScript. Here are a few examples.

Ease of use

JavaScript can be a handful, jQuery can be far cleaner and more concise than the equivalent in vanilla JavaScript. Take a look at these two examples of a fade in effect:

JavaScript Fade In

function fadeIn(element) {
  element.style.opacity = 0;
  var last = +new Date();
  var tick = function() {
    element.style.opacity = +element.style.opacity + (new Date() - last) / 400;     
    last = +new Date();
    if (+element.style.opacity < 1) {
      (window.requestAnimationFrame && 
      requestAnimationFrame(tick)) || setTimeout(tick, 16);
    }   
  };
  tick();
}
fadeIn(element);

jQuery Fade In

$(element).fadeIn();

Cross browser support

Cross-browser support is one of the most difficult things about web development. jQuery normalises this so you don’t have to worry about different browsers as much.

This reason becomes less true with time. However, If you need to support older browsers, particularly anything older than IE8 then you should seriously consider jQuery.

Lots of people use jQuery

It might seem like a silly reason to use something just because loads of others are using it too. Having said that there are some real benefits to that thinking. In particular, there are plenty of resources available to help you learn and use jQuery. So if you need examples of how to do something you should have no problem finding them.

Even if you’re already a skilled developer, the practice of coding is continuous learning. So it’s always good to have a strong community around the area in which you work.

Why not use jQuery?

Based on the above you’d think jQuery would be a no brainer, and in many situations that’s true. However there are plenty of situations where it isn’t the best option, here’s why.

You can do everything without it

There is nothing in jQuery you can’t do in vanilla JavaScript. So depending on your project adding jQuery to the mix may actually be creating an unnecessary dependency. If you’re not using many of jQuery’s capabilities in your app, it pay’s to consider alternatives.

jQuery contains hundreds of methods that on many applications you’ll never use. There’s no sense in bundling all that in if you’re only using a small part of it.

People are moving away from jQuery

This one is a little contentious as depending on who you’re talking to. For a few years now there are signs that people may or may not be moving away from jQuery. Regardless, if new jQuery based projects are in decline there is such a huge existing usage of the library it still pays to learn it.