Learn JQuery in One Video

JQuery TutorialIn this video we’ll learn pretty much everything about JQuery. We’ll cover how to load the JQuery and JQuery UI libraries. We’ll also cover selecting elements, styling elements, adding text, retrieving text, changing attributes, JQuery events, JQuery animations, JQuery UI, and Ajax.

I did my best to condense everything you’d learn in a standard 200 page book down into one video. All the code used is available below. I also have a link to everything in a compressed form here for download.

If you like videos like this, it helps me when you tell Google with a click here [googleplusone]

Code From the Video

jquerytut.html

<!DOCTYPE HTML>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JQuery Tutorial</title>

  <style type="text/css">
  .highlight { background-color: yellow; }
  </style>

  <!-- Get the JQuery library
  Jquery 1 & 2 are the same except JQuery 2 doesn't
  support IE 6, 7, and 8 -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</head>
<body>
<div id="wrapper">

<h1>Random Stuff</h1>

<p id="p_one"><img src="ntt-logo.png" id="logo2" alt="NTT Logo" height="180" width="180">Lorem ipsum dolor sit amet, consectetur adipiscing elit. <em>Aenean pretium</em>, ipsum quis ultrices aliquet, lacus urna ultrices odio, eu interdum tortor tortor quis ligula. <a href="#">Morbi finibus</a> auctor ipsum vel tempus. Nullam gravida leo ac iaculis pretium. <b>In pretium varius nisi</b>, quis tristique ipsum semper vitae. Mauris eu aliquet odio. Pellentesque tristique sem turpis, id gravida nunc consequat vel. <a href="#">Nullam nec condimentum magna</a>. Sed dignissim interdum risus ac mattis. In hac habitasse platea dictumst. Vivamus placerat tristique vestibulum. Pellentesque quis eleifend nisl. Quisque mollis aliquam enim eu ullamcorper.</p>
<p id="p_two">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean pretium, ipsum quis ultrices aliquet, lacus urna ultrices odio, eu interdum tortor tortor quis ligula. <a href="mailto:derekbanas@verizon.net">Morbi finibus</a> auctor ipsum vel tempus. Nullam gravida leo ac iaculis pretium. In pretium varius nisi, quis tristique ipsum semper vitae. Mauris eu aliquet odio. Pellentesque tristique sem turpis, id <a href="http://google.com">gravida nunc consequat</a> vel. Nullam nec condimentum magna. Sed dignissim interdum risus ac mattis. <a href="http://www.newthinktank.com/wordpress/PersonalityTest.pdf">In hac habitasse</a> platea dictumst. Vivamus placerat tristique vestibulum. Pellentesque quis eleifend nisl. Quisque mollis aliquam enim eu ullamcorper.</p>

<p id="p_three">Lorem ipsum dolor sit amet, consectetur adipiscing elit. <i>Aenean pretium,</i> ipsum quis ultrices aliquet, lacus urna ultrices odio, eu interdum tortor tortor quis ligula.</p>

<table id="tableData">
<caption>Baseball</caption>
<thead>
<tr>
<td colspan="4">Best Baseball Players</td>
</tr>
</thead>
<tfoot>
<tr><td colspan="4">* Hall of Fame</td></tr>
</tfoot>
<tbody>
<tr>
<td></td>
<td>Average</td>
<td>RBIs</td>
<td>Homeruns</td>
</tr>
<tr>
<td><a href="#">Hank Aaron*</a></td>
<td>.305</td>
<td>2297</td>
<td>755</td>
</tr>
<tr>
<td><a href="#">Babe Ruth*</a></td>
<td>.342</td>
<td>2214</td>
<td>714</td>
</tr>
<tr>
<td><a href="#">Barry Bonds</a></td>
<td>.298</td>
<td>1996</td>
<td>762</td>
</tr>
</tbody>
</table>

<h2 id="bestSelling">Best Selling Childrens Books</h2>

<ol id="oListTypes">
<li>Harry Potter
<ol id="oListIndent">
<li>and the Sorcerer's Stone</li>
<li>and the Half-Blood Prince</li>
<li>and the Chamber of Secrets</li>
<li>Prisoner of Azkaban</li>
<li name="best_book">and the Goblet of Fire</li>
<li>and the Order of the Phoenix</li>
<li>and the Deathly Hallows</li>
</ol>
</li>
<li>The Very Hungry Caterpillar</li>
</ol>

<input type="text" id="yourName" size="50">

<input type="text" id="listStuff" size="50"><br />

<h2 id="trackEvents">Tracking Events</h2>

Mouse Click : X : <input type="text" id="mClickXPos">
Y : <input type="text" id="mClickYPos"><br />

Mouse Move : X : <input type="text" id="mMoveXPos">
Y : <input type="text" id="mMoveYPos"><br />

Key Pressed : <input type="text" id="keyPressed"><br />

<span id="formEvent">Form Event</span> : <input type="text" id="inputFormEvent"><br /><br />

<img src="1.jpg" id="accident" alt="accident">

<div id="jsonData"></div>

<button type="button" id="getData">Get Data</button>

<script type="text/javascript">

// When the document is ready execute the JQuery
$("document").ready(function() {

  // ADDING / REMOVING / CHANGING ELEMENTS

  // You can change CSS attributes like this
  // # targets ids and . targets classes
  $("#wrapper").css("width", 500);
  $("#wrapper").css("margin", "auto");
  $("#logo2").css("float", "left");
  $(".p_two").css("color", "purple");

  // How to pass in multiple arguments
  $(".p_two").css({"background" : "url('repeatBkgrnd.png') repeat-y"});

  // Target elements by tag
  $("a").css("color", "red");

  // Target tags only in other tags, classes, or ids
  $("#tableData a").css("color", "green");

  // Target every a element that comes after a em
  $("em + a").css("color", "orange");

  // Target children elements in elements
  $("p > em").css("color", "gray");

  // Target the 3rd li in a list
  $("#oListIndent li:nth-child(3)").css("color", "red");

  // Change the text in an html element if the li has a
  // name attribute
  $("li[name]").html("'and the Goblet of Fire'");

  // Change the value in a text input element
  $("input[type='text']#yourName").val("Derek");

  // Target items that contain a value (*=)
  $("a[href*='google']").css("font-weight", "bolder");

  // Target an image with an alt that starts with (^=) NTT
  // and change the border
  $("img[alt^='NTT']").css({"border-color": "black",
             "border-width":"1px",
             "border-style":"solid"});

  $("a[href^='http://g']").css("color", "cyan");

  $("a[href^='mailto:']").css("color", "yellow");

  // Change an image height and width on one line
  $("img[alt^='NTT']").width(150)
                      .height(150);

  // Target items that end with ($=) a value
  $("a[href$='pdf']").css("color", "red");

  // Select the odd (1,3,5) and even (0,2,4) items
  $("#tableData tr:even").css("background-color", "#FFFDD0");
  $("#tableData tr:odd").css("background-color", "#F0F8FF");

  // Select the first matching element
  $("#tableData tr:first").css({"background-color" : "#001A57", "color" : "white"});

  // Select the last matching element
  $("#tableData tr:last").css("background-color", "#FFC0DB");

  // Select the elements that don't contain 'and' in them
  $("#oListTypes li:not(:contains(and))").css("color", "red");

  // Select every a element that contains 'gravida'
  $("a:contains(gravida)").css("color", "blue");

  // Select every p element that contains a i element
  // and hide it
  $("p:has(i)").hide();

  // Display the text between the matching p element
  alert($("p:has(i)").html());

  // Change the text in the matching p element and show it
  // .text() works the same but it doesn't recognize html
  // elements
  $("p:has(i)").html("<i>Some normal text</i>").show();

  // Append adds text at the end of an element
  $("p:has(i)").append(" I go at the end");

  // Prepend adds text at the beginning of an element
  $("p:has(i)").prepend("I go at the beginning ");

  // Add a new element before the targeted one
  $("p:has(i)").before("<p id='before_p'>A new paragraph before</p>");

  // Add a new element after the targeted one
  $("p:has(i)").after("<p id='after_p'>A new paragraph after</p>");

  // When the element with the id 'after_p' is clicked
  // remove it from the document
  $("#after_p").click(function() {
    $(this).remove();
  });

  // Replace an element with another on click
  $("#before_p").click(function() {
    $(this).replaceWith('<p>I\'m the new paragraph</p>');
  });

  // Perform a different action on each matching element
  $("#oListIndent li").each(function(index) {

    // Get the value in the input element
    var inputListStuff = $("#listStuff").val();

    // Assign a new value to the input element
    // $(this).text() gets the value for each individual
    // li element
    $("#listStuff").val(inputListStuff + ", " + $(this).text());

  });

  // CHANGING ELEMENT ATTRIBUTES

  // Add a class to elements
  // .removeClass() will take the class away
  $("#oListIndent li").addClass("Harry_Potter");

  $(".Harry_Potter").css("color", "#36454F");

  // You can toggle classes on and off an element
  $("#oListIndent li").click(function() {
    $(this).toggleClass("highlight");

    // Get the changing background color and display it
    // in the input element
    var bgColor = $(this).css("background-color");
    $("input[type=text]#yourName").val(bgColor);
  });

  $("#logo2").click(function() {

    // Get the value stored in an attribute
    var imgName = $(this).attr("src");
    $("input[type=text]#yourName").val(imgName);

    // Change the value of an attribute
    $("#logo2").attr("src", "ntt-logo-horz.png");
  });

  // EVENTS IN JQUERY

  // Trigger events on mouseover
  $("#logo2").mouseover(function() {
    $("#logo2").attr("src", "ntt-logo-horz.png");
  });

  // Trigger events on mouseout
  $("#logo2").mouseout(function() {
    $("#logo2").attr("src", "ntt-logo.png");
  });

  // Handle mouseover and mouseout with hover
  $("h2").hover(function() {
    // mouseover
    $("h2").css("color", "green");
  }, function() {
    // mouseout
    $("h2").css("color", "black");
  });

  // Perform an action on double click
  $("#logo2").dblclick(function() {
    $("#logo2").attr("src", "ntt-logo-plastic.png");
  });

  // Get the document x and y position on click
  $(document).click(function(e) {
    $("#mClickXPos").val(e.pageX);
    $("#mClickYPos").val(e.pageY);
  });

  // Get the x and y as the mouse moves
  // Use screenX and screenY to get x and y for the screen
  $(document).mousemove(function(e) {
    $("#mMoveXPos").val(e.screenX);
    $("#mMoveYPos").val(e.screenY);
  });

  // Show key pressed on the keyboard
  // You can also use keydown() and keyup()
  $(document).keypress(function(e){

    // e.which returns the keycode which we convert into
    // the key with fromCharCode
    var keyPressed = String.fromCharCode(e.which)
    $("#keyPressed").val(keyPressed);
  });

  // Execute when input loses focus
  $("#inputFormEvent").blur(function() {
    $("#formEvent").text("Left Input Element");
  });

  // Execute when input value changes (Conflicts with blur)
  $("#inputFormEvent").change(function() {
    $("#formEvent").text("Input Element Changed");
  });

  // Execute when input gains focus
  $("#inputFormEvent").focus(function() {
    $("#formEvent").text("Input Element Focused");
  });

  // Execute when input value is selected
  $("#inputFormEvent").select(function() {
    $("#formEvent").text("Input Element Selected");
  });

  // We can assign events with on and pass the event to
  // track, an argument to pass and the function to call
  // You can attach multiple events by seperating them with
  // a space ex. "mouseover keypress"

  function showWhatTouched(e){
    alert(e.data.message);
  }

  var bsMsg = { message:"Best Selling Touched" };

  var teMsg = { message:"Track Events Touched" };

  $("#bestSelling").on("mouseover", bsMsg, showWhatTouched);

  $("#trackEvents").on("mouseover", teMsg, showWhatTouched);

  // Catch when the document loads with ready()
  // Catch if the browser resizes with resize()
  // Catch when an element is scrolled with scroll()

  // Create simple slide show
  var accidentImgs = ["1.jpg", "2.jpg", "3.jpg", "4.jpg"];

  var focusImg = 1;

  $("#accident").click(function() {

    var image = accidentImgs[focusImg];
    focusImg++;
    if(focusImg > 3){
      focusImg = 0;
    }

    $("#accident").attr("src", image);

  });

  // JQUERY ANIMATIONS

  // hide an element on click
  $("#p_one").click(function() {
    $(this).hide();
  });

  // slowly fade out an element over 2000 ms
  // You can also use fast, normal, and slow
  $("#p_two").click(function() {
    $(this).fadeOut(2000);

    // Redisplay the hidden element
    // You can also use .toggle(), .show() and .fadeIn()
    $("#p_one").fadeToggle(2000);
  });

  // Fade an image to a given opacity
  $("#logo2").click(function() {
    $(this).fadeTo('slow', .50);
  });

  // Target td that contains 'Bonds'
  $("td:contains('Bonds')").click(function() {

    // Hide row that contains a td that contains 'Bonds'
    $("tr:has(td:contains('Bonds'))").slideUp(1000);
  });

  // Make the Bonds row reappear
  // You can also use slideToggle()
  $("td:contains('Hall')").click(function() {
    $("tr:has(td:contains('Bonds'))").slideDown(1000);
  });

  // You can create custom animations with animate
  $("#p_one").click(function() {

    // To define left, right, top or bottom the element must
    // have a position property of relative or absolute
    $(this).css("position", "relative");

    // Pass an object that contains the properties to change,
    // duration in milliseconds, easing function to use for
    // the transition and the function to call after the
    // animation completes
    // The easing method functions are "swing or "linear"
    // You also have the JQuery UI animations : easeInQuad,
    // easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic,
    // easeInOutCubic, easeInQuart, easeOutQuart,
    // easeInOutQuart, easeInQuint, easeOutQuint,
    // easeInOutQuint, easeInExpo, easeOutExpo,
    // easeInOutExpo, easeInSine, easeOutSine, easeInOutSine,
    // easeInCirc, easeOutCirc, easeInOutCirc, easeInElastic,
    // easeOutElastic, easeInOutElastic, easeInBack,
    // easeOutBack, easeInOutBack, easeInBounce,
    // easeOutBounce, easeInOutBounce
    $("#p_one").animate(
    {
      left: 300,
      opacity: .5,
      'font-size': "22px",
      width: 300
    }, 2000, "easeInQuad", function(){alert("All Done");});
  });

  // It is common to use stop to prevent multiple
  // animations on the same object like this
  // $("#p_one").stop().animate( ...

  // JQUERY UI
  // A plug-in that has effects and user interface tools
  // http://jqueryui.com/download/ allows you to
  // customize the widgets you need
  // http://jqueryui.com/themeroller/ allows you to
  // pick the colors, fonts, etc. for the theme used

  // JQUERY AND AJAX
  // Ajax allows a page to update with information from
  // the server without a page reload

}); <!-- End of JQuery Code -->

</script>

</div> <!-- End of wrapper -->

<!-- Most common CSS attributes
https://developer.mozilla.org/en-US/docs/Web/CSS/Reference
  background, background-attachment, background-color, background-image, background-repeat, border, border-bottom, border-color, border-style, border-bottom-color, border-bottom-style, border-bottom-width, border-left-color, border-left-style, border-left-width, border-right-color, border-right-style, border-right-width, border-top-color, border-top-style, border-top-width, box-shadow, color, columns, direction, float, font-family, font-size, font-style, font-weight, height, letter-spacing, line-height, list-style-type, list-style-image, list-style-position, margin, margin-bottom, margin-top, margin-right,margin-left, opacity, padding-bottom, padding-top, padding-right, padding-left, text-align, text-decoration, text-decoration-color, text-decoration-line, text-decoration-style, text-indent, text-orientation, text-shadow, text-transform, vertical-align, visibility, width, word-spacing, z-index
  -->
</body>
</html>

jqueryuitut.html

<!DOCTYPE HTML>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JQuery Tutorial</title>

  <style type="text/css">
  .highlight { background-color: yellow; }
  #wrapper {
    width: 500px;
    margin: auto;
  }
  .ui-menu{
    width: 15em;
  }
  #cartDiv{
    border-style: solid;
    border-width: 5px;
  }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

  <!-- Add the JQuery UI CSS -->
  <link href="css/jquery-ui.min.css" rel="stylesheet">

  <!-- Add the JQuery UI JS file -->
  <script src ="js/jquery-ui.min.js" > </script>

<body>
<div id="wrapper">

<ul id="shMenu">
  <li><a href="JavaScript:void(0)">X Men</a>
    <ul>
      <li><a href="JavaScript:void(0)">Angel</a></li>
      <li><a href="JavaScript:void(0)">Cyclops</a></li>
      <li><a href="JavaScript:void(0)">Beast</a></li>
      <li><a href="JavaScript:void(0)">Marvel Girl</a></li>
      <li><a href="JavaScript:void(0)">Iceman</a></li>
    </ul>
  </li>
  <li><a href="JavaScript:void(0)">Defenders</a>
    <ul>
      <li><a href="JavaScript:void(0)">Hulk</a></li>
      <li><a href="JavaScript:void(0)">Doctor Strange</a></li>
      <li><a href="JavaScript:void(0)">Namor</a></li>
      <li><a href="JavaScript:void(0)">Silver Surfer</a></li>
    </ul>
  </li>
</ul><br />

<div id="accordion">
<h4>Batman</h4>
<div>
Batman is a fictional superhero appearing in American comic books published by DC Comics. The character was created by artist Bob Kane and writer Bill Finger, and first appeared in Detective Comics #27 (May 1939). Originally named "the Bat-Man", the character is also referred to by such epithets as the "Caped Crusader",the "Dark Knight", and the "World's Greatest Detective".
</div>
<h4>Flash</h4>
<div>
The Flash is a fictional superhero appearing in American comic books published by DC Comics. Created by writer Gardner Fox and artist Harry Lampert, the original Flash first appeared in Flash Comics #1 (January 1940).
</div>
<h4>Superman</h4>
<div>
Superman is a fictional superhero appearing in American comic books published by DC Comics. The character is considered an American cultural icon. The Superman character was created by writer Jerry Siegel and artist Joe Shuster in 1933; the character was sold to Detective Comics, Inc. (later DC Comics) in 1938. Superman first appeared in Action Comics #1 (June 1938) and subsequently appeared in various radio serials, newspaper strips, television programs, films, and video games. With the character's success, Superman helped to create the superhero genre and establish its primacy within the American comic book.
</div>
</div><br />

<div id="shTabs">
<ul>
  <li><a href="#ironman">Iron Man</a></li>
  <li><a href="#hulk">Hulk</a></li>
  <li><a href="#thor">Thor</a></li>
  <li><a href="#spiderman">Spiderman</a></li>
</ul>
<div id="ironman">
Iron Man (Tony Stark) is a fictional superhero appearing in American comic books published by Marvel Comics, as well as its associated media. The character was created by writer and editor Stan Lee, developed by scripter Larry Lieber, and designed by artists Don Heck and Jack Kirby. He made his first appearance in Tales of Suspense #39 (cover dated March 1963).
</div>
<div id="hulk">
The Hulk is a fictional superhero appearing in American comic books published by Marvel Comics. The character was created by Stan Lee and Jack Kirby, and first appeared in The Incredible Hulk #1 (May 1962). Throughout his comic book appearances, the Hulk is portrayed as a large green humanoid that possesses immense superhuman strength and great invulnerability, attributes that grow more potent the angrier he becomes. Hulk is the alter ego of Bruce Banner, a socially withdrawn and emotionally reserved physicist who physically transforms into the Hulk under emotional stress and other specific circumstances at will or against it; these involuntary transformations lead to many complications in Banner's life.
</div>
<div id="thor">
Thor is a fictional superhero that appears in American comic books published by Marvel Comics. The character, based on the Norse mythological deity of the same name, is the Asgardian god of thunder and possesses the enchanted hammer Mjolnir, which grants him the ability of flight and weather manipulation amongst his other superhuman attributes.
</div>
<div id="spiderman">
Spider-Man is a fictional superhero appearing in American comic books published by Marvel Comics existing in its shared universe. The character was created by writer-editor Stan Lee and writer-artist Steve Ditko, and first appeared in the anthology comic book Amazing Fantasy #15 (Aug. 1962) in the Silver Age of Comic Books. Lee and Ditko conceived the character as an orphan being raised by his Aunt May and Uncle Ben, and as a teenager, having to deal with the normal struggles of adolescence in addition to those of a costumed crime-fighter.
</div>
</div><br />

<div id ="customDialog" title ="Custom Dialog">
<p>A random dialog box that contains important information</p>
</div>

<a href="JavaScript:void(0)" id="openDialog" title="Open Dialog Box">Open Dialog</a><br /><br />

<form action="#" id="sampForm">

Present:<br />
<select name="present" id="present">
<option>Toy</option>
<option>Video Game</option>
<option>Book</option>
<option>Money</option>
</select><br />

Birthday:<br />
<input type="text" name="birthday" id="birthday"><br /><br />

<p class="numOfPresents">Number of Presents</p>

<fieldset>
    <legend>Number of Presents</legend>
    <div id="radioPresents">
      <input type="radio" id="onePresent" name="presents" checked="checked">
      <label for="onePresent">1</label>

      <input type="radio" id="twoPresent" name="presents">
      <label for="twoPresent">2</label>

      <input type="radio" id="threePresent" name="presents">
      <label for="threePresent">3</label>
    </div>
  </fieldset>

<br />

<input type="button" id="randButton" value="Click Me"><br /><br />

<div id="cartDiv">
<img src="cart.png" alt="Shopping Cart" id="cart">
</div>

<img src="toy1.png" alt="Bear" id="toy1" class="toy">

<img src="toy2.png" alt="Duck" id="toy2" class="toy">

<img src="toy3.png" alt="Batman" id="toy3" class="toy">

</form>

<script type="text/javascript">

$(document).ready(function() {

  $("#shMenu").menu({
    position: {
      // Popup menu comes on the right by default
      my: "center top",
      at: "center bottom"
    },

  });

  $("#accordion").accordion({
    // Slide animation or not or length
    animate: 1500,
    // Starting tab
    active: 1,
    // Collapsible if same tab is clicked
    collapsible: true,
    // Event that triggers
    event: "click",
    // Height based on content (content) or largest (auto)
    heightStyle: "content"
  });

  $("#shTabs").tabs({
    // The event that switches the panel
    event: "click",
    // Effects: fadeIn, fadeOut, slideDown, slideUp, animate
    show: "fadeIn",
    hide: "fadeOut",
    // Starting panel
    active: 3,
    // Collapse by clicking the current tab
    collapsible: true,
    // Height based on content (content) or largest (auto)
    heightStyle: "auto"
  });

  // Create a draggable / resizable dialog box
  $('#customDialog').dialog({
    draggable: true, // Set true by default
    resizable: false, // Set true by default
    // You can use minWidth, minHeight, maxWidth, maxHeight
    height: 300, // Defined in pixels
    width: 300,
    // If set true the user can't do anything until the
    // dialog is closed
    modal: true,
    // Position the dialog with my and define the browser
    // position with at
    // 1st: left, right, center
    // 2nd: top, center, bottom
    position: {
      my: 'center top',
      at: 'center bottom',
      // You can also target to place based on an element
      // on the screen (center under the link)
      of: "#openDialog"
    },
    // Define a delay for showing or hiding it
    show: 1000,
    hide: '1000',
    autoOpen: false, // Open true by default
    // create buttons for the dialog
    buttons : {
      "OK" : function(){
        $("#openDialog").html("You clicked ok");
        $(this).dialog("close");
      },
      "CANCEL": function(){
        $("#openDialog").html("You clicked cancel");
        $(this).dialog("close");
      }
    }
  });

  // Displays the dialog box on click
  $("#openDialog").click(function() {
    $('#customDialog').dialog("open");
  });

  // Use custom tooltip if the element has a title
  $("[title]").tooltip();

  // JQUERY UI FORMS

  $("#present").selectmenu({
    width: 200
  });

  $("#birthday").datepicker({
    // Show month dropdown
    changeMonth: true,
    // Show year dropdown
    changeYear: true,
    dateFormat: "MM dd, yy",
    // Number of months to display
    numberOfMonths: 1,
    // Define maxDate
    maxDate: 365,
    // Define minDate
    minDate: -3650
  });

  // Style radio buttons
  $("#radioPresents").buttonset();

  // Style buttons
  $("#randButton").button();

  // You can make any element draggable
  $("#sampForm").draggable();

  // Dragging and dropping elements
  $("#toy1").draggable();
  $("#toy2").draggable();
  $("#toy3").draggable();

  $("#cartDiv").droppable({
    // Adds the class highlight to the droppable
    activeClass: "highlight",

    // Adds class for when element is hovered
    hoverClass: "hoverDroppable",

    // Function to call when element is dropped
    drop: function(event, ui){

      // Apply an effect when an element is dropped
      // clip, explode, fade, puff,
      // pulsate, scale, shake, slide,
      ui.helper.hide("fade");

      // Get the alt for the itm dropped
      var itemAlt = $(ui.draggable).attr("alt");

      // Display the item dropped
      alert("Item added : " + itemAlt);
    },

    // Define class of elements that can be dropped
    accept: ".toy",

    // Can elements currently be dropped on it
    disabled: false,

    // Add an element when droppable items starts to drag
    activate: function(event, ui){

      $("#cartMsg").remove();
      $(this).append("<span id='cartMsg'>Drop Toy Here</span>");
    },

    // Called when an item isn't dropped in the dropzone
    deactivate: function(event, ui){

      $("#cartMsg").remove();
      $(this).append("<span id='cartMsg'>You know you want it</span>");
    },

    // Called when draggable is over droppable
    over: function(event, ui){

      $("#cartMsg").remove();
      $(this).append("<span id='cartMsg'>Drop It!!!</span>");
    },

    // Called when item leaves dropzone
    out: function(event, ui){

      $("#cartMsg").remove();
      $(this).append("<span id='cartMsg'>NOOOOOO!!!</span>");
    }
  });

}); // End of JQuery

</script>

</div> <!-- End of Wrapper -->
</body>
</html>

jqueryajaxtut.html

<!DOCTYPE HTML>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JQuery Tutorial</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>

<h3>Playing with Server Data</h3>
<div>
  <h3>Message from the Server:</h3>
  <p id="first">Waiting for Message</p>
</div>

<form id="theForm">
  <button type="button" id="oneButton">Get Text</button><br />

<div>
  <h3>Double Number on the Server:</h3>
  <span></span><br />
</div>

<input type="text" name="data" id="data"></input>
<button type="button" id="twoButton">Double Number</button><br /><br />
<button type="button" id="threeButton">Get XML Data</button>

</form>

<div>
  <h3>XML Data from the Server:</h3>
</div>

<div id="customers">Customer Information</div>

<script type="text/javascript">
$("document").ready(function() {
  $("#oneButton").on("click",getInfoFromServer);
  $("#twoButton").on("click",getDblFromServer);
  $("#threeButton").on("click",getXmlFromServer);
});

// Pull text from a text file on the server
// Type defines the type of request to make being GET or POST
// Success defines the function to call if the request
// succeeds
// Error could be defined to specify the function to call if
// an error happens

function getInfoFromServer() {
$.ajax({
  type: "GET",
  url: "textFromServer.txt",
  success: postToPage});
}

// Function called to display the message from the server
// Receives the text and the server status
function postToPage(data, status) {
  $('#first').text(data);
}

// Load a value into a span
// I define that the program getDouble.php should be executed
// getDouble is sent the information in the form and then it
// stores the returned info in the span

function getDblFromServer() {
  $("span").load("getDouble.php",
  $("#theForm").serializeArray());
}

// Here I define that I'm receiving xml data from the server

function getXmlFromServer() {
$.ajax({
  type: "GET",
  url: "customers.xml",
  datatype: "xml",
  success: postToPageTwo});
}

// I use the find method to search through the xml data
// When I match for any of these attributes I append them to
// the div named customers

function postToPageTwo(data) {

  $(data).find('customer').each(function(){
    var id = $(this).attr('id');
    var firstName = $(this).find('firstName').text();
    var lastName = $(this).find('lastName').text();
    var street = $(this).find('street').text();
    var city = $(this).find('city').text();
    var zip = $(this).find('zip').text();

    $('<div class="firstname"></div>').html(firstName).appendTo('#customers');

    $('<div class="lastname"></div>').html(lastName).appendTo('#customers');

    $('<div class="street"></div>').html(street).appendTo('#customers');

    $('<div class="city"></div>').html(city).appendTo('#customers');

    $('<div class="zip"></div><br />').html(zip).appendTo('#customers');

  });
}
</script>
</body>
</html>

textFromServer.txt

Bunch of random text

GetDouble.php

<?php
// Get the value passed
$numberToDbl = $_POST["data"];

// Create the response
echo $_POST["data"] . " Times 2 Equals ";
$doubleUp = $numberToDbl * 2;
echo $doubleUp;
?>

customers.xml

<?xml version="1.0" encoding="iso-8859-1"?>
<customers>
  <customer id="0">
    <firstName>Paul</firstName>
    <lastName>Jones</lastName>
    <street>123 Main St</street>
    <city>Anywhere</city>
    <zip>15235</zip>
  </customer>

  <customer id="1">
    <firstName>Sally</firstName>
    <lastName>Jones</lastName>
    <street>123 Main St</street>
    <city>Anywhere</city>
    <zip>15235</zip>
  </customer>
</customers>

Leave a Reply

Your email address will not be published. Required fields are marked *