Welcome!

Wifi — First Round Capital Guest

Password (all lowercase) — frclovesphilly

Slides — ivanaveliskova.com/gdi-jquery

Demo Filesivanaveliskova.com/gdi-jquery/demo-files.zip

Remember to unzip demo-files and place it somewhere easily accessible on your desktop!

GDI Logo

Intro to jQuery

Welcome!

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

Our code of conduct

Some "rules"

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

GDI Philly is now on Slack!

Slack is a free, chat and messaging system available as either a web or native application for your desktop or mobile device. All our welcome to join our Slack team, but we need to add you! For an invitation, sign up here.


Join #frontend-classes to slack about this class!

Welcome!

  • This class will be a combo of lecture + exercises
  • It is 4 hours long, with a 30 minute break in the middle
  • 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?
  • What is your favorite breakfast food?

JavaScript Review

Variables

var name = "Ivana";

var greeting = "Hey there, " + name;

console.log(greeting);

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

Don't forget to open up the console!

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",
  age: 25,
  roles: ["hacker", "teacher", "coder"]
};

JavaScript Review

Looping

var favoriteThings = ["Puppies", "Doctor Who", "Settlers of Catan"];

for(var i = 0; i < favoriteThings.length; i++) {
  console.log((i + 1) + ". " + favoriteThings[i]);
}
var i = 0;

while(i < 10) {
  console.log("The current number is: " + i);
  i++; // Don't forget to increment i or you will get stuck in an infinite loop!
}

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

Combining Conditionals and Looping (FizzBuzz)

for(var i = 1; i <= 100; i++) {
  var print;

  if ((i % 5) === 0 && (i % 3) === 0) {
    print = 'FizzBuzz';
  } else if ((i % 3) === 0) {
    print = 'Fizz';
  } else if ((i % 5) === 0) {
    print = 'Buzz';
  } else {
    print = i;
  }

  console.log(print);
}

There is no single 'right' way of solving this. This is just one solution. When you have some time try to figure out a different solution!

JavaScript Review

Functions

var name = "Ivana";

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

greet();

What will happen if we run this code?

JavaScript Review

Functions

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

add(2, 3);
add(1000, 30000);
var name = "Ivana";
function sayHelloTo(name){
  console.log("Hello, " + name + "!");
}
sayHelloTo("Maggie");
sayHelloTo(name);
sayHelloTo();

JavaScript Review

Traversing the DOM

document.getElementById('above-paragraph');
// Finds an element in the DOM by ID
// will return first one that matches (there should only be 1)
document.getElementsByClassName('past');
// Finds elements in the DOM by class
// will return an array even if there is only one match
document.getElementsByTagName('body');
// Finds elements in the DOM by tag
// will return an array even if there is only one match
document.querySelectorAll('[data-slide]');
// Finds elements in the DOM by any selector that you can use in CSS
// will return an array even if there is only one match
document.querySelector('[data-slide]');
// Finds an element in the DOM by any selector that you can use in CSS
// will return only the first one that matches

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

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

Example: JavaScript


To hide images:

var allImages = document.getElementsByTagName("img");
for (var i = 0; i < allImages.length; i++) {
  allImages[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 (content delivery network)
    • Good for development
  • Use a content distribution/delivery network
    • User may have it cached, saves on page weight
    • <script src="http://code.jquery.com/jquery-2.2.1.js"></script>
    • Good for production

Let's Develop It!

  • 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 (from the last slide)
  • 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
  • Once you finish that, create a new javascript file in the same directory and link it to your html page and move the hide image code in there to make sure it still works
  • Make sure to leave the jQuery script tag where it is!

Anatomy of a jQuery call

This HTML...

<img src="puppies.jpg">

with this jQuery...

$('img').hide();

results in this HTML...

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

Anatomy of a jQuery call


$('img').hide();

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

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

Selectors

All CSS selectors are valid

Some Examples:

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)

[data-hide-image] elements that have the data attribute "data-hide-image"

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

Methods to Memorize:

No arguments

.parent() Retrieves the element's direct parent

.children() Retrieves all direct children of the element

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

.width() Returns the width of element (in px)

.height() Returns height of element (in px)

.fadeOut() Gradually decreases opacity of element and then add a "display: none"

.fadeIn() Will add a "display:block" and then gradually increase opacity of element

Examples:


$('.hero img').remove();

$('#banner > span').hide();

$('#banner').children().hide();

$('img:not(.hero img)').fadeOut();

Let's try this in the console of our demo files!

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('<p>The end!<p>')–Inserts a 'p' tag inside the element at the end

.prepend('<h1>Hey!</h1>')–Inserts an 'h1' tag inside the element at the beginning

Examples:


$('.hero img').attr('src');

$('#banner > span').addClass('visible');

$('#banner').children().append('!');

Let's try this in the console of our demo files!

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"

Trick question:

$('a').css('color'); "rgb(0, 128, 0)"

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');

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

<a href="http://www.yahoo.com" style="color: purple; text-decoration: underline;">Yahoo!</a>

Alternatively the javascript code above can be written as:

$('a').text('Yahoo!').attr('href', 'http://www.yahoo.com').css({'color': 'purple', 'text-decoration': 'underline'});

You can pile on as many methods as you need, as long as you keep track of what is happening. (And potentially can document it.)

Let's Develop It!

In your demo-files javascript page, use jQuery to

Make sure to comment out the code that hid the images!!!

  • Hide the navigation
  • Add the class "spin" to the main page heading
  • Change the color of the links in the opening paragraph only
  • Photobomb just the hero image with a photo (or photos) of your favorite celeb!

Bonus Challenge! Try to replace the text on the images in the gallery! (Start by changing all of the text to be the same and then try to make each line different)

Try not to modify the HTML/CSS directly (such as adding classes so you can select certain elements), try to only make the changes using jQuery

Why not just HTML/CSS?

  • Sometimes you don't have access to those files
  • Dynamic Content
  • Conditionals
var $doc = $('body');
var style = $doc[0].style;

if ( style.msGrid === '' || style.grid === '' ) {
  $doc.addClass("supports-grid");
}

And now you can be sure that your browser supports grid! And if you have the latest version of Chrome (57) or FireFox (52) you should be able to get this class to show up in the DOM!

Why not just HTML/CSS?

<img class="sale-img" src="images/sale.png">
var currentTime = new Date().getTime();
// sets currentTime variable to current unix timestamp like 1428534443

var endDayBegin = new Date(2017, 4, 23).getTime();
var endDayEnd = new Date(2017, 4, 23, 23, 59, 59).getTime();

if (currentTime > endDayBegin && currentTime < endDayEnd) {
  $('.sale-img').attr('src', '/images/ends-today.png');
} else if ( currentTime > endDayEnd ) {
  $('.sale-img').remove();
}
// changes sale image to an 'ends today' version if it's the last day of the sale
// And removes the image if it's past the day 

Looping

In javascript we wrote a 'for' statement and kept track of the index with a variable.

var listItems = document.getElementsByTagName('li');
for(var index = 0; index < listItems.length; index++) {
  console.log('This is list item # ' + index);
}

With jQuery we can use...

.each() commonly used method to loop through a collection

$('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.

Example coming right up!

And now a word from one of our sponsers*:

this

"used to indicate a person, thing, idea, state, event, time, remark, etc., as present, near, just mentioned or pointed out…" — Dictionary.com

Thank you

*Not really a sponsor.

Now back to your regularly scheduled programming.

Looping

Using 'this' as an iterator:

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

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

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

One more note from another one of our sponsers:

Storing Variables

$('#someID').append('!');
$('#someID').css('color', 'green');

This will ask jQuery to rescan for the matching element, wrap it in a jQuery object, and create a new instance of something you already have in memory.

$someVarName = $('#someID');
$someVarName.append('!');
$someVarName.css('color', 'green');

This will allow you to cache your elements and refer to them when needed. Saving memory!

Thank you

Now back to your regularly scheduled programming.

Let's Develop It!


In demo-files/index.html, use .each() to credit each listed quote to David Tennant!

  • "I can’t help it if the ladies of the universe are flinging themselves at me, can I?" –David Tennant

Challenge: Give credit at the beginning of each quote

  • According to David Tennant, "I can’t help it if the ladies of the universe are flinging themselves at me, can I?"

Bonus Challenge! Take each image and make the overlay appear and disappear 'on' hover! Hint: try using the jQuery documentation (http://api.jquery.com/) to figure this out!

Stretch break!

kitty!

Interaction

The bread and butter of jQuery.


Events

When something happens

Interaction

When I do this thing, it will respond somehow

  • Most events happen via the .on() method, which usually takes two args.
  • The first argument is the event (or events), passed in as a string
  • The second argument 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:

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

Let's Develop It!


  • Add console logs on mouseenter/mouseleave for the hero image
  • Add some text underneath the button when it's clicked
  • Toggle the hamburger menu to show and hide on click. (Inspect the DOM to figure out which elements should have the event happen to and which should be handled.)


Bonus Challenge: Have the text that appears underneath the button appear when the button is clicked and disappear if the button is clicked again

Document Readiness

A break in our regularly scheduled program

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

Sometimes jQuery will try to load and hook onto elements that don't exist yet.

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

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

This waits for the DOM to be fully loaded and does a check if it is loaded before any JavaScript/jQuery is run.

Built-in Effects & Animation

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

Animation controls

  • delay
  • stop
  • finish
  • queue

Custom Animation

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

$('p.special').animate(
  {opacity: 0.25, fontSize:'3em'},
  4000,
  'linear',
  function(){
    alert('done!');
  }
);

I'm a special paragraph!

Try it together!

When hovering a gallery image: hide, show, or animate the overlay info.

$('.gallery li').on('mouseenter mouseleave', function() {
  $(this).find('.overlay').fadeToggle('fast');
});
  • Be mindful of what a user will see without JavaScript
  • A lot of these features are possible through CSS3, but jQuery is supported on older browsers
  • Also, jQuery allows you to trigger effects on elements other than the one being interacted with

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 after your call to jQuery
  • In the JavaScript, call the jQuery plugin on your DOM

Let's Develop It!

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?

?

Get Involved

  1. Join Slack community
  2. Teaching assist
  3. Teach something
  4. Mentor or be mentored

All forms here

Thank You!


Survey

We value your feedback and are always trying to improve.

http://bit.ly/gdi-philly-jquery


Get in touch!

@ivanaveliskova

ivanaveliskova@gmail.com

;