<info 343/>

jQuery and

Other Libraries

Joel Ross
Autumn 2016

View of the Day

  • Homework check-in

  • JavaScript Libraries

  • jQuery

  • Lodash

  • Bootstrap JS

Tip: Variable Type Names

Even though variables are loosely typed, the data type of a value is still important! In order to help keep track of the type of each variable in JavaScript, include the type in the variable name:

//parameter is a String
function countLetters(textString) {

  //split String into Array
  var wordsArray = textString.split(' ');

  //reduce Array into Number
  var totalNum = wordsArray.reduce(function(countNum, itemStr){
    return countNum + itemStr.length();
  }, 0);

  return totalNum;
}

JavaScript Libraries

Lots and lots of people have created JavaScript libraries full of helpful functions to make specific programming tasks easier. 

Framework vs. Library

Inversion of Control is a key part of what makes a framework different to a library. A library is essentially a set of functions that you can call, these days usually organized into classes. Each call does some work and returns control to the client.

A framework embodies some abstract design, with more behavior built in. In order to use it you need to insert your behavior into various places in the framework either by subclassing or by plugging in your own classes. The framework's code then calls your code at these points.

 

- Martin Fowler

jQuery

jQuery is a predefined set of JavaScript methods for manipulating the DOM.

just a js file!

minified file

Include this before your own script!

<!-- load jQuery -->
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
//version 3.x is new (modern browsers)
//version 2.x is for IE 9+; otherwise version 1.x

This creates a jQuery variable in global scope

jQuery Selector

//selects element with id="foo" (e.g., <p id="foo">)
var fooElem = jQuery('#foo'); 

//selects all <a> elements (returns an array)
var allLinksArray = jQuery('a');

Use the jQuery() function to select DOM elements. The parameter is a CSS selector String (like querySelector()).

More common to use the $() shortcut alias:

//selects element with id="foo" (e.g., <p id="foo">)
var fooElem = $('#foo'); 

//selects all <a> elements (returns an array)
var allLinksArray = $('a');

jQuery Selector

$('#my-div') // by id
$('div') // by type
$('.my-class') // by class
$('header, footer') // group selector
$('nav a') // descendant selector
$('p.red') // scoped selector

$('section:first') // first <section> element
                   // not a css selector!

jQuery handles most all CSS selectors, as well as some additional pseudoclasses

jQuery Methods

but first...

VS Code Typings

VS Code supports Intellisense (autocompletion) for external libraries like jQuery. But you have to set it up.

First, create a .jsconfig file in your project.

  • Open the entire folder in VS Code
  • Open up a .js file
  • Look for the lightbulb in the corner, click it, then save the file it makes

VS Code Typings

# install the `typings` package
# to manage library definitions
sudo npm install -g typings

cd path/to/project

# install jQuery definitions
typings install dt~jquery --global

Then install the type definitions file

First, Make sure you've created a .jsconfig file

tilde

jQuery & Elements

var txt = $('#my-div').text();      //get the textContent
$('#my-div').text('new info!');     //change the textContent

$('#my-div').html('<em>new html!</em>'); //change the HTML

jQuery provides methods to access and modify both attributes and CSS, similar to the core DOM functions

Changes apply to all selected elements!

var txt = document.querySelector('#my-div').textContent;
document.querySelector('#my-div').textContent = 'new info!';

document.querySelector('#my-div').innerHTML = '<em>new html!';
$('svg rect').attr('height');       //get attribute (of all)
$('svg rect').attr('height',200);   //set attribute (of all)
$('svg rect').attr( {x:50, y:60} ); //set multiple attributes!
$('section').addClass('container'); //add class
$('section').removeClass('old');    //remove class
$('body').css('font-size','24px');  //set css property
$('body').css( {'font-size':'24px',
                'font-family':'Helvetica'} ); //multiple
document.querySelector('svg rect').getAttribute('height');
document.querySelector('svg rect').setAttribute('height', 200);
document.querySelector('section').classList.add('container');
document.querySelector('section').classList.remove('old');
document.querySelector('section').style['font-size'] = '24px;

jQuery & the DOM Tree

//create an element (not in DOM)
var newP = $('<p class="new">This is a new element</p>');

//add content to DOM
$('main').append(newP); //add INSIDE, at end
$('main').append('<em>new</em>'); //can create element on the fly

$('main').prepend('<em>new</em>'); //add INSIDE, at beginning

$('main').before('<header>'); //insert BEFORE

$('footer').insertAfter('main'); //insert target AFTER param


$('main').wrap('<div class="container"></div>'); //surround

$('footer').remove(); //remove element
$('main').empty(); //remove all child elements

works without closing tag

selects existing element, so will move!

jQuery Event Handling

jQuery provides convenience methods for registering event listeners.

$('#button').click(function(event) {
   console.log('clicky clicky!');
   
   //who was clicked 
   var element = $(event.target);
});

like addEventListener('click')

$('#button').click(function(event) {
   console.log('clicky clicky!');
   
   //who was clicked 
   var element = $(this);
});

`this` refers to source of event

get as jQuery element
to call jQuery methods on it ("wrap it")

jQuery Exploration

Open the js/poll.js file (for the poll.html file) and follow the instructions to create an interactive "poll" builder!

You will need to look up functions in the jQuery documentation. Work with a partner!

Document Ready

Can listen for when the document is finished loading in order to run our script. This lets us put the script in the <head>

$(document).ready(function() {
  //your program goes here
  //this need not be an anonymous function

});
//shortcut: just pass the function to the jQuery method
$(function() {
  //your program goes here
  //this need not be an anonymous function

});

For Fun: Effects!

jQuery also lets us add transitions to modify the appearance of elements.

$('#id').fadeIn(1000);   //fade in over 1 second
$('#id').fadeOut(500);   //fade out over 1/2 sec
$('#id').slideDown(200); //slide down over 200ms
$('#id').slideUp(500);   //slide up over 500ms
$('#id').toggle();       //toggle whether displayed
//custom animation syntax:
//$(selector).animate({targetProperties}, speed [, doneCallback]);
$("#face").animate({
    left: '500px',
    opacity: '0.5',
    height: '200px',
    width: '200px'
}, 1500);

CSS3 transitions are usually a better choice!

Utility Functions

jQuery includes a number of utility functions that provide cleaner syntax and cross-browser compatibility for task.

These functions are part of the global jQuery ($) object.

//check if an item is in an array
$.inArray(4, [3,4,3] ); 

//find an item in an array that matches the filter function
$.grep( [3,4,3], function(item) {
   return item > 3;
});
//this is like .filter, but works on old browsers (if right jQuery vers)


//iterate over arrays or objects -- works for either!
$.each( [3,4,3], function(key, value) {
   console.log('Give me a '+value);
}); 

$.each( {first:'Joel',last:'Ross'}, function(key, value) {
   console.log(key+' name: '+value);
});

But if you really want some utility functions...

Lodash

A library of handy shortcut methods for working with basic data structures (arrays, objects, etc).

These methods often perform better than native versions.

Including Lodash

There are a few different ways to include lodash:

  • Download the file directly and
    include it

  • Load the file via a package manager and include it

  • Include the file via a CDN link

Package Managers

Package managers such as npm allow you to download and organize the many libraries you may use.

They also allow you to save and keep track of what version of a library you are using (more later).

#install package in local folder
npm install packagename

make sure node_modules is in .gitignore!

Note that because node_modules is being ignored, you'll need to "copy" the file into a non-ignored directory
(e.g., js/). This is usually done via automated build tools (more later!)

Other Package Managers

released
Oct 11, 2016

Lodash Functions

Including Lodash creates a _ (underscore) variable in global scope . You can then call functions on this object.

For example: _.find()

Lodash Scavenger Hunt!

Open the js/scavenger.js file (uncomment in demo.html file) and search for Lodash functions that solve the problems!

You will need to look up functions in the Lodash documentation. Work with a partner!

Bootstrap

Bootstrap has JavaScript too! This provides common interactive widgets like dropdown menus.

These require jQuery to work---be sure and include the library after jQuery!

Bootstrap Examples

Bootstrap's JS components are documented primarily through examples. You need to look at the sample code and explanation, interpret what each HTML attribute is doing, and then determine how to apply those to your own content.

Example: collapsible elements 
http://getbootstrap.com/javascript/#collapse

Bootstrap Practice

  1. Make all sections of the demo.html page collapsible as an accordion (so only one is open at a time)!
     

  2. Use jQuery and Bootstrap-provided methods to make the top buttons ("Collapse all sections" and "Expand all sections") functional.

 

What we did...

  • jQuery for DOM and interaction

  • Lodash for utility functions

  • Bootstrap for widgets

Action Items!

 

Mon: ES 6; automated build systems (so we
           can use npm!)

info343au16-jquery

By Joel Ross

info343au16-jquery

  • 1,879