Introduction to jQuery

CC-BY-NC-4.0 / September 2019 / Loïc TRUCHOT

A JavaScript love story

in 2020

Table of content

 

  • Installation
  • Why Love and Hate about jQuery ?
  • First jQuery date
  • Who is jQuery ?
    • The DOM Master
    • The Event Catcher
    • The AJAX Slayer
  • jQuery Universe
  • What next ? 

Installation

  • Content Delivery Network (CDN)
// dans la <head>
<script 
	src="https://code.jquery.com/jquery-3.5.1.min.js" 
	integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" 
	crossorigin="anonymous">
</script>
  • Prendre le fichier, et l'utiliser comme dépendance
    • https://code.jquery.com/jquery-3.5.1.min.js
  • Le solution professionnelle
    • npm install --save jquery

Why Love and Hate about jQuery ?

Back to early 2000's

  • Web 1.0 is static and ugly
  • No W3C, no browser compatibility
  • Everyone makes fun of JavaScript
  • Frameworks are cryptic geeky tools (Dojo, Prototype, YUI)
  • Any JavaScript action costs 10 unreadable lines of code

What happened ?

John Resig choose to workout:

  • jQuery library is released
  • It's free, open source
  • It's small
  • It work with literally one line of code

Why it becomes so popular ?

  • It stops JavaScript browser compatibility nightmare
  • It stops DOM manipulation nightmare
  • It stops event-handling nightmare
  • And, of course, Programming is a pop culture
// before
var title = window.document.getElementById("page-title");
title.addEventListener("click", function(e) {
  e = e || window.event;
  var thisElement = e && e.target;
  if (thisElement) {
    var isBig = thisElement.style.textTransform === "uppercase";
    thisElement.style.textTransform = isBig ? "capitalize" : "uppercase";
  }
});

// after
$("#page-subtitle").click(function() {
  var isBig = $(this).css("text-transform") === "uppercase";
  $(this).css({ "text-transform": isBig ? "capitalize" : "uppercase" });
});

A simple DOM example

Not even complete !

// before
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.onload = () => {
  var response = JSON.parse(xhr.responseText);
  window.document.getElementById("page-title").innerText = response.title;
};
xhr.onerror = () => console.log(xhr.statusText);
xhr.send();

// after
$.get("https://jsonplaceholder.typicode.com/posts/1").then(data => {
  $("#page-subtitle").text(data.title);
});

A simple AJAX example

Not even complete !

Why it matters ?

  • JavaScript becomes reliable
  • DOM manipulation and AJAX are now intuitive and easy to learn
  • So we can create real Web Applications
  • Then Web 2.0 can begin...
  • 2020: jQuery is in 70% of all website of the WWW

Love        &&        Hate

  • Programming with visual feedback
  • Webapps
  • little scope, easy and intuitive features
  • plugins for everything 
  • No learning curve
  • Make people love JavaScript
  • web standard now implements jQuery ideas
  • often used as  framework
  • versioning nightmare
  • Not enough professional
  • well organized challengers (react, angular, vue)
  • A more global problem with programming as a pop culture 

First date with jQuery

Dom basics

// get anything by css selector
$("body");
$("#any-id");
$(".any-class");
$("tr:nth-child(even) > td");
$("input[type='button']");
// append, prepend, remove
$("#any-id").remove();
const that = $(".any-class");
that.append("<img />");
$("body").append(that);
$("body").prepend($("div.test > img:nth-child(3)"));

// change any css
$("input[type='button']").css("font-size", "20px");
$("td.dark").css({
  "background-color": "black",
  color: "white"
});

Workshop session

DOM basics

  • Add Jquery in index.html. Now, it's totally forbidden to touch HTML - index.js only !
  • Append every image in "hate" or "love" box (get them by "id", "class", and other options
  • Prepend h3 titles in boxes: "hated", "loved"
  • Remove the worst one
  • add beautiful yellow borders to your favorite
  • bonus: try 3 other maniputation methods from https://api.jquery.com/category/manipulation/

git clone https://github.com/ltruchot/jquery-introduction.git
 

To remember

  • jQuery was a revolution, that leads to web 2.0
  • jQuery is less popular since the JS framework war (react / angular / vue), but still in 75% of websites
  • jQuery is useful for
    • DOM manipulation
    • Event handling
    • AJAX requests
  • Main form of jQuery is the global function "$", like in $("#id")
  • We load jQuery just before the </body> tag, then we put our own javascript using jQuery
  • Basic methods we know: .append, .prepend, .remove, .css

Who is jQuery ?

What the DOM master can do ?

  • CRUD anything
  • Find anything, extract informations
  • Move anything
  • Copy anything
  • Transform any attribute and style
  • Animate the DOM

A function to rule them all

const $ = function(selector) {
  let element = null;
  switch (selector.charAt(0)) {
    case "#":
      return document.getElementById(selector.substr(1));
    case ".":
      return document.getElementsByClassName(selector.substr(1));
    default:
      break;
  }
  return element;
};
const test = $("#test");
console.log(test);

Really understand the dom master, from scratch...

An easy way to Create

var divEl = $('<div id="toto"></div>');
$("body").append(divEl);
// ou directement
$("#toto").append('<div id="titi"></div>');
$("#toto").prepend('<div id="tutu"></div>');
// after, before
$('<div id="tete"></div>').appendTo("#tutu");

An easy way to Update

console.log($("#tutu").text(), $("#tutu").html());
$("#tutu").html("<span>aurevoir</span>");
console.log($("#tutu").text(), $("#tutu").html());
$("#tutu > span").text("adieu");
console.log($("#tutu").text(), $("#tutu").html());

An easy way to Remove

$("#toto").remove();
$("#tutu").empty();

Workshop

  • Créer un formulaire 100% avec JQuery
  • Nom, prénom, tel, email + bouton envoyer
  • Ajouter une étoile à la fin de chaque input, en une seule ligne de code
  • Modifier "envoyer" en "save" avec JQuery
  • Supprimer le champ "tel" avec JQuery
  • Bonus: Vider tout le body quand on click sur "save"

alternative...

Workshop

  • Reprenez votre tamagochi
  • utiliser "setInverval" pour faire apparaître une crotte toutes les 10 sec. 
  • Un bouton "clean" permet de nettoyer les crottes de l'ecran du tamagochi
  • Il y a un compteur de "nettoyage" qui augmente de 1 pour chaque crotte nettoyée
  • Le bonheur du tamagochi commence à 100% et baisse de  0.1% par seconde. 
  • Le nettoyage remonte le bohneur de 1%
  • Bonus: Un bouton play remplace l'image du tamagochi par un nouveau gif rigolo temporaire et augmente le bonheur de 2%... au bout de 5 sec. ça revient à la normale

Tamagochi revival

Find

Copy

$('#tutu').find("span");
console.log($("span").parent());
$("span").closest("div");
console.log($("#tutu").siblings())
var newTutu = $('#tutu').clone();
$("body").append(newTutu);
$("#toto").clone().appendTo("#tutu");
  • A lot of method to find anything
  • Using css selectors
  • Always based on family members
  • one way to clone deep

Iterate

$('#toto > div').each(function () {
    $(this).text("coucou");
});
  • one way to iterate over results
  • with a confusing "this"

CRUD css

  • JQuery is your friend for any kind of visible event and animation
  • But always choose CSS animation if possible
console.log($("h1").css("font-size"));
$("h1").css("font-size", "12px");
$("h1").css({"font-color": "blue", "text-transform": "uppercase"});

CRUD attributes

  • you have the control of all attribute with .attr
  • there is more specific choices for css classes
  • removeAttr, removeClass
console.log($("input").attr("type"));
$("input").attr("type", "number");
$("<img />").attr({
    src: "/resources/hat.gif",
    alt: "jQuery Logo"
  });
$("h1").addClass("hidden");

Workshop

  • Créer un backround bleu
  • Ajouter des poissons et des algues à différents emplacements
  • Cloner ces entités pour remplir mieux votre aquarium
  • Animer un poisson avec setInterval, en changeant son CSS chaque dixième de seconde
  • Trouver chaque poisson pour lui faire dire "je suis un poisson", à côté de son image
  • Bonus: animer tous vos poissons, rendre aléatoire leurs positions de "spawn", leurs directions et leurs vitesses...

L'aquarium

Back to JavaScript

  • Ne pas confondre JQuery et JavaScript
  • Ne pas désapprendre JavaScript ($ or not $)
  • JQuery est une librairie, pas un framework
  • Si react ou angular ou vue: pas besoin de JQuery
  • En conditions réelles, JQuery se charge plutôt via NPM
  • --> retour à parcel

Workshop

En 1202, Fibonacci décrit l'évolution d'une population de lapins. Il remarque que chaque mois leur nombre augmente: pour chaque couple de lapin fertile existant, il y a un nouveau couple qui naît... et qui sera fertile dans 1 mois !

Les lapins de Fibonacci

  • Trouvez une image de lapin sur internet
  • Un mois représente 3 secondes
  • Chaque mois, créez des div de classe "lapin" de 50x50px avec cette image en background, en fonction du nombre de lapin qui doivent naître (utiliser setInterval)
  • Leurs positions doit être absolue et aléatoire dans 800x600px
  • Combien y-a-t'il de couples après 2, 3, 4, 5, 6, 12 mois ? 
  • Bonus: Si un lapin apparaît sur un autre, le changer de place

Animation

  • The final power of the DOM master
  • A series of common tools
  • And a generic and deep animation method
$("h1").hide();
$("h1").fadeIn(3000);
$("h1").animate(
  {"margin-top": "100px"}, 
  1000
);
$("h1").fadeOut("fast", function() { 
    $(this).show() 
});

Workshop

  • Faites un slideshow avec 5 photos
  • Les images défilent régulièrement de gauche à droite
  • Lorsqu'on click sur une image, elle s'affiche avec un effet de fade-in dans une popup
  • Lorsqu'on click sur la popup, elle fade-out

🠣 Alternative 🠣

Workshop

  • Au premier clic sur les rideaux, ils s'ouvrent sur un théâtre de marionette
  • Les personnages arrivent (fadeIn ? show ? animate ?)
  • Ils commencent à discuter...

To remember

  • JQuery is not magic, it's just a big JavaScript function
  • jQuery is perfect to manipulate the DOM
  • manipulation methods: append, prepend, empty, remove
  • read or update methods are often 1 vs 2 args: html, text
  • attributes and styles methods work like that too: attr, css
  • JQuery is not JavaScript

The event catcher

  • Mouse
    • click, mouseover...
  • Keyboard
    • keyup, keydown...
  • Form
    • select, focus, change...
  • Window
    • scroll, resize...

Listen regular JS events....

...and even more (hover, toggle) 

With 3 listener options :

on, off, one

That's it !

Know your JS events and you know everything

  • Don't forget to remove your events when you remove your elements
  • the method without parameters trigger the function, there is a "trigger" method too
  • special event "toggle", and even "hover"
  • special event "ready" 

Workshop(s)

You have

all the keys

You can do anything you want

  • propose a workshop that implies event + dom transformations
  • examples:
    • whack a mole
    • cascading selects
    • gamebook
    • your project

The AJAX Slayer

Long before axios...

  • ...jquery used to provide us some AJAX
  • A lot of stuff but only 3 matters
    • $.ajax
      • $.get
      • $.post
  • A LOT of callbacks (done, but...
    • use only .then(...), AKA the promise
      • and .catch(...)
  • It usually returns a plain JSON object
  • Simpler, but no metadata

When JQuery shows limits

  • Some servers needs some specific HTTP "headers"
  • JQuery don't create those headers smartly
  • Here is an example of different steps needed to ensure a POST of JSON
  • A LOT of configurations can be chosen:
  • Use Axios or Native fetch if needed
$.ajax({
  contentType: 'application/json',
  url: 'https://mini-json-server.committers.ngo/livres',
  dataType: 'json',
  data: JSON.stringify(data),
  type: 'POST',
})
  .then(() => $.get('https://mini-json-server.committers.ngo/livres'))
  .then(console.log);

Workshop

  • Une API collective, pour des livres sur l'informatique
  • Les livres sont recommandé via un accompte github
  • Alimentez/la avec au moins deux livres (l'ISBN est l'ID unique, userID est l'accompte github)
  • Allez cherchez vos 3 livres préféré avec un Promise.all()
  • Affichez les sur la page

Workshop

  • seed fontawesome/bootstrap
  • Assembler bds dans format JSON décidé collectivement
  • Requêter JSON via AJAX
  • Afficher titres, auteurs, images des bds

La bdthèque

  • Chaque livre à un lien "en savoir plus" - cliquer dessus montre le résumé, la date de parution, etc, re-cliquer cache
  • Un panier en haut à droite nous suit dans la navigation
  • Glisser déposer l'image d'un livre dans ce panier le cache
  • Cliquer sur le panier l'agrandi, un bouton d'emprunt fonctionne
  • Les livres empruntés ne s'affichent plus
  • Un bouton "rendre les livres" permet de les retrouver
  • Enregistrer les utilisateurs, et leurs livres empruntés
  • slideshow suggestion livres  empruntés par amis avec même goût
  • CRUD admin 

JQuery

Universe

JQuery UI

  • Official user interface plugins on top of JQuery
  • All what you need:
    • Accordion
    • Autocomplete
    • Button
    • Checkbox
    • Datepicker
    • Dialog
    • Slider
    • etc
  • Import or src, then use
  • CSS should be added too
import "./styles.scss";
import $ from "jquery";
import drag from "jquery-ui/ui/widgets/draggable";
import drop from "jquery-ui/ui/widgets/droppable";
$("#drag").draggable();
$("#drop").droppable({
    drop: function(event, ui) {
        ui.draggable.empty();
        $(this).css("background-color", "red")
    }
});
  <body>
    <div id="drag">drag</div>
    <div id="drop">drop</div>    
  </body>

Workshop(s)

You have

all the keys

You can do anything you want

  • Implements any JQuery UI element in your app
  • examples:
    • Confirmation dialog
    • Progress bar with a setInterval
    • 2 datepickers to select a period
    • your project

Rich, but old

  • A plugin for everything
  • Often outdated
  • Sometimes needs an old version of JQuery
  • Sometimes, not ES6 « importable »
    • noop import
    • or pure HTML import
  •  
  • sources:
  • Two rules
    • Don't pick a plugin without commit since 3y+
    • Don't pick a plugin for a 2.x or older version of JQuery
import 'summernote';
<script src="jquery.flot.js"></script>

Workshop

JQuery plugins

What's next ?

  • Play with querySelector, css animations, fetch and other new native features
  • You are ready for the descendants of JQuery:
    • Pure ES6 libs & frameworks to control the data, the dom, the navigation and AJAX
  • Don't forget JQuery for simple project or POCS
  • JQuery is a good match with PHP or CMS too

THANK'S EVERYONE
It's finally done ! See you soon

Indroduction to JQuery in 2020

By Loïc TRUCHOT

Indroduction to JQuery in 2020

Indroduction to JQuery

  • 527