Chapter 12.5: jQuery

CS 80: Internet Programming

Instructor: Mark Edmonds

jQuery

  • A lightweight javascript library
  • Main advantage: provides a lot of functionality in a minimal amount of code
    • Works across browsers and platforms
    • Means you don't have to worry about minor differences between browsers
  • Makes practical javascript much easier

Importing jQuery

  • jQuery is hosted by many large companies

                <!-- import your own local jQuery -->
            <script src="jquery-3.1.0.min.js"></script>
            <!-- import Google's hosting of jQuery -->
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

jQuery Basics

  • Conceptual starting points
    • We will select HTML elements and then perform some action on the elements
    • Basic syntax:
                $(selector).action()
    • $ indicates we are using jQuery
    • ( selector ) finds corresponding HTML elements
    • action() performs some action on the elements

Anonymous Functions

  • Anonymous functions are functions without a name

  • We had subtly been using anonymous functions when we assigned variables to functions

  • Remember:

                // javascript anonymous function declaration
            var sum2 = function(a,b){
              return a + b;
            }

Anonymous Functions

  • Remember:

                // javascript anonymous function declaration
            var sum2 = function(a,b){
              return a + b;
            }
  • The right hand side of this assignment has no name!

  • We'll be seeing this pattern more, don't freak out!

Document Loading

  • Previously, we used the following paradigm to wait until the page is ready:

                // wait for document to load to run the start function
            window.addEventListener("load", start, false);
    
            function start(){
              // startup code
            }
  • jQuery makes this a lot easier…

                // equivalent to adding an event listener for when document is loaded
            $( document ).ready(function() {
              // startup code
            }); //notice the syntax of this, we are passing an anonymous function as a parameter! (see the ");" ending the parameter

Document Loading

  • What does this do?
    • $(document) Selects the document
    • .ready() is a a jQuery event
    • The anonymous function is the callback to call when the event is trigger
    • Notice how similar this is to what we did before, but with much simpler code
      • We didn't have to register a listener for the page loading, then define another function for the start of the DOM interaction.
      • jQuery does this in one step!

jQuery Selectors

  • * - select all
  • #id - select id id
  • .class - select CSS class class
  • ele - select all HTML ele elements
  • You can also use comma separated values to select multiple selectors
    • E.g. .class1,.class2 will select both .class1 and .class2
  • See: http://www.w3schools.com/jquery/jquery_ref_selectors.asp

Old Example: loading_event_listeners.html

<!DOCTYPE html>
        <html>

        <head>
          <meta charset=utf-8 />
          <title>Proper Loading</title>
          <script>
            
            function start(){
              document.getElementById("p1").addEventListener("mouseenter", addHighlight);
              document.getElementById("p1").addEventListener("mouseleave", removeHighlight);
            }

            document.addEventListener("DOMContentLoaded", start);
            
            // the following line will not work! DOM is not loaded (yet) 
            //start();

            function addHighlight() {
              var p1 = document.getElementById("p1");
              p1.setAttribute("style", "background-color: #3F6");
            }
            
            function removeHighlight() {
              var p1 = document.getElementById("p1");
              p1.removeAttribute("style");
            }
          </script>
        </head>

        <body>
          <p id="p1">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque faucibus augue in risus tempus viverra. Etiam gravida augue a venenatis sollicitudin. Praesent varius ex varius, accumsan libero vel, bibendum eros. Aenean tristique mattis sem id scelerisque. In cursus ultrices massa nec tristique. Phasellus efficitur ac neque eu suscipit. Donec volutpat pretium justo, eget fringilla sapien. Integer vitae metus eget lorem auctor vestibulum non ut risus. Aenean hendrerit iaculis sapien. Nunc vestibulum purus quam, nec consequat sem cursus a. Aenean interdum euismod dui id dapibus. Curabitur vel placerat purus. Etiam dolor turpis, dictum in augue sit amet, suscipit suscipit leo. Aliquam auctor fringilla ligula, vitae sodales ligula facilisis quis. Donec consequat molestie tempus. Donec faucibus elit ullamcorper ante accumsan congue.
          </p>
        </body>

        </html>
        

Exercise

  • How can we achieve the same with jQuery?
  • Hint: you have the .mouseenter(), .mouseleave(), .attr(), and .removeAttr() jQuery actions

Example: highlighting_mouse.html

<!DOCTYPE html>
        <html>

        <head>
          <meta charset=utf-8 />
          <title>Proper Loading</title>
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
          <script>
            
          $(document).ready(function(){
            $("#p1").mouseenter(addHighlight);
            $("#p1").mouseleave(removeStyle);
          });

          function addHighlight(){
            $("#p1").attr("style", "background-color: #3F6");
          }

          function removeStyle(){
            $("#p1").removeAttr("style");
          }

          </script>
        </head>

        <body>
          <p id="p1">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque faucibus augue in risus tempus viverra. Etiam gravida augue a venenatis sollicitudin. Praesent varius ex varius, accumsan libero vel, bibendum eros. Aenean tristique mattis sem id scelerisque. In cursus ultrices massa nec tristique. Phasellus efficitur ac neque eu suscipit. Donec volutpat pretium justo, eget fringilla sapien. Integer vitae metus eget lorem auctor vestibulum non ut risus. Aenean hendrerit iaculis sapien. Nunc vestibulum purus quam, nec consequat sem cursus a. Aenean interdum euismod dui id dapibus. Curabitur vel placerat purus. Etiam dolor turpis, dictum in augue sit amet, suscipit suscipit leo. Aliquam auctor fringilla ligula, vitae sodales ligula facilisis quis. Donec consequat molestie tempus. Donec faucibus elit ullamcorper ante accumsan congue.
          </p>
        </body>

        </html>

        

Exercise

  • How would we do this with anonymous functions?

Example: highlighting_mouse_anon.html

<!DOCTYPE html>
        <html>

        <head>
          <meta charset=utf-8 />
          <title>Proper Loading</title>
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
          <script>
            
          $(document).ready(function(){
            $("#p1").mouseenter(function(){
              $("#p1").attr("style", "background-color: #3F6");
            });
            $("#p1").mouseleave(function(){
              $("#p1").removeAttr("style");
            });

          });
          </script>
        </head>

        <body>
          <p id="p1">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque faucibus augue in risus tempus viverra. Etiam gravida augue a venenatis sollicitudin. Praesent varius ex varius, accumsan libero vel, bibendum eros. Aenean tristique mattis sem id scelerisque. In cursus ultrices massa nec tristique. Phasellus efficitur ac neque eu suscipit. Donec volutpat pretium justo, eget fringilla sapien. Integer vitae metus eget lorem auctor vestibulum non ut risus. Aenean hendrerit iaculis sapien. Nunc vestibulum purus quam, nec consequat sem cursus a. Aenean interdum euismod dui id dapibus. Curabitur vel placerat purus. Etiam dolor turpis, dictum in augue sit amet, suscipit suscipit leo. Aliquam auctor fringilla ligula, vitae sodales ligula facilisis quis. Donec consequat molestie tempus. Donec faucibus elit ullamcorper ante accumsan congue.
          </p>
        </body>

        </html>


        

Exercise

  • But this is not very resuable
  • Why?

Exercise

  • But this is not very resuable
  • Why?
    • We can't make #p1 a variable!
    • And cannot easily highlight other IDs
  • Fix?

Example: highlighting_mouse_anon_func.html

<!DOCTYPE html>
        <html>

        <head>
          <meta charset=utf-8 />
          <title>Proper Loading</title>
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
          <script>
            
          $(document).ready(function(){
            highlightOnMouseEnter("#p1");
            highlightOnMouseEnter("#p2");
          });
          
          function highlightOnMouseEnter(selector){
            $(selector).mouseenter(function(){
              $(selector).attr("style", "background-color: #3F6");
            });
            $(selector).mouseleave(function(){
              $(selector).removeAttr("style");
            });
          };
          </script>
        </head>

        <body>
          <p id="p1">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque faucibus augue in risus tempus viverra. Etiam gravida augue a venenatis sollicitudin. Praesent varius ex varius, accumsan libero vel, bibendum eros. Aenean tristique mattis sem id scelerisque. In cursus ultrices massa nec tristique. Phasellus efficitur ac neque eu suscipit. Donec volutpat pretium justo, eget fringilla sapien. Integer vitae metus eget lorem auctor vestibulum non ut risus. Aenean hendrerit iaculis sapien. Nunc vestibulum purus quam, nec consequat sem cursus a. Aenean interdum euismod dui id dapibus. Curabitur vel placerat purus. Etiam dolor turpis, dictum in augue sit amet, suscipit suscipit leo. Aliquam auctor fringilla ligula, vitae sodales ligula facilisis quis. Donec consequat molestie tempus. Donec faucibus elit ullamcorper ante accumsan congue.
          </p>
          <p id="p2">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque faucibus augue in risus tempus viverra. Etiam gravida augue a venenatis sollicitudin. Praesent varius ex varius, accumsan libero vel, bibendum eros. Aenean tristique mattis sem id scelerisque. In cursus ultrices massa nec tristique. Phasellus efficitur ac neque eu suscipit. Donec volutpat pretium justo, eget fringilla sapien. Integer vitae metus eget lorem auctor vestibulum non ut risus. Aenean hendrerit iaculis sapien. Nunc vestibulum purus quam, nec consequat sem cursus a. Aenean interdum euismod dui id dapibus. Curabitur vel placerat purus. Etiam dolor turpis, dictum in augue sit amet, suscipit suscipit leo. Aliquam auctor fringilla ligula, vitae sodales ligula facilisis quis. Donec consequat molestie tempus. Donec faucibus elit ullamcorper ante accumsan congue.
          </p>
        </body>

        </html>
        

Example: highlighting_mouse_anon_func.html

  • This is a good example of how to modularize and expand a simple example into a reusable segment of code

jQuery Animation

  • jQuery can animate CSS property changes!

  • The property changes must be numerical (e.g. cannot animate background-color: red)

  • The properties are contained in a set of curly braces like so (this data format is called JSON, which we will cover later):

                { css-prop1: value, css-prop2: value }

Exercise

  • Write an animation to change a box's hieght and width to 300px when the user's mouse enters the box. The box should start at 100px by 100px and return to that size when the mouse leaves

Example: animation.html

<!DOCTYPE html>
        <html>

        <head>
          <!-- use google's hosting of jQuery -->
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
          <!-- write our own jQuery code using the script above -->
          <script>
            $(document).ready(function() {
              $("#box").mouseenter(function() {
                $("#box").animate({
                  height: "300px",
                  width: "300px"
                });
              });
              $("#box").mouseleave(function() {
                $("#box").animate({
                  height: "100px",
                  width: "100px"
                });
              });
            });
          </script>
        </head>

        <body>
          <div id="box" style="background:#98bf21; height:100px; width:100px; margin:6px;"></div>
        </body>

        </html>