JavaScript! Yay!!!

So, we've finally gotten to the portion of the class where we get to work with JavaScript. JavaScript is a browser or client-side, interpretive, scripting language that has been around since 1995, when it was called LiveScript and it was maintained by the browser company Netscape as a way of adding interactivity to web pages. We're going to be exploring JavaScript via jQuery, a very popular JavaScript framework that is currently blowing up huge. 

framework, in this sense, is a comprehensive library of shortcut methods (a.k.a. functions) and objects that are all built with JavaScript. In other words, developers took many of the functions and classes they had already been using in JavaScript, stuck them all in a single library file, and made them accessible with shortcut syntax that we call jQuery.

Example #1

We'll start with a simple example. Create an HTML doc with the following code and call it index.html:

  1. <!doctype html>
  2. <!--[if lt IE 7]> <html lang="en"> <![endif]-->
  3. <!--[if IE 7]> <html lang="en"> <![endif]-->
  4. <!--[if IE 8]> <html lang="en"> <![endif]-->
  5. <!--[if gt IE 8]><!--> <html lang="en"> <!--<![endif]-->
  6. <meta charset="utf-8">
  7. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title></title>
  8. <meta name="description" content="">
  9. <meta name="author" content=""> <meta name="viewport" content="width=device-width">
  10. <link rel="stylesheet" href="css/style.css"> <script src="js/libs/modernizr-2.5.3.min.js"></script>
  11. </head>
  12. <body>
  13. <p>
  14. jQuery is not loaded.
  15. </p>
  16. <script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
  17. <script>window.jQuery || document.write('<script src="js/libs/jquery-3.1.0.js"><\/script>')</script> <script src="js/plugins.js"></script>
  18. <script src="js/script.js"></script>
  19. </body>
  20. </html>



Then create the following CSS file and name it style.css:

  1. @charset "UTF-8";
  2. /* CSS Document */
  3. body { font: 16px sans-serif; }
  4.  
  5. p { color: red; border: 1px solid red; padding: 5px; margin: 5px; }
  6.  
  7. p.tmpFrameworkLoaded { color: green; border: 1px solid green; }


and place the following JavaScript in a js/script.js file:

  1. // JavaScript Document
  2. if ($) {
  3.  
  4. $(document).ready( function() {
  5.  
  6. $('p').addClass('tmpFrameworkLoaded');
  7.  
  8. $('p').text('jQuery successfully loaded and running!');
  9.  
  10. } );
  11.  
  12. }

Example #1 in action

In the previous code, we created a simple HTML5 document with nothing special in the body: 

<p>jQuery is not loaded.</p>

But if we then load this into a browser, we will see the following:  

jquery not loaded

This shouldn't be all that suprising, since that message appears in the HTML. But the jQuery code we place in script.js should have given us the following: 

jquery loaded

This example is a simple test to see if jQuery has loaded properly. Since we didn't download the jQuery library, it should be no surprise that it doesn't work. Downloading jQuery is easy: simply go to the  jQuery.com download section and download the most recent version (compressed or uncompressed – it doesn't matter, though compressed is smaller in size and, therefore, loads faster).  Whichever version you have, you'll see that it is contained inside a single JavaScript file. This file should be saved into a js/libs folder like so:

jquery install
Once you have installed (a.k.a. saved) jQuery, open up your index.html file in a browser again to test it.


Example #1 Explained

So here's what is going on the previous example. The HTML is pretty simple: just a simple <p> tag with a default message in it. In the CSS file we created, this simple style declaration:

p { color: red; border: 1px solid red; padding: 5px; margin: 5px; }

which applies to all <p> tags in the HTML document, including the aforementioned <p> tag, and the message text within it. In the script.js file we have the following code: 


$('p').addClass('tmpFrameworkLoaded');This code uses the jQuery object selector ($) and, in this case, it is selecting all HTML <p> elements in the DOM. It is then calling the jQuery addClass function on all <p> tags. This nifty function simply attaches CSS classes to whatever elements it is "chained" to.  The class that is attached is passed as a parameter to the addClass function, adding to (and, in this case, overiding) whatever styles the tag had prior. In this case the class is .tmpFrameworkLoaded , the definition of which is defined in our CSS file:

p.tmpFrameworkLoaded { color: green; border: 1px solid green; }

The next line of jQuery uses the jQuery text function to change the text within all <p> and </p> tags to whatever string of characters is passed as a parameter: 

$('p').text('jQuery successfully loaded and running!'); 

If jQuery has indeed been loaded successfully, the $s, the addClass and text functions, and all the other jQuery syntax in our script.js file should work and we will be presented with an HTML document, altered directly in the browser, to look like this:

jquery loaded


How Is This Better Than Good Ole' JavaScript? 

I'm so glad you asked! Well, this is a simple example – realy only a couple of choice lines – that changes a few things around in our DOM (Document Object Model).  As simple as it is, however, if we wanted to do the same thing using standard JavaScript, with no APIs or frameworks, it would look like this:

  1. // JavaScript Document
  2. window.onload = function() {
  3.  
  4. var $p = document.getElementsByTagName('p')[0];
  5.  
  6. $p.className = 'tmpFrameworkLoaded';
  7.  
  8. if($p.innerText) {
  9.  
  10. $p.innerText = 'jQuery successfully loaded and running!';
  11.  
  12. } else {
  13.  
  14. $p.textContent = 'jQuery successfully loaded and running!';
  15.  
  16. }
  17.  
  18. };

Yikes! Variable declarations?! getElementsBy TagName?! If/else statements?! That code is a hot mess! However, before jQuery was invented in 2006, this was the only way to do it. 


So What Makes jQuery Better? 

One thing that makes jQuery far easier to implement than standard Javascript is its selectors API. We're already quite familar with the concept of a selector: we've been using them constantly in our CSS files. In the following code snippet, bodya, and .highlight and all selectors:

body{ padding: 0px; margin: 0px; background: url("/images/bg.gif") #ccc no-repeat; }
a:link, a:hover{ color: red; }
.highlight{ color: black; background-color: yellow; }

As you can see, selectors are what CSS uses to reference HTML elements in general, and class names and ID tag specifically, with the intent of making them look and feel a certain way. In jQuery the concept is the same, but rather than determine styling,  jQuery determines behavior. Take the following HTML code...go on, literally take it, and save it as an HTML document.

Example #2: Controlling Links

  1. <!doctype html><!--[if lt IE 7]> <html lang="en"> <![endif]--><!--[if IE 7]> <html lang="en"> <![endif]--><!--[if IE 8]> <html lang="en"> <![endif]--><!--[if gt IE 8]><!-->
  2. <html class="no-js"lang="en"><!--<![endif]-->
  3. <head>
  4. <metacharset="utf-8">
  5. <metahttp-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  6. <metaname="description" content="">
  7. <metaname="author" content="">
  8. <metaname="viewport" content="width=device-width">
  9. <link rel="stylesheet" href="css/style_02.css">
  10. <script src="js/libs/modernizr-2.5.3.min.js"></script>
  11. </head>
  12. <body>
  13. <ul id="tmpFavorites">
  14. <li><a href="<a href="http://www.google.com">Google</a></li>">http://www.google.com">Google</a></li></a>
  15. <li><a href="<a href="http://www.facebook.com">FaceBook</a></li>">http://www.facebook.com">FaceBook</a></li></a>
  16. <li><a href="<a href="http://www.apple.com">Apple</a></li>">http://www.apple.com">Apple</a></li></a>
  17. <li><a href="<a href="http://instagr.am/">Instagram</a></li>">http://instagr.am/">Instagram</a></li></a>
  18. </ul>
  19. <script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.js" ></script>
  20. <script>window.jQuery ||document.write('<script src="js/libs/jquery-3.1.0.js"><\/script>')</script>
  21. <script src="js/plugins.js"></script>
  22. <script src="js/script_02.js"></script>
  23. </body>
  24. </html>

The HTML above contains a simple un-ordered list of common links. Nothing special... We're going to add a stylesheet containing the following code:

  1. @charset "UTF-8";
  2. /* CSS Document */
  3. body { font: 16px sans-serif; }
  4.  
  5. ul {
  6. list-style: none;
  7. margin: 0;
  8. padding: 0;
  9. }
  10.  
  11. a{ text-decoration: none; }


and finally we're going to place the following jQuery code in our script.js file

  1. // JavaScript Document
  2. //create a new js object called tempExample
  3. var tmpExample = {
  4. //create a member method called ready
  5. ready : function(){
  6. // Find and return all links in ul#tmpFavorites, found in the jQuery object ($)...
  7. //attach a click event to each link
  8. $("ul#tmpFavorites li a").click(
  9. //pass the click event an anonymous function, with the event object ($e) as a parameter...
  10. function($e){
  11. //use the preventDefault() function to inhibit the default link click action
  12. $e.preventDefault();
  13. //and instead open a new browser window (or tab)
  14. window.open(this.href, "CoolLinks", ""); }
  15. //first parameter: the URL opened in the new window
  16. //second parameter: the name of the window or tab
  17. //third paramterL: a string containing window options, which we're leaving blank for now.
  18. );
  19. }
  20. };
  21. /*the above object and function doesn't get called until the entire document, and thus the DOM, has loaded. To make sure of this, we'll pass a reference to the tmpExample's ready function using the built-in jQuery $(document).ready*/
  22.  
  23. $(document).ready(tmpExample.ready);

Example #2: Explained

The jQuery code above is fully commented, but here is a rundown of what it's doing: 1.) The tmpExample object is created, along with a member method entitled ready. Then it just sits there in memory. 2.) As soon as the DOM is fully loaded, jQuery calls the $(document).ready() function we placed inside our script.js file. But notice we also passed it a reference to the tmpExample.ready object method, declared above. 3.) Because we did this, the browser will also execute this code.   

This example demonstrates the essence of the jQuery selector API: after the DOM is fully loaded into the browser's memory, this bit of code: 
<span style="line-height: 22.4px;">$(‘ul#tmpFavorites li a’).click()</span>

uses the main jQuery selector ($) and then more specifically selects all links with each list item of the unnumbered list with the #tmpFavorites ID. It looks a lot like CSS, and this is not a coincidence: the jQuery selector API was developed to be familiar to CSS developers…like us!


Example #3: Toggling a Popup Div

So let's try another example using selectors. Using the following HTML code:

  1. <!doctype html><!--[if lt IE 7]> <html lang="en"> <![endif]--><!--[if IE 7]> <html lang="en"> <![endif]--><!--[if IE 8]> <html lang="en"> <![endif]--><!--[if gt IE 8]><!-->
  2. <html class="no-js"lang="en"><!--<![endif]-->
  3. <head>
  4. <metacharset="utf-8">
  5. <metahttp-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  6. <metaname="description" content="">
  7. <metaname="author" content="">
  8. <metaname="viewport" content="width=device-width">
  9. <link rel="stylesheet" href="css/style_03.css">
  10. <script src="js/libs/modernizr-2.5.3.min.js"></script>
  11. </head>
  12. <body id="tmpDialogueExample" >
  13. <form action="javascript:void(0);" method="post">
  14. <p> In jQuery, the selector API allows you to select elements from the DOM, just like you do in CSS stylesheets. This simple dialogue contains a few selector API examples. </p>
  15. <p>
  16. <input type="submit" name="tmpDialogueOpen" id="tmpDialogueOpen" value="Open Dialogue" />
  17. </p>
  18. <div id="tmpDialogue" >
  19. <input type="submit" name="tmpDialogueClose" id="tmpDialogueClose" value="Close Dialogue" />
  20. </div>
  21. </form>
  22. <script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.js" ></script>
  23. <script>window.jQuery ||document.write("<script src='js/libs/jquery-3.1.0.js'><\/script>")</script>
  24. <script src="js/plugins.js"></script>
  25. <script src="js/script_03.js"></script>
  26. </body>
  27. </html>


and the following styles in a css/style.css file:

  1. @charset "UTF-8";
  2. /* CSS Document */
  3. body {
  4. font: 16pxsans-serif;
  5. }
  6.  
  7. div#tmpDialogue {
  8. display: none;
  9. position: absolute;
  10. top: 50%;
  11. left: 50%;
  12. width: 500px;
  13. height: 500px;
  14. margin: -251px 0 0-251px;
  15. border: 1px solid blue;
  16. background: lightblue; }
  17.  
  18. body#tmpDialogueExample div.tmpDialogueOn { display: block; }
  19.  
  20. input#tmpDialogueClose {
  21. position: absolute;
  22. bottom: 5px;
  23. right: 5px;
  24. width: 100px;
  25. }


In our scripts.js file, place the following javascript:

  1. // JavaScript Document
  2. var tmpExample ={
  3. ready : function(){
  4. $('input#tmpDialogueOpen').click(
  5. function($e){
  6. $e.preventDefault();
  7. $('div#tmpDialogue').addClass('tmpDialogueOn');
  8. }
  9. );
  10. $('input#tmpDialogueClose').click(
  11. function($e){
  12. $e.preventDefault();
  13. $('div#tmpDialogue').removeClass('tmpDialogueOn');
  14. }
  15. );
  16. }
  17. };
  18.  
  19. $(document).ready(tmpExample.ready);

Example 3: Explained

On the surface, the above example works similar to the previous example: the jQuery ready function is called after the document loads. Chained to this ready function is our custom tmpExample.ready function. This function does two things:

1.)It attaches a jQuery click() event function to the first submit button in the HTML, labeled with the #tmpDialogueOpen ID attribute. This click function takes as its parameter an anonymous function. The event object ($e) is passed to it so that we can prevent the default action of this event: $e.preventDefault();. Finally, we add a class to the tmpDialogue div. 

This new class, you may notice, simply unhides the div#tmpDialogue, set to display:none; in the css.

2.)tmpExample.ready also attaches a second click() event, as seen in the code above. This event does something similar to the previous click() event, but in this case it is attached the submit button labelled #tmpDialogueClose, and it removes the .tmpDialogueOn class from the #tmpDialogue div. As #tmpDialogue's native style is to display none, this line of code essentially re-hides it.

The result is something like a kind of toggling popup window:

Screen Shot 2012-04-14 at 5.07.09 PM


Example #4: Refining Selectors

One more example, this time a little more advanced. [Click here] to see it in action. You can find the code [

Example #4: Explained

The HMTL is fairly straightforward: Two unnumbered lists and a section of links below it. Upon closer inspection, you will notice that nearly every tag is classed and/or IDed. For example: <ul id='tmpPlants'> and <li class='tmpVegetables' id='tmpOnion'>Onion</li>.

  1. <!doctype html>
  2. <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
  3. <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
  4. <!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]-->
  5. <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
  6. <meta charset="utf-8">
  7. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  8. <meta name="description" content="">
  9. <meta name="author" content="">
  10. <meta name="viewport" content="width=device-width">
  11. <link rel="stylesheet" href="css/style.css">
  12. <script src="js/libs/modernizr-2.5.3.min.js"></script>
  13. </head>
  14. <body id='tmpDialogueExample'>
  15. <div id='tmpSelection'>
  16. <div class='tmpList'>
  17. <h4>Edible Plants</h4>
  18. <ul id='tmpPlants'>
  19. <li class='tmpVegetables' id='tmpOnion'>Onion</li>
  20. <li class='tmpVegetables' id='tmpBroccoli'>Broccoli</li>
  21. <li class='tmpVegetables' id='tmpPepper'>Pepper</li>
  22. <li class='tmpVegetables' id='tmpCarrot'>Carrot</li>
  23. <li class='tmpFruits'>Apple</li>
  24. <li class='tmpFruits'>Cherry</li>
  25. <li class='tmpFruits' id='tmpOrange'>Orange</li>
  26. <li class='tmpFruits'>Lemon</li>
  27. </ul>
  28. </div>
  29. <div class='tmpList'>
  30. <h4>Animals</h4>
  31. <ul id='tmpAnimals'>
  32. <li id='tmpChicken'>Chicken</li>
  33. <li id='tmpCow'>Cow</li>
  34. <li id='tmpBuffalo'>Buffalo</li>
  35. <li id='tmpSheep'>Sheep</li>
  36. <li id='tmpRabbit'>Rabbit</li>
  37. </ul>
  38. </div>
  39. </div>
  40. <div id='tmpRecap'>
  41. <p>
  42. <a href='#' id='tmpFind'>
  43. Find all &amp;lt;li&amp;gt; elements inside of &amp;lt;ul&amp;gt; elements.
  44. </a>
  45. </p>
  46. <p>
  47. <a href='#' id='tmpSiblings'>
  48. Find all siblings of the &amp;lt;li&amp;gt; element with id tmpCarrot.
  49. </a>
  50. </p>
  51. <p>
  52. <a href='#' id='tmpNext'>
  53. Select the &amp;lt;li&amp;gt; sibling element after the &amp;lt;li&amp;gt; element
  54. with id name tmpBroccoli.
  55. </a>
  56. </p>
  57. <p>
  58. <a href='#' id='tmpPrev'>
  59. Select the &amp;lt;li&amp;gt; sibling element before the &amp;lt;li&amp;gt; element
  60. with id name tmpBroccoli.
  61. </a>
  62. </p>
  63. <p>
  64. <a href='#' id='tmpNextAll'>
  65. Select all &amp;lt;li&amp;gt; sibling elements after the &amp;lt;li&amp;gt; element
  66. with id name tmpBroccoli.
  67. </a>
  68. </p>
  69. <p>
  70. <a href='#' id='tmpPrevAll'>
  71. Select all &amp;lt;li&amp;gt; sibling elements before the &amp;lt;li&amp;gt; element
  72. with id name tmpOrange.
  73. </a>
  74. </p>
  75. <p>
  76. <a href='#' id='tmpVegetables'>
  77. Select only &amp;lt;li&amp;gt; sibling elements before the &amp;lt;li&amp;gt;
  78. element with id name tmpOrange that are vegetables.
  79. </a>
  80. </p>
  81. <p>
  82. <a href='#' id='tmpParents'>
  83. Find the parent &amp;lt;div&amp;gt; element, with id tmpSelection.
  84. </a>
  85. </p>
  86. <p>
  87. <a href='#' id='tmpParent'>
  88. Find parent &amp;lt;ul&amp;gt; elements of &amp;lt;li&amp;gt; elements.
  89. </a>
  90. </p>
  91. <p>
  92. <a href='#' id='tmpChildren'>
  93. Find children &amp;lt;h4&amp;gt; elements of parent &amp;lt;div&amp;gt; elements with
  94. class name tmpList.
  95. </a>
  96. </p>
  97. <p>
  98. <a href='#' id='tmpNot'>
  99. Select children &amp;lt;li&amp;gt; elements of parent &amp;lt;ul&amp;gt; elements,
  100. except for vegetables.
  101. </a>
  102. </p>
  103. <p>
  104. <a href='#' id='tmpSlice'>
  105. Select &amp;lt;li&amp;gt; elements beginning with Cow and ending with Sheep.
  106. </a>
  107. </p>
  108. <p>
  109. <a href='#' id='tmpAdd'>
  110. Select all animal &amp;lt;li&amp;gt; elements, then add Pepper and Broccoli.
  111. </a>
  112. </p>
  113. <p>
  114. <a href='#' id='tmpEq'>
  115. Select all &amp;lt;li&amp;gt; elements, and reduce to only Buffalo.
  116. </a>
  117. </p>
  118.  
  119. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
  120. <script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.2.js"><\/script>')</script>
  121.  
  122. <script src="js/plugins.js"></script>
  123. <script src="js/script.js"></script>
  124. </body>
  125. </html>

This is done to achieve granular selection in jQuery (described below).


The CSS is also straightforward:

  1. body {
  2. font: 16px sans-serif;
  3. }
  4. ul {
  5. list-style: none;
  6. padding: 0;
  7. margin: 0;
  8. width: 200px;
  9. }
  10. li {
  11. padding: 3px;
  12. margin: 3px;
  13. }
  14. div.tmpList {
  15. float: left;
  16. margin: 0 20px;
  17. }
  18. div#tmpRecap {
  19. clear: left;
  20. padding: 10px;
  21. }
  22. .tmpExample {
  23. border: 1px solid rgb(200, 200, 200);
  24. background: #cbe5f8;
  25. }
  26. div#tmpSelection {
  27. overflow: hidden;
  28. }


The jQuery code, inside the script.js file, uses the same surface logic as the previous examples: creating an object with a ready function, then calling that object.function when the document is fully loaded:

  1. var tmpExample = {
  2. ready : function() {
  3. // Find all <input> elements and add a click
  4. // event.
  5. $('a').click(tmpExample.findElements);
  6. },
  7.  
  8. findElements : function($e)
  9. {
  10. // Prevent the default action, navigating to the link.
  11. $e.preventDefault();
  12.  
  13. // Reset the example before applying the next.
  14. $('*').removeClass('tmpExample');
  15.  
  16. switch (this.id)
  17. {
  18. case 'tmpFind':
  19. {
  20. // If the id of "this" <input> element contains "Find",
  21. // Do the find() example.
  22. $('ul').find('li').addClass('tmpExample');
  23. break;
  24. }
  25. case 'tmpSiblings':
  26. {
  27. $('li#tmpCarrot').siblings().addClass('tmpExample');
  28. break;
  29. }
  30. case 'tmpNext':
  31. {
  32. $('li#tmpBroccoli').next().addClass('tmpExample');
  33. break;
  34. }
  35. case 'tmpPrev':
  36. {
  37. $('li#tmpBroccoli').prev().addClass('tmpExample');
  38. break;
  39. }
  40. case 'tmpNextAll':
  41. {
  42. $('li#tmpBroccoli').nextAll().addClass('tmpExample');
  43. break;
  44. }
  45. case 'tmpPrevAll':
  46. {
  47. $('li#tmpOrange').prevAll().addClass('tmpExample');
  48. break;
  49. }
  50. case 'tmpVegetables':
  51. {
  52. $('li#tmpOrange').prevAll('li.tmpVegetables').addClass('tmpExample');
  53. break;
  54. }
  55. case 'tmpParents':
  56. {
  57. $('li#tmpCarrot').parents('div#tmpSelection').addClass('tmpExample');
  58. break;
  59. }
  60. case 'tmpParent':
  61. {
  62. $('li').parent('ul').addClass('tmpExample');
  63. break;
  64. }
  65. case 'tmpChildren':
  66. {
  67. $('div.tmpList').children('h4').addClass('tmpExample');
  68. break;
  69. }
  70. case 'tmpNot':
  71. {
  72. $('ul li').not('li.tmpVegetables').addClass('tmpExample');
  73. break;
  74. }
  75. case 'tmpSlice':
  76. {
  77. $('ul#tmpAnimals li').slice(1, 4).addClass('tmpExample');
  78. break;
  79. }
  80. case 'tmpAdd':
  81. {
  82. $('ul#tmpAnimals li').add('li#tmpBroccoli, li#tmpPepper').addClass('tmpExample');
  83. break;
  84. }
  85. case 'tmpEq':
  86. {
  87. $('ul li').eq(10).addClass('tmpExample');
  88. break;
  89. }
  90. }
  91. }
  92. };
  93.  
  94. $(document).ready(tmpExample.ready);


It attaches a click() event to each link in the HTML, with the tmpExample.findElements function call passed as the click event parameter. This ensures that tmpExample.findElements function, defined below tmpExample.ready, is called whenever a link is clicked.

The Switch Statement

findElements() is actually pretty simply too, it just uses a code construct we haven't seen before: the switch statementSwitch statements are pretty universal throughout the programming world. They can be thought of as switchboards: the statement checks the given input value and, based on this value, fires off a specific set of instructions. In our example, the switch statement is looking for the ID of whatever link called the findElements() function:

switch (this.id)Then the statement defines eventualities for every link ID case we're interested in with case statements. Every case statement ends with the break; command. This exits the case, thereby exiting the switch statment as well. Some examples of the case statements in our code: 


case 'tmpSiblings':{   $('li#tmpCarrot').siblings().addClass('tmpExample');   break;}–and–case 'tmpVegetables':{ $('li#tmpOrange').prevAll('li.tmpVegetables').addClass('tmpExample');   break;} These cases simply add the .tmpExample class to specific list items, but notice how jQuery is going about selecting them: siblings(), prevAll(), children(), parents(), etc. These methods allow you to search and filter the selection results you obtain. More on this below.


A Rundown of the jQuery Filters

The previous example is really designed to show you all of the jQuery Selector API's filtering functions in a single script. Let's examine each on a case by case basis.

find(): The find() method lets you search for elements within a selection you’ve already made. Below, we select all ul tags, then find() all li tags within them so we can add the .tmpExample class to each one:


  case 'tmpFind':
{
// If the id of "this" <input> element contains "Find",
// Do the find() example.
   $('ul').find('li').addClass('tmpExample');
   break;
}


siblings(): The siblings() method lets you select all elements on the same hierarchical level as your main selection, in this case all other list items in the same list as <li id="tmpCarrot">:

case 'tmpSiblings':
{
   $('li#tmpCarrot').siblings().addClass('tmpExample');
   break;
}

next(): The next() method lets you select the next sibling element in the HTML document:

case 'tmpNext':
{
   $('li#tmpBroccoli').next().addClass('tmpExample');
break;
}

prev(): Similar to next(), the prev() method lets you select the preceding sibling element in the HTML document:

case 'tmpPrev':
{
   $('li#tmpBroccoli').prev().addClass('tmpExample');
   break;
}


nextAll() and prevAll(): these two methods work similarly to next() and prev(), except they select all sibling elements after and before your main selection respectively: 

case 'tmpNextAll':
{
   $('li#tmpBroccoli').nextAll().addClass('tmpExample');
break;
}
case 'tmpPrevAll':
{
   $('li#tmpOrange').prevAll().addClass('tmpExample');
   break;
}


This instance of the prevAll() method has been passed a parameter, which further narrows its searching power to only select those previous siblings of #tmpOrange that happened to have the .tmpVegetables class:

case 'tmpVegetables':
{
   $('li#tmpOrange').prevAll('li.tmpVegetables').addClass('tmpExample');
   break;
}

parents(): not surprisingly, parents() selects all parents of a selected element. In this example, however, parents() is being passed a selector for the tmpSelection div, further narrowing it to just that parent: 

case 'tmpParents':
{
   $('li#tmpCarrot').parents('div#tmpSelection').addClass('tmpExample');
   break;
}

parent(): Note that parent() is different than parents() in that it only selects the most immediate parent of the select element:

case 'tmpParent':
{
   $('li').parent('ul').addClass('tmpExample');
break;
}

children(): this method can be used to select specific children elements of a selected element, in this case all h4 tags in the tmpList div: 

case 'tmpChildren':
{
   $('div.tmpList').children('h4').addClass('tmpExample');
   break;
}

not(): The not() method allows to essentially deselect specific elements. In the case below, we want to select all list items, except those with the .tmpVegetables class: 

case 'tmpNot':
{
   $('ul li').not('li.tmpVegetables').addClass('tmpExample');
   break;
}


slice(): this method takes a beginning index value and ending index value as its parameters, allowing you to select a range of elements within a selection. 

case 'tmpSlice':
{
   $('ul#tmpAnimals li').slice(1, 4).addClass('tmpExample');
   break;
}


add(): The add() method allows to make a selection and then add elements to it, useful for constructing complicated selections of elements. Below we make a standard jQuery selection of all list items in the tmpAnimals unnumbered list, then we add the tmpBroccoli and tmpPepper list items.

case 'tmpAdd':
{
   $('ul#tmpAnimals li').add('li#tmpBroccoli, li#tmpPepper').addClass('tmpExample');
   break;
}


eq(): this method allows you to reduce a selection based on its index number. In the following example, we select all list items, which returns an array of all list items in the DOM. The then eq() method is chained to our selection and passed an index number of 10. Because indexes always start at 0, eq(10) selects the 11th list item in the DOM, i.e. "Buffalo": 

case 'tmpEq':
{
   $('ul li').eq(10).addClass('tmpExample');
   break;
}



Events in jQuery

Not surpisingly, event handlers in any programming language exist to deal with events: mouse clicks, mouse moves, drags, drops. In short, user interaction. Creating event handlers in oldschool JavaScript used to be really difficult, but jQuery makes it much easier. There are a few ways to deal with events in jQuery, but the bind() method is by far the easiest. 

The bind() method accepts two parameters: 

  1. the event name, such as ‘ready’, ‘mouseover’, ‘mouseout’, or ‘click’  
  2. a function call or anonymous function declaration (i.e. the entire body of the function is passed in as one lone parameter) 
Try the following example:

Example 5: the jQuery bind() method

[click here to see example 5 in action] [click here to download the Example 05 files]

 The bind() method simply attaches some other function or method to a particular event. In the case below, we have a very basic HTML5 document:

  1. <!doctype html>
  2. <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
  3. <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
  4. <!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]-->
  5. <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
  6. <meta charset="utf-8">
  7. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title></title>
  8. <meta name="description" content="">
  9. <meta name="author" content=""> <meta name="viewport" content="width=device-width">
  10. <link rel="stylesheet" href="css/style.css">
  11. <script src="/js/libs/modernizr-2.5.3.min.js"></script>
  12. </head>
  13. <body>
  14. <div></div>
  15. <div></div>
  16. <div></div>
  17. <div></div>
  18. <div></div>
  19. <div></div>
  20. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
  21. <script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.2.min.js"><\/script>')</script>
  22. <script src="js/plugins.js"></script>
  23. <script src="js/script.js"></script>
  24. </body>
  25. </html>


And some simple CSS:

  1. @charset "UTF-8";
  2. /* CSS Document */
  3. div {
  4. border: 1px solid rgb(200, 200, 200);
  5. width: 100px;
  6. height: 100px;
  7. margin: 5px;
  8. float: left;
  9. }
  10. div.tmpExampleOver {
  11. background: #5092c5;
  12. }
  13. div.tmpExampleOn {
  14. background: #165b91;
  15. }


and the following  jQuery code in our script.js file:

  1. // JavaScript Document
  2. $(document).bind(
  3. 'ready',
  4. function() {
  5. $('div').bind(
  6. 'mouseover',
  7. function() {
  8. $(this).addClass('tmpExampleOver');
  9. }
  10. );
  11.  
  12. $('div').bind(
  13. 'mouseout',
  14. function() {
  15. $(this).removeClass('tmpExampleOver');
  16. }
  17. );
  18.  
  19. $('div').bind(
  20. 'click',
  21. function() {
  22. if ($(this).hasClass('tmpExampleOn')) {
  23. $(this).removeClass('tmpExampleOn');
  24. } else {
  25. $(this).addClass('tmpExampleOn');
  26. }
  27. }
  28. );
  29.  
  30. }
  31. );


The resulting index.html file, rendered in a browser, should look something like this:

example 05

[click screenshot to see the actual page in a browser]

As you can see, the six divs change background color as you hover the mouse over them (mouseover events), change back to their original background color when the mouse moves out (mouseout events) and toggles a dark blue background color when you click on any of them(click event). Let’s see how it works, shall we? 

Example 5: Explained

The HTML and CSS is fairly straightforward: six anonymous divs in the HTML, styled as six squares by the CSS. The CSS also has two additional classes: they add background colors for the mouseover state and the clicked state, respectively:

div.tmpExampleOver {
    background: #5092c5;
}

div.tmpExampleOn {
    background: #165b91;
}

 As per usual, the jQuery is where the interaction happens. The first thing that occurs is a use of the bind() method to attach further functions to the entire document when the ready event is detected:

$(document).bind( 'ready', ...)


The bind() method accepts two parameters: 1.)the event name, in this case ready and 2.) a function call or anonymous function declaration. We’ll be passing an entire anonymous function as one big parameter. The function we’re passing is really just three simple subroutines:

1.)To each div tag we’re binding a mouseover event function that adds the tmpExampleOver upon detecting any mouse over event:

    $('div').bind( 'mouseover',
        function() {
        $(this).addClass('tmpExampleOver');
      }
    );

2.)Then to each div we’ll bind an event that essentially undoes what we just did when the mouse leaves the div area: 

    $('div').bind(  'mouseout',
      function() {
        $(this).removeClass('tmpExampleOver');
      }
    );

And finally we’ll bind a click event to each div that adds tmpExampleOn class if it isn’t attached, and removes the class if it is attached: 

    $('div').bind(
      'click',
      function() {
        if ($(this).hasClass('tmpExampleOn')) {
          $(this).removeClass('tmpExampleOn');
        } else {
          $(this).addClass('tmpExampleOn');
        }
      }
    );


Advanced Event Handling 

As I said before, there a plenty of interesting ways to handle events in jQuery. The following example covers four of them:

Example 6: Advanced Event Handling Examples

[click here to play with this example in a browser] [click here to get the example code]

The HTML and CSS for this example is very similar to that of example 05 above, i.e. some anonymous divs styled to be 100px by 100px squares. The code found in the script.js file provides four different examples of the innovative and simple ways to deal with events. Each of these functions is declared when the document has loaded via this line of jQuery:

$(document).ready( function(){...});

Let’s examine each example. The first uses the standard bind() method we used in the previous example, but notice that it combines, or chains, three bind() methods together like so: $('div.tmpBind').bind(...).bind(...).bind(...); You may also notice that we’re using the find() method to find all children div tags within the div.tmpBind.

EXAMPLE 06.01:

  1. function() {
  2. //Example 06.01: handling events with the bind() method:
  3. $('div.tmpBind').bind(
  4. 'mouseover',
  5. function() {
  6. $(this).find('div').addClass('tmpExampleOver');
  7. }
  8. ).bind(
  9. 'mouseout',
  10. function() {
  11. $(this).find('div').removeClass('tmpExampleOver');
  12. }
  13. ).bind(
  14. 'click',
  15. function() {
  16. if ($(this).find('div').hasClass('tmpExampleOn')) {
  17. $(this).find('div').removeClass('tmpExampleOn');
  18. } else {
  19. $(this).find('div').addClass('tmpExampleOn');
  20. }
  21. }
  22. );
  23. //end of Example 01// JavaScript Document

Rather than bind(), Example 06.02 uses jQuery’s mouseover()mouseout(), and click() methods directly to add event functions, chaining them together like so:

$('div.tmpIndividual').mouseover(...).mouseout(...).click();

EXAMPLE 06.02:


  1. $('div.tmpIndividual').mouseover(
  2. function() {
  3. $(this).find('div').addClass('tmpExampleOver');
  4. }
  5. ).mouseout(
  6. function() {
  7. $(this).find('div').removeClass('tmpExampleOver');
  8. }
  9. ).click(
  10. function() {
  11. if ($(this).find('div').hasClass('tmpExampleOn')) {
  12. $(this).find('div').removeClass('tmpExampleOn');
  13. } else {
  14. $(this).find('div').addClass('tmpExampleOn');
  15. }
  16. }
  17. );
  18. //end of Example 02


Example 06.03 uses the very convenient jQuery hover() and toggle() methods.

The hover() methods takes two functions as parameters, following this pattern:

$(‘the_element’).hover( the function to be called when the mouse is moved over the_element,  the function to be called when the mouse is moved away from the_element);

The toggle() method is similar, except it deals with clicks rather than mouseover events:

$(‘the_element’).toggle(the function to be called when the mouse is clicked on the_element,  the function to be called when the mouse is clicked a again on the_element);

EXAMPLE 06.03:

  1. $('div.tmpPattern').hover(
  2. function() {
  3. $(this).find('div').addClass('tmpExampleOver');
  4. },
  5. function() {
  6. $(this).find('div').removeClass('tmpExampleOver');
  7. }
  8. ).toggle(
  9. function() {
  10. $(this).find('div').addClass('tmpExampleOn');
  11. },
  12. function() {
  13. $(this).find('div').removeClass('tmpExampleOn');
  14. }
  15. );


And finally Example 06.04, which uses JavaScript methods focus() and blur() to deal with what happens when a browser gives focus (or removes it) from different user interface elements. In this case, we have a simple <textarea> tag. Users can ‘focus’ on things like textareas or input boxes by using the tab key on their keyboard, or by clicking on them directly. ‘blur’ refers to what happens when the user tabs away or clicks somewhere else. Using the focus() and blur() methods, we can define event functions for precisely this type of user interaction:

EXAMPLE 06.04:

  1. $('div.tmpTrigger textarea').focus(
  2. function($e) {
  3. $(this).addClass('tmpFocused');
  4. }
  5. ).blur(
  6. function() {
  7. $(this).removeClass('tmpFocused');
  8. }
  9. );
  10. $('div.tmpTrigger textarea').focus();
  11. }

Above we are essentially adding the class .tmpFocused when a user focuses on the textarea in div#tmpTrigger, then removing that class when focus is removed, or blurred, as it is called. Also notice the last line in the function: 

$('div.tmpTrigger textarea').focus();


This forces browser focus on our textarea. Just calling the focus() method on a focussable element like <textarea> will give it immediate focus in the browser. (Note that with HTML5, this can be done without any JavaScript at all, as it is a built-in property of the new HTML5 form elements. However, it’s always nice to have fallbacks.)