jQuery

Things we're going to cover:

  • jQuery
  • jQuery Plugins

Native JavaScript vs. JQuery

  • Javascript has been built upon rapidly.
  • It is very basic and awkward on some levels (although it's getting better)
    • getElementsByClassName
      • Appending and removing classes
  • Common tasks require you to recode every time (tasks like AJAX, or DOM Manipulation)

WOULDN'T IT BE GREAT IF SOMEONE WROTE A LIBRARY OF PRE-MADE FUNCTIONS THAT WAS EASY TO USE??

JQuery

What is jQuery

  • Facade Language
  • Created by John Resig in 2006
  • Common js tasks
    • DOM manipulation
    • AJAX
    • Animation
    • Data handling
  • WRITE LESS, DO MORE!!

javascript

jQuery

//Add and remove a class
function addClass( classname, element ) {
    var cn = element.className;
    //test for existance
    if( cn.indexOf( classname ) != -1 ) {
        return;
    }
    //add a space if the element 
    //already has class
    if( cn != '' ) {
        classname = ' '+classname;
    }
    element.className = cn+classname;
}

function removeClass( classname, element ) {
    var cn = element.className;
    var rxp = new RegExp( "s?b"+classname
             +"b", "g" );
    cn = cn.replace( rxp, '' );
    element.className = cn;
}

var myElement = document
    .getElementByID('myEl');

addClass('active', myElement);
removeClass('idle', myElement);
//with jQuery
$('#myEl')
    .addClass('active')
    .removeClass('idle');

You might not need jQuery

jQuery adds 87Kb (compressed) to the page, meaning a 87 ms delay in loading plus 1/6 blocking

HOW TO INCLUDE JQUERY

You can:

So, in your HTML page:

<script src="https://cdnjs.cloudflare.com
    /ajax/libs/jquery/3.3.1/jquery.js"></script>

<script src="./scripts/main.js"></script>

Make sure to use the right version of jQuery:

  1. Is for legacy browsers
  2. Obsolete (Check browser support)
  3. USE THIS ONE

Make sure you put your script afterwards!!

Full Docs

The $

  • The full library is loaded as one function that sits in the window object
  • The function is called jQuery
  • When you call the function you can say jQuery()
  • But for brevity you can also say $()

Getting it to load when the Document is ready

$(function(){
    //Your code goes here...
});
  • In order to use jQuery properly we need the browser to load all the html & css first. When the DOM is fully loaded and ready to be used it uses its ready method to fire an onDOMReady handler. This is slightly different from DOMContentLoaded listeners, as it will still fire if the event is emitted before the code is loaded...
  • There are various forms, like $(document).ready(handlerFn); , use the one below, unless you really like typing for no reason.

The Two Phases of JQuery

$("p");
$("ul li");

Phase 1: Select Element(s)

  • jQuery uses sizzle to select elements, meaning that you can pass it a string that looks like a css selector to target those elements
    • Select (pick up) by element
  • Select By Class
$(".myClass");

$(".myClass p");

$(".myClass .myChildClass");

The Two Phases of JQuery

$("#myDiv");

Phase 1: Select Element(s)

  • select by ID

There are lots of combinations

The Two Phases of JQuery

$("#dropdown-menu").slideUp();

$(".my-icons").fadeOut();

Phase 2: Manipulation

  • Use any of jQuery's functions on it

The Two Phases of JQuery

$("#dropdown-menu")
    .slideUp().fadeOut()
    .parents(".myParent")
    .slideUp().end().fadeIn();

Phase 2: Manipulation

  • To quote the internet: "When using jQuery, CHAIN LIKE A B*TCH!!"

The Two Phases of JQuery

$("#myDiv").show();
$("#myDiv").css({
    color: "red"
});
$("#myDiv").slideUp();

Phase 1: Select Element(s)

RE-QUERY

When you call the jQuery main function on an element it is EXPENSIVE. It takes ALL the measurements required for ALL the functions. If you do that repeatedly (as above) then it slows your code down.

The Two Phases of JQuery

var $myDiv = $("#myDiv");

$myDiv.show().css({
    color: "red"
}).slideUp();

Phase 1: Select Element(s)

RE-QUERY - solved

This is called caching. We measure once and save as a variable. By convention (to remind us we've measured it once) we put a $ before the variable name.

DOM Traversal

$("#myContainer")
.parents(".main-container")
.children("ul")
.find("li");

JQuery measures the first element, then you can use functions like the above to move around the DOM and find things, filtering elements out as it goes.

To go back to the before you used the last filter use the .end() method.

Show/Hide

//To show and hide an element(s) we can do

var $els = $('.myEls');

//separately
$els.show();
$els.hide();
$els.toggle();

$els.fadeIn();
$els.fadeOut();
$els.fadeToggle();

$els.slideDown();
$els.slideUp();
$els.slideToggle();

Class Manipulation

//To show and hide an element(s) we can do

var $els = $('.myEls');

//separately
$els.addClass('on');
$els.removeClass('on');
$els.toggleClass('on');

Event Bindings

var $redLightControl = $('#red-light-control');

$redLightControl.on('click.onOffToggle', function($e){
    var $redLights = $('.light.stop');
    $redLights.toggleClass('on');
    return false;
});

Notes:

  1. USE the 'ON' function
  2. Namespace your events, like: 'click.onOffToggle', so you can remove them independently
  3. In event handlers the this keyword refers to the element clicked
  4. return false - prevents default and bubbling.

Programatically Trigger an Event

var $redLightControl = $('#red-light-control');

$redLightControl.trigger('click.namespace', extraData);

Notes:

  1. .trigger() an event on an element.
    1. There's .triggerHandler() which has some differences, like not triggering the underlying event. (see docs for more)

JQuery Plugins

JQuery Plugins are pre-made software.

 

They are loaded into jQuery to be executed later!

How to write your own

Using Plugins

Pick up the element and call the function...

// jQuery plugins are extra peices of code that use jQuery to accomplish a task.
// To keep things in order jQuery generally insisted that they follow the same pattern

//STEP 1 - Find the DOM node you want to fire it on

//STEP 2 - call that function! So...

$('body').masonry();

$('ul.gallery').lightBox({
    pagination: true,
    easing: 'ease-out'
});

// Sites will often have a GitHub repository with instructions, or a dedicated website, 
// if in doubt...

List of jQuery Plugins for Exercise