Intro to jQuery



Intro to jQuery

0 0


gdi-jquery

These are the slides for Intro to jQuery

On Github ivanaveliskova / gdi-jquery

Welcome!

Wifi — First Round Capital Guest

Password (all lowercase) — frclovesphilly

Slides — ivanaveliskova.com/gdi-jquery

Demo Files — ivanaveliskova.com/gdi-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
  • It is 4 hours long, with a 30 minute break
  • 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?
  • Who is your favorite TV/movie character?

JavaScript Review

Variables

var name = "Ivana";

var greeting = "Hey there, " + name;

console.log(greeting);

Open up the demo-files/js-review in your browser and 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",
  age: 25,
  roles: ["hacker", "teacher", "coder"]
};

JavaScript Review

Functions

var name = "Ivana";

function greet() {
  var 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);
var name = "Ivana";
function sayHelloTo(name){
  console.log("Hello, " + name + "!");
}
sayHelloTo("Molly");
sayHelloTo();
sayHelloTo(name);

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

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++;
}

JavaScript Review

Combining Conditionals and Looping

for(var i = 1; i <= 100; i++) {
  if ((i % 3) === 0 && (i % 5) === 0) {
    console.log("FizzBuzz");
  } else if ((i % 3) === 0) {
    console.log("Fizz");
  } else if (( i % 5) === 0) {
    console.log("Buzz");
  } else {
    console.log(i);
  }
}

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 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
    • 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
  • 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="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();

$() 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

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)

[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!

A Getter
  • The method retrieves something and stores it in the browser's memory
A Setter
  • The method takes action and changes something
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() Returns the width of element (in px)

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

.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('<p>The end!<p>')—Inserts a 'p' 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');

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

Let's Develop It!

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 just the hero image with a photo (or photos) of your favorite celeb!

Bonus Challenge! Try to change all the images in the gallery with images of your favorite celeb (or use the images in the images folder) and replace the text on the overlay!

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

Looping

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

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

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.

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('!');
});

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!

Interaction

The bread and butter of jQuery.

Events

Interaction

  • 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 menu to show and hide on click. (Inspect the DOM to figure out which elements we should be selecting and showing.)

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.

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

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

Or you can put you javascript at the bottom of the document

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(
  {height:'500',fontSize:'3em'},
  4000,
  'linear', 
  function(){
    alert('done!');
  }
);

Try it together!

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

$('.gallery li').each(function() {
  var $thisImage = $(this);
  $thisImage.on('mouseenter mouseleave', function() {
    $thisImage.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

Next Steps

Questions?

?

Thank You!

Survey

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

Get in touch!

@ivanaveliskova

ivanaveliskova@gmail.com

Intro to jQuery ~ Girl Develop It ~