jquery_101



jquery_101

0 1


jquery_101

Intro to jQuery for Girl Develop It Philadelphia

On Github TNBWorkshop / jquery_101

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!

Tell us about yourself.

  • Who are you?
  • What do you hope to get out of the class?
  • What is your superpower?

What is jQuery?

A javascript library

Ok, what is a library?

A collection of functions

So, what are functions?

Reusable pieces of code that do something and may return a value. Can contain other functions. (more on this later)

The purpose of jQuery

  • Write less code for common tasks
  • Cross-browser uniformity
  • Not meant to replace an understanding of javascript

The jQuery base library includes...

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

Example: Raw JS (full browser support)

var p = document.createElement('p');
p.appendChild(document.createTextNode('Welcome!'));
p.style.cssFloat = 'left';
p.style.styleFloat = 'left';
p.style.backgroundColor = 'red';
p.className += ' special';
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++){
  var div = divs[i];
  if(/\bheader\b/.test(div.className)){
    div.appendChild(p);
    break;
  }
}

Example: Raw JS (IE9+)

var p = document.createElement('p');
p.textContent = 'Welcome!';
p.style.cssFloat = 'left';
p.style.backgroundColor = 'red';
p.className += ' special';
document.querySelector('div.header').appendChild(p);

Example: jQuery

$('<p>Welcome!</p>')
.css({'float': 'left', 'background-color': 'red'})
.addClass('special')
.appendTo('div.header');

Try them both

In your dev tools console...

Why not use jQuery?

  • You want to understand how it really works
  • Sometimes it's faster to write your own than to customize (plugins)
  • Page weight—it likely includes stuff you don't need

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-1.11.0.min.js
    • Good for production

Including jQuery

  • Can be included at the bottom of your html content
  • Or, if included in the head, code you want to run when content is complete needs to be inside a document.ready function (more on this later)
$(document).ready(function() {
  // Handler for .ready() called.
});

Let's Develop It

  • Include the script on the sample page, either in the head or at the end of the body
  • Now try the jQuery command from before

Scripting

  • Experiment in your dev tools console
  • Anything you want to keep goes into your file

Anatomy of a jQuery call

This HTML...

<p>Welcome!</p>

with this jQuery...

$('p').addClass('special');

results in this HTML...

<p class="special">Welcome!</p>

Anatomy of a jQuery call

$('p').addClass('special');

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

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

. We'll get back to this

addClass('') jQuery method to add the specified class to each element in the collection. http://api.jquery.com/addClass/

Functions in Disguise

The $ (and jQuery), and .addClass() are just functions!

  $('p')
          
  // These are just two functions "chained" together!
  $('p').addClass('special');
          
  Name(argument)

  function(argument)
          

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/

Let's Develop It

Select some elements in your sample file.

Filters

Filters create a new jQuery collection from members of an original collection that pass a check.

var collection = $('input');
var inputNotRadio = $(collection).not('[type="radio"]');
var inputError = $(collection).filter('.error');
var inputIsPA = $(collection).filter(function(){
  return $(this).val() === 'PA';
});

Here is an example of passing a variable into the global jQuery function, rather than a selector.

The original collection is not altered.

Let's Develop It

  • Assign a collection to a variable
  • Filter that collection and assign the result to a new variable

Creating Elements

$('<p>') <p></p>

$('<p class="intro">') <p class="intro"></p>

$('<p>Welcome!</p>') <p>Welcome!</p>

  • An opening tag, alone, creates an empty element with the specified properties
  • A tag with content creates html, as written

Reading elements & their properties

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

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

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

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

On the example page, some properties of the link to Yasmine's email.

Changing elements & their properties

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

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

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

$('a').css({'color': 'purple'});

Recap: Getting vs. Setting

Many of jQuery's methods do double-duty.

<p>What's in here?</p>

  $('p').html();  // No argument, will get the value "What's in here?"
          
  $('p').html("Heyo!");  // SETS the value!
          

<p>Heyo!</p>

Chaining

That same set of manipulations could be written as

$('a').html('Yahoo')
  .attr('href','http://www.yahoo.com')
  .css({'color':'purple'});
          

because each jQuery function returns the collection again.

This is called "chaining" and is done with a period between method calls.

Chaining is a widely appreciated feature of jQuery.

A Train (Chain) of Functions

  $('p').addClass('special').html('hello!');
          

Ok, but...

This works great when we know there is only one link.

Run $('a').append('!'); and see what happens.

We need a better selector, if we want to affect one out of many.

Looping

  • Many built-in methods include implicit iteration
  • Explicit iteration is for more complex tasks to be run on each member of a collection
$('img.profile-pic').each(function(index){
  if($(this).width() < $(this).height()){
    $(this).css({'border':'solid 3px red'});
  } else {
      $(this).css({'border':'solid 3px blue'});
  }
});

What does this function do?

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.

Let's Develop It

For all links to twitter, add an external icon to the end of the anchor content, and make the text blue.

$('a[href*="twitter"]').append('<img src="assets/externalicon.png" />')
  .css({'color':'blue'});

Problems with this:

  • Separation of concerns
  • Maintainability

Much better to apply classes than to granularly add styles and change content.

Interaction

The bread and butter of jQuery.

Events

Binding handlers

The "click" method is one of the simplest ways to bind a handler to an event. http://api.jquery.com/click/

function onButtonClick() {
  console.log('clicked!');
}

$('#button').click(onButtonClick);

Or more succinctly

$('#button').click(function () {
  console.log('clicked!');
});

Binding handlers

You can also...

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

event: 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. http://api.jquery.com/on/

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

Try it

Add console.log messages on mouseEnter/mouseLeave for all names

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.
});

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

When clicking a profile photo, hide, show, or animate the contact info.

$('.profile-pic').on('click',function(){
  $(this).siblings('.contact').slideToggle('slow');
});
  • 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, and is very well documented.
  • jQuery is open source and widely used, so there are many many plugins available (of varying quality and levels of documentation)
  • date pickers, slideshows, and accordions (oh my!)

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

Try it

Add the "sortable" functionality from jQuery UI to the nav links.

http://jqueryui.com/sortable/

AJAX

  • Asynchronous javascript and XML
  • Used for any communication to the servers without a page refresh
    • form submissions
    • adding items to your shopping cart
    • updating twitter/facebook feeds
  • jQuery ajax method allows for JSONP

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

Try it

Look at GDI ajax request to meetup

Summary

  • jQuery is a well-documented library of ready-made javascript functions
  • Can be used to get and change info about html elements or create new elements
  • Best employed to enrich user interactions
  • Widely used for its simple AJAX functionality
  • Many plugins are available in the open source community. Contribute your own!

Questions?

?

Survey

http://bit.ly/gdi-jquery

Intro to jQuery ~ Girl Develop It ~