• Wifi — PromptWorks-Guest
  • Password — handcrafted
  • Slides — ahoef.co/jquery/slides
  • Demo Files — ahoef.co/jquery/demo-files.zip

Intro to jQuery

Welcome!

Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

Some "rules"

  • We are here for you!
  • Every question is important
  • Help each other
  • Have fun

Welcome!

  • This class will be a combo of lecture + exercises
  • 2 Sessions: 6:30pm-8:45pm
  • Agenda
    • Introductions
    • Quick review of JavaScript
    • JQuery overview
    • Selectors & Methods
    • JQuery Documentation
    • Events & Animations
    • Plugins

Welcome!

Tell us about yourself.

  • Who are you?
  • What do you hope to get out of the class?
  • Which of your web projects are you most proud of?

JavaScript Review

Variables

var name = "Ali";

var greeting = "Hey there, Ali";

var greeting = "Hey there, " + name;

console.log(greeting);

Open up demo-files/js-review.html in your browser & text editor to test this out!

JavaScript Review

Data Types

var myString = "This is a string!";
var myInteger = 1;
var myBoolean = true;
var myArray = ["string", 1, myVar, true];
var myObject = {
  name: "Pamela",
  adjective: "Cool",
  roles: ["hacker", "teacher", "coder"]
}

JavaScript Review

Functions


var name = "Ali";

function greet(){
  console.log("Hey there, " + name);
}

greet();

JavaScript Review

Functions


var name = "Ali";

function greet() {
  name = "Joey";
  console.log("Hey there, " + name);
}

greet();

JavaScript Review

Functions


function add(number1, number2){
  console.log("Total: " + (number1 + number2));
}

add(2, 3);
add(1000, 30000);

JavaScript Review

Conditionals


var total = 10;

if (total >= 100) {
  console.log("Total is greater than or equal to 100");
} else {
  console.log("Total is less than 100");
}

JavaScript Review

Traversing the DOM


document.getElementById('presentation');
document.getElementsByClassName('slide');
document.getElementsByTagName('body');
document.querySelectorAll('a');
document.querySelector('img');


We made it through the JS review!




Any questions?

What is jQuery?


  • A library of predefined JavaScript functions
  • A tool that prevents developers from having to reinvent the wheel
  • A well-supported cross browser solution
  • Not a replacement for an understanding of JavaScript

The jQuery base library includes...

  • Data manipulation
  • DOM manipulation
  • Events
  • Effects and animation
  • AJAX

Example: JavaScript


To hide images:

var elems = document.getElementsByTagName("img");
for (var i = 0; i< elems.length; i++) {
  elems[i].style.display = "none";
}

Example: jQuery


To hide images:

$('img').hide();

The Source



www.jquery.com

Including jQuery

  • Use a <script> tag
  • Download and serve
    • Allows you to work locally without an internet connection
    • May be faster than a cdn
    • Good for development
  • Use a content distribution network
    • User may have it cached, saves on page weight
    • http://code.jquery.com/jquery-2.1.3.js
    • Good for production

Exercise!

  • Open up demo-files/index.html in your text editor & in your browser
  • Include the jQuery library as a source attribute in a script tag before the closing body tag
  • Under that script tag, create a new set of script tags, where your code will live
  • Use the jQuery command from a few slides back to hide all of the images on the page

Anatomy of a jQuery call

This HTML...

<img src="cats.jpg">

with this jQuery...

$('img').hide();

results in this HTML...

<img style="display: none;" src="cats.jpg">

Anatomy of a jQuery call

$('img').hide();

$() Global jQuery function. Alternately "jQuery()" Used to trigger all jQuery functionality.

'img' Argument being passed into the global jQuery function. In this case, a selector to return all 'img' elements. Also accepts variables and html strings. Returns a jQuery collection/object

.hide() jQuery method to hide the element by adding a style of 'display: none;'

; Syntax to conclude a statement

Anatomy of a jQuery call


$('img').hide();

  • $('img') is a selector
  • .hide() is a method

Selectors

All CSS selectors are valid, plus some extras

a all anchors

.blue elements with the class "blue"

p:eq(2) the third paragraph (zero-based count)

[id^="vidLink_"] elements with an id beginning with "vidLink_"

:contains("free") elements that contain the text "free" (case-sensitive)

http://api.jquery.com/category/selectors/

Methods

There are many jQuery methods- like tools in a toolkit!


Like screwdrivers, hammers, wrenches, there are a few main groups that methods fall into:

  • Getting/changing content within elements
  • Finding/changing elements themsleves
  • Changing attributes
  • Getting/changing dimensions & positions
  • Creating animations
  • Events

Methods


So break it down even further, a method can be a getter, a setter, or both!

  1. A Getter
    • The method retrieves something and stores it in the browser's memory
  2. A Setter
    • The method takes action and changes something
  3. Or Both!
    • Depending on how it is used, a method can either get or set (more on this later)

Methods to Memorize:

No arguments

.hide() Adds an inline style of "display: none" to the element

.show() Adds an inline style of "display: block" to the element

.remove() Deletes element from the DOM

.html() Retrieves html within the selected element

.text() Retrieves only the text within the selected element

.parent() Retrieves the element's direct parent

Methods to Memorize:

No arguments

.children() Retrieves all direct children of the element

.next() Retrieves the next single element at the same level in the DOM tree

.width() Calculates width of element

.height() Calculates height of element

.fadeOut() Gradually decreases opacity of element

.fadeIn() Gradually increases opacity of element

Examples:


$('.hero img').remove();
          
          $('#banner > span').hide();
          
          $('#banner').children().hide();
          
          $('img:not(.hero img)').fadeOut();
        

Methods to Memorize:

Single argument

.addClass('your-classname')Adds your-classname as a class attribute on to the element

.removeClass('your-classname')Removes your-classname as a class attribute on to the element

.attr('src')Retrieves the src attribute for the element

.css('background-color')Retrieves the background color of the element

.append('<h1>Hey!</h1>')Inserts an h1 tag after the element

Examples:


$('.hero img').attr('src');
          
          $('#banner > span').addClass('visible');
          
          $('#banner').children().append('!');
          
        

Methods to Memorize:

Single argument- Getters turn to Setters

.html()Retrieves html within element

.html('<h1>Hey!</h1>');Inserts/Replaces html within element


.text()Retrieves text within element

.text('Hey you!');Inserts/Replaces text within element


.width()Retrieves the width of element

.width(300)Sets the width of the element to be 300px


Methods to Memorize:

Multiple Arguments

.attr('src', 'sunset.jpg')Finds the element's src attribute and changes its value to sunset.jpg


.css('background-color', 'green')Finds the elements background color and changes it to green by adding an inline style, which overrides any background-color that might already be there


Check the jQuery Documentation for info on how each method works!

Reading elements & their properties


<a href="http://www.google.com" style="color: green;">Google</a>

$('a').text(); "Google"

$('a').attr('href'); "http://www.google.com"

$('a').css('color'); "green"

Changing elements & their properties

<a href="http://www.google.com" style="color: green;">Google</a>

$('a').text('Yahoo!');

$('a').attr('href', 'http://www.yahoo.com/search');

$('a').css({'color': 'purple', 'text-decoration': 'underline'});





Yahoo!

Exercise!

In demo-files/index.html, use jQuery to

  • Hide the navigation
  • Add the class "spin" to the main page heading
  • Change the color of the links in the opening paragraph only
  • Photobomb all the gallery images with photos of your favorite celeb!

Why not just css/html?

  • Sometimes you don't have access to those files
  • Dynamic Content
  • Conditionals
var isMobile = screen.width <= 640;

if (isMobile) {
  $('.desktop-nav').hide();
  $('.mobile-nav').show();
}
      

Why not just css/html?

<img class="sale-img" src="images/sale.png">


var currentTime = new Date().getTime();
// sets currentTime variable to current unix timestamp like 1428534443

if (currentTime > 1428595627) {
  $('.sale-img').attr('src', '/images/ends-today.png');
}
// changes sale image to an 'ends today' version if the time is after 7am on Sunday
      

Document Readiness

Most everything you want to do with jQuery requires the DOM to be fully loaded.

The browser renders the markup from top to bottom, then triggers a DOMReady event.

$(document).ready(function() {
  // Handler for .ready() called.
});
$(function() {
  // Handler for .ready() called.
});

Exercise!

Separate your JS from your HTML

  • In the demo-files folder, create a new folder called 'js'
  • In your new js folder, create a file called 'site.js'
  • Include site.js in index.html with a script tag
  • In site.js, add a document ready function
  • Move your jQuery code from index.html to inside your document ready function

Looping

.each() commonly used method to loop through a collection
$('ul li').each(function() {
  console.log('This is a list item.');
});

          $('ul li').each(function(index) {
  console.log('This is list item #' + index);
});

Index and This

index: the function supplied to "each" is automatically passed the number of the current loop iteration, which will generally match the index of each member of the collection.

this: "this" is the context of any function. Frequently in jQuery, "this" will refer to the element being pointed to by the iterator.

Other built-in methods are sometimes passed other pertinent data.

Looping

Use 'this' as an iterator:

$('ul li').each(function() {
  $(this).append('!');
});

To be more efficient, cache a variable for $(this):


$('ul li').each(function() {
  var $this = $(this);
  $this.append('!');
});

Exercise!


Use .each() to credit each listed quote to Ryan Gosling!

  • "You just tell me what you want, and I'm gonna be that for you." —Ryan Gosling


Challenge: Give credit at the beginning of each quote

  • According to Ryan Gosling, "You just tell me what you want, and I'm gonna be that for you."

Interaction

The bread and butter of jQuery.


Events


Interaction

  • Most events happen via the .on() method, which usually takes two args.
  • The first arg is the event, passed in as a string
  • The second arg is a function that will run when the event happens, called an event handler
  • 
    $('button').on('click', function() {
      console.log('the button was clicked!');
    });
    

Binding handlers

You can also...

$('a').on('click', function (event) {
  event.preventDefault();
  console.log('Not going there!');
});

Event handlers are typically passed the event that has triggered them, and that data can then be used by the handler. See info on the event object: http://api.jquery.com/category/events/event-object/

Binding handlers

You can also use the "on" method to bind to multiple events at once:

$('.sidebar').on({
  click: function() {
    $(this).toggleClass('active');
  }, focusin: function() {
    $(this).addClass('inside');
  }, focusout: function() {
    $(this).removeClass('inside');
  }
});

Exercise!


  • Add a console log on click of a nav item
  • Add console logs on mouseenter/mouseleave for the hero image
  • Hide the gallery of images when the button is clicked

Built-in Effects & Animation

  • show / hide / toggle
  • slideUp / slideDown / slideToggle
  • fadeIn / fadeOut / fadeToggle / fadeTo

Custom Animation

.animate( properties [, duration ] [, easing ] [, complete ] );

$('p.special').animate(
  {height:'300',fontSize:'5em'},
  3000,
  'linear', 
  function(){
    alert('done!');
  }
);

jQuery UI & Plugins

  • jQuery UI offers more advanced interaction methods. It's very well documented, but can be heavy on pageload. Only load in pieces you need!

  • jQuery is open source and widely used, so there are many many plugins available (of varying quality and levels of documentation)
    • date pickers, slideshows, accordions, much more!


http://plugins.jquery.com/

Using Plugins

  • Download the plugin and associated files from the site or github repo
  • Copy them into your project folder
  • In the HTML, reference any associated CSS files
  • In the HTML, add a script tag for the jQuery plugin itself
  • In the JavaScript, call the jQuery plugin on your DOM

Exercise!

Add a slideshow using Slick.js!

  • Use any of the images in the demo-files image folder, or any of your own images
  • Test out some of the different display/interaction options Slick has

Next Steps

Questions?

?

Thank You!


Survey

http://bit.ly/gdi-jQ


Get in touch!

@ahoefinger

alexandra.hoefinger@gmail.com