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

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
  • Used by nearly 20 million(!) websites

Including jQuery

Two ways to include jQuery on your page:
Download the library, store it locally:

  <head>
    <script type="text/javascript" src="jquery.js"></script>
  </head>
          
Include the the live library:

  <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js">
    </script>
  </head>
          
Note: live code can change! It's always best to download

Exercise

  • Create a new HTML file.
  • Download jquery here. Copy it to the same folder as your HTML
  • You might want to rename the file to "jquery.js" for simplicity
  • Link the jQuery library to this HTML file.
  • Include the link to jQuery inside of your <head> tags, like we did on the last slide

jQuery Selectors

Remember document.getElementByTagName()?

(used to get a list of all the tag elements)

JavaScript code:

    var divs = document.getElementsByTagName("div");
            

The same line, translated into jQuery!


    var divs = $("div"); 
            

jQuery Selectors

Remember document.getElementById()?

(used to get a list of all the elements by ID)

JavaScript code:

    var myHeader = document.getElementById("myHeader");
            

The same line, translated into jQuery!


    var myHeader = $("#myHeader"); 
            

jQuery Selectors

Class name (.result, .picture)

     var images = $(".picture"); //All images with class picture 
            
make sure you include the dot, before the classname

Exercise

What is the difference between these two selectors

          $("#myElement"); 
            
And

          $(".myElement"); 
            
Why do we need both types of selectors? hint
spoiler alert... next slide has the answer, so think about this before you move on

          $("#myElement"); 
            
The above code will select the single element with id "myElement" in your HTML. There should only be one unique element on the page with that id. (if you didn't read the hint, it's helpful )

          $(".myElement"); 
            
The above code will select all of the elements with the class attribute "myElement". If you have multiple elements with this class, the above code will return a list of those elements

What is an API?

  • Application Programming Interface
  • Specifies how software components should interact with each other
  • Data structure and rules for accessing a web-based application

jQuery Actions

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

All the actions are methods, specified in the jQuery API

As methods they are called with dot notation

Action format

        $(selector).action();     
            

Document Ready

Webpages take time to load

Almost always, you don't want the JavaScript to be called until the page is loaded

Document ready is a method called when the page is loaded

        $(document).ready(function(){
          
        });
            
Note: The function() inside is an "anonymous function". It has no name, but still performs like a function.

Exercise


        $(document).ready(function(){
           $(".myElement").hide();
        });
        

Why doesn't document need quotes around it, while other selectors do need quotes?

answer ->


        $(document).ready(function(){
           $(".myElement").hide(); // needs quotes
        });
        

* document is already a defined object

* When creating selectors like $(".myElement"), you need to pass a string into the selector.

* the parameter inside of $( ) needs to be a string or a predefined variable (like document)

* Use single or double quotes within the parenthesis in cases like:


  $("div").hide(); // hides all divs
  $(".myClass").hide(); // hides all elements with class myClass
        

HTML events

Events occur on a webpage via user interaction

Common Events:

  • mouseenter -- mouse goes inside an element
  • mouseleave -- mouse leaves an element
  • click -- mouse clicks an element
  • Other events

Handling events


  $(selector).click(function(){
    //code when the selector is clicked
  });
      

  $('.myElement').click(function(){
    $(this).hide();
  });
      
The $(this) selector in jQuery refers to the element on whom the action was called.
Here $(this) is the $('.myElement') that we clicked.

Handling event examples

// Change the background to purple when the mouse hovers over the element
      $('.myElement').mouseenter(function(){
        $(this).css('background-color', 'purple')
      });
            
// Change the background to orange when the mouse leaves the element
      $('.myElement').mouseleave(function(){
        $(this).css('background-color', 'orange')
      });
          
 // Change the background to green when you click the element
      $('.myElement').click(function(){
        $(this).css('background-color', 'green') 
      })
          

Exercise

  • Add a div to a new (or existing) HTML document
  • Make sure jQuery is linked to your HTML file
  • Create a new div in the HTML body with class myElement
  • Add some text into that div, so you can see it
  • Try applying the 3 examples (on the last slide) to that element.
  • Make sure you add your code inside of document.ready(...);
  • $(document).ready(function(){
      // your code goes here!
    
    });

Combining events

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


      $('.myElement').bind({
        click: function() {
          $(this).css('background-color', 'green')
        },
        mouseenter: function() {
          $(this).css('background-color', 'purple')
        },
        mouseleave: function(){
          $(this).css('background-color', 'orange')
        }
      });
          

Let's Develop it!

Start with this HTML
<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Demo</title>
</head>
<body>
    <p>this is a PARAGRAPH</p>
    <div id="myId">This is a DIV with id "myId"!</div>
    <div class="myClass">This is a DIV with class "myClass"!</div>
    <a href="http://jquery.com/" id="myLink">jQuery</a>
    <script src="jquery.js"></script>
    <script>
    // Your code goes here.
    </script>
</body>
</html>
            

Let's develop it!

  • When you click on the paragraph, hide it
  • When you click on div myId, hide it
  • When you click on div myClass, hide it

  • To hide an element, use the .hide() method
  • Remember to use $(this) to locate the element that is receiving the action
  • If you get ahead, add a button to your HTML that uses the .slideToggle() method to show or hide the jquery link from the HTML
  • Remember you can research more about a method in the jQuery API

Updating attributes and css


  <img id="mainpicture" src="http://girldevelopit.com/assets/pink-logo.png">         
            
Attribute get and set

  var img = $('#mainpicture');
  img.attr('src');
  img.attr('src', 'http://girldevelopit.com/assets/pink-logo.png');
            
CSS property get and set

  var img = $('#mainpicture');
  img.css('width');
  img.css('width', '200px');
            

Exercise

What is the difference between

    $(document).ready(function(){
        $('#mainpicture').css('width', '100px');
    });
            
And

    $(document).ready(function(){
        $('#mainpicture').click(function(){
            $('#mainpicture').css('width', '100px');
        });
    });            
        

Exercise answer


    $(document).ready(function(){
        $('#mainpicture').css('width', '100px');
    });
            

The code above will resize the image as soon as the page loads


    $(document).ready(function(){
        $('#mainpicture').click(function(){
            $('#mainpicture').css('width', '100px');
        });
    });            
        

The code above will load the webpage normally with the image at its normal size. When you click the picture, it will resize it

Updating values and html


  <div id = "results">Boo!</div>         
            
Set the html value

  var div = $('#results');
  div.html('New html!'); // sets the HTML
            
Get the html value

  var div = $('#results');
  div.html(); // gets the HTML
            

Exercise

In an HTML document that has jQuery hooked up, add the following div

  <div id = "results">Boo!</div>         
            

when you click on the div with Boo!, change the text to New html!

if you want an extra challenge, use the bind() method to also add a mouseleave and mouseenter event to that div

Append and Prepend


  <div id = "results">Boo!</div>         
            
Append html

    var div = $('#results');
    div.append('Additional html');
            
Prepend html

    var div = $('#results');
    div.prepend('Additional html (on top)');
            

Creating new element


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

Let's Develop It!

Try to convert last week's DOM interaction into jQuery.

Don't forget to include jQuery in your html head!

Let's Develop It

  • Add a div to your html that is 100px by 200px
  • Bind events to the div in your javascript file
  • Don't forget to surround your events with document ready
  • Try to change size, color, or even the html inside the div
  • Bonus: change all the onclick events to jQuery click events

Questions?

?