Beginning Javascript

Class 3

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

Goals for the class

  • Week 1: Intro to JavaScript
  • Week 2: More JavaScript & the DOM
  • Week 3: Intro to jQuery
  • Week 4: AJAX and APIs

Useful References

What is a library?

  • Software libraries hold functions (not books!)
  • When you include a library, you can use all the functions in that library
  • That means: you get to take advantage of other people's experience!
  • And... Save time!

What is jQuery?

jQuery is a library of JavaScript functions.

It contains many functions to help simplify your programming, including:

  • HTML element selection & manipulation
  • CSS manipulation
  • HTML events
  • JavaScript effects and animations

Why use jQuery?

  • The most popular JavaScript library
  • jQuery empowers you to "write less, do more."
  • Great documentation and tutorials
  • Works across a multitude of browsers
  • Used by nearly 20 million(!) websites

jQuery: A Brief History

  • jQuery was created by John Resig, a JavaScript tool developer at Mozilla.
  • January 2006: John announced jQuery at BarCampNYC: BarCampNYC Wrap-up
  • September 2007: A new user interface library is added to jQuery: jQuery UI: Interactions and Widgets
  • September 2008: Microsoft and Nokia announce their support for jQuery
  • December 2009: jQuery wins .Net Magazine's Award for Best Open Source Application

Including jQuery

Three main ways to include jQuery on your page.

Including jQuery: Local

Download the library, store it locally:


  <head>
    <script src="jquery.js"></script>
  </head>
          

Including jQuery: Hosted by jQuery

Include the the live library from jQuery:


  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js">
    </script>
  </head>
          

Including jQuery: Hosted by Google

Include the the live library from Google:


  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
  </head>
          

Let's Develop It

Add jQuery

  • Link to the Google hosted jQuery
  • Put it before your JavaScript file

Let's Develop It

Add jQuery


  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
    <script src="scripts.js"></script>
  </head>
            

jQuery should go first because
our code will depend on it later.

Example

Are you done or really stuck?

Check out our example.

Keep in mind that this is one of many possible solutions.

jQuery Basics

Select some elements and do something with them.

jQuery Basics

The jQuery API Documentation is a great reference.


API

  • Stands for Application Programming Interface
  • A set of routines, protocols, and tools for building software applications.
  • The building blocks that help a programmer
    build a program.

jQuery Selectors

Before we used things like document.getElementById() and document.getElementsByTagName()


In jQuery, we find elements using $()

In jQuery, we find elements using CSS selectors

$() is an alias for jQuery()

jQuery Selectors: id

Find elements by id using #


  <div id="my-data">
    the data
  </div>

  <div id="important">
    <p>important text</p>
  </div>
            

  $("#important");
  $("#my-data");
            

jQuery Selectors: id

Try it!

jQuery Selectors: element

Find elements by element name


  <ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
  </ul>

  <a id="gdi-link" href="http://girldevelopit.com">
    Girl Develop It
  </a>
            

  $("li");
  $("a");
            

jQuery Selectors: element

Try it!

jQuery Selectors: class

Find elements by class name using .


  <h1 class="header">My Page.</h1>

  <div class="other">
    <p>other text</p>
  </div>
            

  $(".header");
  $(".other");
            

jQuery Selectors: class

Try it!

jQuery Selectors

jQuery supports most CSS3 selectors.


  $("ul li");
  $(".other p");
            

See the documentation for a full list

jQuery Selectors: Filters

Sometimes a selection has more than you need.

Filter methods help refine your selection.


  $("div").has("p");
  $("li").first();
  $("p").eq(2);
  $("div").not("#important");
            

saving jQuery selections

If you've made a selection you might want to use again, you can save it in a variable.

This is a good idea for performance.


  $important = $("#important");
            

The convention is to start the variable name with a $ to indicate it contains a jQuery object.

jQuery Actions

jQuery has hundreds of actions that can be performed on any element

All the actions are methods

As methods they are called with dot notation

Action format

        $(selector).action();
            

get and set attributes

We use the attr method as a getter and a setter


  <a id="gdi-link" href="http://girldevelopit.com">
    Girl Develop It
  </a>
              

Get attribute


  $("#gdi-link").attr('href');
              

Set attribute


  var pghLink = 'http://girldevelopit.com/chapters/pittsburgh';
  $("#gdi-link").attr('href', pghLink);
              

get and set attributes

Try it!

get and set html

We use the html method to
get and set an element's HTML


  <div id="my-data">the data</div>
              

Get html


  $("#my-data").html();
              

Set html


  $("#my-data").html('different data!'); // Text

  $("$my-data").html('<strong>Strong Data!</strong>'); // HTML
              

get and set html

Try it!

get and set text

We use the text method to
get and set an element's text


  <div id="my-data">the data</div>
              

Get text


  $("#my-data").text();
              

Set text


  $("#my-data").text('different data!'); // Text
              

append and prepend

We use the append and prepend methods to
add to an element's HTML


  <div id="my-data">the data</div>
              

Append - add to the end


  $("#my-data").append('back');
  $("#my-data").append('<strong>strong back</strong>');
              

Prepend - add to the beginning


  $("#my-data").prepend('front');
  $("#my-data").prepend('<strong>strong front</strong>');
              

append and prepend

Try it!

Creating new elements


  var newDiv = $('<div></div>');
            
Seriously. That's it!

Removing elements

Use the remove method to remove the element(s).


  <div id="my-data">the data</div>
              

  $('#my-data').remove();
            

get and set styles

We use the css method as a getter and a setter

  <div id="styled" styles="color: red;">styled text!</div>

Get style

  $("#styled").css('color');

Set style


  $("#styled").css('color', 'blue');

  // Set multiple styles
  $("#styled").css({
    'margin': '10px',
    'border': 'solid 1px black'
  });
              

get and set styles

Try it!

modify classes

We use the class manipulation methods
to modify classes


  $("#styled").addClass("active");
  $("#styled").hasClass("active");
  $("#styled").removeClass("active");
  $("#styled").toggleClass("active");
            

chaining

Many jQuery methods return a jQuery object,
so you can call additional methods
without pausing for a semicolon.

  <div id="styled" styles="color: red;">styled text!</div>

Separately


  $("#styled").css('color');
  $("#styled").append('extra text!');
              

Chained


  $("#styled").css('color').append('extra text!');
              

each

jQuery's each method makes it easy to iterate through elements.


  <ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
  </ul>
              

  $("li").each(function(index, element) {
    $(element).text("This is item #" + index);
  });
              

each

Try it!

Let's Develop It!

Convert to jQuery

  • Convert last week's DOM interactions into jQuery
  • Bonus: add some style changes too

Hints

  • Use $() with css selectors to find elements.
  • Look at the slides and/or the jQuery API to figure out how methods work

Example

Are you done or really stuck?

Check out our example.

Document Ready

The DOM takes time to load

Immediately running JS that depends on the DOM leads to problems

Document ready is a method called when the page is loaded

  $(document).ready(function(){
    // Code that depends on the DOM
  });
            

Document Ready

It can also be written in a short way like this

  $(function(){
    // Code that depends on the DOM
  });
            

Document Ready


  $(document).ready(function(){
    // Code that depends on the DOM
  });
            
callback function - a function that is passed as an argument, and expected to run (call back) at an appropriate time.

anonymous function - a function without a name.

Let's Develop It!

Document Ready

  • Replace window.onload with $(document).ready

Example

Are you done or really stuck?

Check out our example.

HTML events

Events occur on a webpage via user interaction

Common Events:

Handling events


  $(selector).mouseenter(function(){
    //code when the mouse enters
  });
      

  $('.box').mouseenter(function(){
    $(this).css('background-color', 'purple')
  });
      
The $(this) selector in jQuery refers to the element on whom the action was called.
Here $(this) is the $('.box') that the mouse entered.

Handling event examples


  $('.box').mouseenter(function(){
    $(this).css('background-color', 'purple')
  });
            

  $('.box').mouseleave(function(){
    $(this).css('background-color', 'orange')
  });
          

  $('.box').click(function(){
    $(this).css('background-color', 'green')
  });
          

Combining events

If you want multiple events to happen on the same element, you should use the on method


  $('.box').on({
    click: function() {
      $(this).css('background-color', 'green')
    },
    mouseenter: function() {
      $(this).css('background-color', 'purple')
    },
    mouseleave: function(){
      $(this).css('background-color', 'orange')
    }
  });
          
Try it!

Let's Develop It!

Events

  • Add a div to your html
  • Bind events to your div in the javascript file
  • Change the div when events trigger
  • Bonus: change all the onclick events to jQuery click events

Hints

  • Remember to put things inside document.ready
  • Some suggested things to change on event: color, text, size

Example

Are you done or really stuck?

Check out our example.

HTML forms

HTML Forms allow users to enter information


<form id="about-me">
  <input type="text" id="name" placeholder="Enter a name"/>
  <label>Do you like popcorn</label>
  Yes <input type= "radio" name="popcorn" val="yes"/>
  No <input type= "radio" name="popcorn" val="no"/>
  <label>Favorite Dinosaur</label>
  <select id="dinosaur">
    <option value="t-rex">Tyrannosaurus Rex</option>
    <option value="tri">Triceratops</option>
    <option value="stego">Stegosaurus</option>
    <option value="other">Other</option>
  </select>
  <input type="submit" value="Go!" style="padding: 7px; font-size:1em;"/>
</form>
            

HTML forms

HTML Forms allow users to enter information



Yes No


Values from Forms

You can use val to get values from a form


    $('#name').val();
    $('select#dinosaur').val();
    $('input:radio[name=popcorn]:checked').val();
            
Or set values of a form

    $('#name').val('Mitch');
    $('select#dinosaur').val('stego');
    $('input:radio[name=popcorn]:checked').val('no');
            

Values from Forms

jQuery has an event for form submission


  $('#about-me').submit(function(event){
    //code to execute on submission
    return false;
  });
            
"return false" to prevent the form trying
to submit to a server.

Let's Develop It!

Forms

  • Start with your favorite activity calculator
  • Create a form to send dynamic data to the function when you click the button
  • Bonus: check the form input and alert the user if it is invalid

Hints

  • Put a text input in the form to get the name of the activity
  • Put a text input in the form to get the times a month you do the activity
  • Use return false; to prevent the form from submitting normally

Hints

Here's an example form.


  <form id="activitiesForm">
    <label for="activityName">Activity:</label>
    <input type="text" id="activityName" />
    <label for="timesPerMonth">Times a month:</label>
    <input type="text" id="timesPerMonth" />
    <input type="submit" value="Calculate" />
  </form>
            

Example

Are you done or really stuck?

Check out our example.

Questions?

?