jQuery introduction
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

jQuery introduction

on

  • 2,910 views

 

Statistics

Views

Total Views
2,910
Views on SlideShare
2,906
Embed Views
4

Actions

Likes
5
Downloads
114
Comments
0

4 Embeds 4

http://www.slideshare.net 1
http://twitter.com 1
http://paper.li 1
http://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

jQuery introduction Presentation Transcript

  • 1. jQueryintroduction
  • 2. Stijn Van Minnebruggenweb developer attwitter.com/donotfoldwww.donotfold.be
  • 3. jQueryintroduction
  • 4. course overviewintroduction to JavascriptDOMjQuery why jQuery? what is jQuery? how to implement?
  • 5. course overviewmethodseventseffectsAjaxutilities
  • 6. Javascripta brief introduction
  • 7. history Javascript exists since 1995 much has happened but not much has changed it’s one of the most popular programming languages on the web mostly because of the advent of Ajax
  • 8. how to implement?<html><head> <title>My first Javascript</title></head><body> <script type=”text/javascript”> // javascript goes here </script></body></html>
  • 9. commentsComment on a single line// this is a commentor multiple lines/*multiple linesof commentsare cool too*/
  • 10. variablesVariables can be strings, numbers, arrays,objects, functions, booleans, ...var name = "Stijn"; // stringvar six = 6; // numbervar colors = ["red", "blue", "green"]; // arrayvar wall = { type: "brick", color: "red" }; // objectvar pretty = true; // boolean
  • 11. debuggingDebugging Javascript is easiest with Firebug orthe developer toolbar in Chrome, Safari or IEconsole.log("Send a general log message");console.warn("Log a warning");console.alert("Log an error message");alert("You can always alert messages, but this is rather limited and irritating");
  • 12. logicMight look simple...var thisIsTrue = true;if(thisIsTrue) { console.log("Yes, its true!");} else { console.log("Dont think so...");}if(2 * 3 == 6) { console.log("I can do math");} else { console.log("I suck at math");}
  • 13. logicMight look simple... but can be tricky sometimesvar numberOne = 1;var numberTwo = 2;var stringOne = "1";numberOne == numberTwo // returns falsenumberOne != numberTwo // returns truenumberOne == stringOne // returns truenumberOne === stringOne // returns falsenumberOne === parseInt(stringOne) // returns truenumberOne < numberTwo // returns truenumberOne > numberTwo // returns falsenumberOne <= numberTwo // returns true
  • 14. mathMight look simple...var a = 10;var b = 1;var c = "1";var d = a + b;var e = a + c;b++;
  • 15. mathMight look simple... but can be tricky sometimesvar a = 10;var b = 1;var c = "1";var d = a + b; // 11var e = a + c; // "101"b++; // 2;
  • 16. loopsThese loops all output the samefor(var i=1; i<=10; i++) { console.log(i);}var i = 1;while(i<10) { console.log(i++);}var i = 1;do { console.log(i++);} while(i<10);
  • 17. l∞psThese loops all output the same Always make sure tofor(var i=1; i<=10; i++) { console.log(i); validate your loops} before running them ;)var i = 1;while(i<10) { You don’t want to console.log(i++);} make infinite loops.var i = 1;do { console.log(i++);} while(i<10);
  • 18. arraysArrays have predefined functionsvar colors = ["green", "red", "blue", "yellow"];console.log(colors.length); // logs 4console.log(colors[0]); // logs "green"console.log(colors[3]); // logs "yellow"colors.push("fuchsia"); // adds "fuchsia" to the end of the arraycolors[2] = "sky"; // changed "blue" to "sky"var colorsString = colors.join(",");console.log(colorsString); // logs "green,red,sky,yellow,fuchsia";
  • 19. objectsObjects have keys and values.The key is a string, the value can be a number,string, array, boolean, function or even an otherobjectvar me = { name: "Stijn", age: 28, cool: true, parents: ["mom", "dad"]};
  • 20. functionsFunctions contain blocks of code that can beexecuted repeatedlyfunction yawn() { console.log("... yaaaawn ...");}yawn(); // logs "... yaaaawn ..."
  • 21. functionsVariables can also be functionsvar yawn = function() { console.log("... yaaaawn ...");};yawn(); // logs "... yaaaawn ..."
  • 22. functionsFunctions can have zero or more parameters andmight return any valuevar kissie = function(person1, person2) { var theLine = person1+" and "+person2+" are sitting in a tree, k-i-s-s-i-n-g!"; return theLine;};console.log(kissie("Will", "Kate"));
  • 23. scopeVariables might be “global” or “local” dependingon the location where you declare them.When a variable is declared within a functionusing the var keyword, it will only be availablewithin this function. Code outside that functionwouldn’t be able to access it.
  • 24. scopeVariables that are declared within a functionaren’t accessible outside the function.function whatsMyName() { var name = "Stijn"; console.log(name);}whatsMyName(); // logs "Stijn"console.log(name); // logs undefined
  • 25. scopeBut variables that are declared outside a functioncan be accessed within a function.var name;function whatsMyName() { name = "Stijn"; console.log(name);}whatsMyName(); // logs "Stijn"console.log(name); // logs "Stijn"
  • 26. scopeRemember: Variables are declared with the varkeyword. Declare a variable within a function andit’s only accessible within the function.var name = "Stijn";function whatsMyName() { var name = "Ben"; console.log(name);}whatsMyName(); // logs "Ben"console.log(name); // logs "Stijn"
  • 27. DOMdocument object model
  • 28. HTML vs DOMBefore you want to implement Javascript on your websiteit is key to know that Javascript works on the DOM, noton the HTML.
  • 29. HTML vs DOM
  • 30. HTML vs DOMHTML (text)
  • 31. HTML vs DOMHTML Browser (text)
  • 32. HTML vs DOMHTML Browser DOM (text) (XML)
  • 33. HTMLJust plain text.<html><head><title>This is an awesome HTML page.</title></head><body><h1>Awesome!</h1><p>Totally rad, dude.</p></body></html>
  • 34. DOMAn XML structure based on the HTML“How the browser sees and works with HTML”<html> <head> <title>This is an awesome HTML page.</title> </head> <body> <h1>Awesome!</h1> <p>Totally rad, dude.</p> </body></html>
  • 35. jQueryjavascript library
  • 36. why jQuery?easy to use Javascripta lot of usefull predefined functions and methods“write less, do more”do it all (some other libraries are specialized in x or y)lightweightwide range of plugins available for various specificneedseasy to learn
  • 37. what is jQuery? it’s a javascript library that simplifies the use of javascript especially for HTML document traversing, event handling, animating, Ajax interactions, ... it’s just plain old javascript and open-source: http://code.jquery.com/jquery-latest.js
  • 38. how to implement?<html><head> <title>My first jQuery</title></head><body> <script type=”text/javascript” src="jquery.js"></script> <script type=”text/javascript”> // javascript goes here </script></body></html>
  • 39. jQuerybasics
  • 40. $
  • 41. $ = jQuery
  • 42. $ = jQueryyou can either choose to use $ or jQuery in your code, these variables are equal
  • 43. $(selector)
  • 44. get a DOM element$(selector)
  • 45. $(selector).function();
  • 46. $(selector).function(); execute a jQuery function
  • 47. $(selector).function(parameters);
  • 48. optional parameters$(selector).function(parameters);
  • 49. optional get a DOM parameters element$(selector).function(parameters); execute a jQuery function
  • 50. rule of thumb:$(selector).function(parameters);
  • 51. example:$(“h2”)
  • 52. example: $(“h2”) get all H2 elementsfrom DOM
  • 53. example:$(“h2”).css();
  • 54. example:$(“h2”).css(); execute the jQuery “css” function
  • 55. example:$(“h2”).css(“color”, “#FFCC33”);
  • 56. example:$(“h2”).css(“color”, “#FFCC33”); set the color to #FFCC33
  • 57. jQueryselectors
  • 58. All selector $(“*”) Get all elements from the DOM Is extremely slow and not recommendedvar numberOfElements = $("*").length;console.log("jQuery found "+numberOfElements+" elements on this page");
  • 59. Element selector $(“tagname”) Select all elements with a specific tagName No special characters needed$("div").css("border", "1px solid red");
  • 60. ID selector $(“#id”) Selects a single element with the given ID attribute Very efficient, one of the quickest ways to get an element The ID selector uses a hash before it’s name$("#myDiv").css("border", "1px solid red");Notice: Each ID value must be used only once within a document, otherwise thisdocument won’t be valid. If more than one element has been assigned the sameID, jQuery will only select the first. This behavior should not be relied on though.
  • 61. Class selector $(“.classname”) Select all elements with the given class An element can have multiple classes, only one of them must match The class selector uses a dot before the class name$(".myClass").css("border", "1px solid red");
  • 62. Multiple selector $(“a, b, c, ...”) jQuery allows multiple selections methods in one selector string It will select the combined result of all the specified selectors Combine as many selectors as you like by the use of commas$("h1, #myDiv, .myClass").css("border", "1px solid red");
  • 63. Attribute selector $(“[attribute]”) Select elements by their attributevar numberOfElements = $("[id]").length;console.log("I found "+numberOfElements+" on this page with an ID attribute");$("div[id]").css("border", "1px solid red");$("input[value=Stijn]").css("border", "1px solid red");
  • 64. Attribute selector $(“[attribute]”) Advanced attribute selectors$(input[name="abc"]) // where name equals abc$(input[name!="abc"]) // where name is not abc$(input[name^="abc"]) // where name starts with abc$(input[name$="abc"]) // where name ends with abc$(input[name*="abc"]) // where name contains the characters abc$(input[name~="abc"]) // where name contains the word abc
  • 65. Descendants $(“ancestor descendant”) Select all elements that are descendants of a given ancestor$("form input").css("border", "1px solid red");
  • 66. Children $(“parent > child”) Select all elements that are descendants of a given ancestor, but only if they are a direct child element of the ancestor$("ul.topnav > li").css("border", "1px solid red");
  • 67. Double column $(“:abc”) There are a bunch of predefined selectors$("li:odd") // select all odd li elements$("li:even") // select all even li elements$("li:first") // select the first li element$("li:last") // select the last li element$("li:eq(4)") // select the 5th li element$(":input") // select all input fields$(":button") // select all buttons$(":checkbox") // select all checkboxes$(":radio") // select all radio elements$(":checked") // select all checked checkboxes and radio buttons$(":selected") // select all selected option elements
  • 68. functionsbasic manipulation
  • 69. .html() Without a parameter it will return the html content of the first element in the selector If you provide a html or text string in the first parameter, the html content of all elements in the selector will be updatedconsole.log($(body).html());$(body).html("<h1>My pagetitle</h1>");
  • 70. .text() Without a parameter it will return the text content of the first element in the selector If you provide a text string in the first parameter, the text content of all elements in the selector will be updatedconsole.log($(body).text());$(body).text("<h1>HTML won’t work</h1>");
  • 71. .empty() Remove all text and DOM elements within the selector$(#myDiv).empty();
  • 72. .val() Get the current value of the first element from the selector The .val() method is primarily used to get the values from form elements$("input:checkbox:checked").val();
  • 73. functionsattributes and classes
  • 74. .attr(attribute, value) Without setting the value parameter, jQuery returns the value of the attribute of the first element in the selector$("img").attr("src"); If you provide a second parameter (value), you set the attribute of all selected elements to this new value$("img").attr("src", "myImage.jpg");
  • 75. .css(name, value) Without setting the value parameter, jQuery returns the specific css value of the first element in the selector$("a").css("color"); // red If you provide a second parameter (value), you set the css value to this new value$("a").css("color", "#FF3300");
  • 76. .css(map) The css function allows an object parameter too$("a").css({ "color": "#FF3300", "text-decoration": "none"});
  • 77. class functions some useful class functions$("a").addClass("active"); // adds the class "active"$("a").removeClass("active"); // removes the class "active"$("a").hasClass("active"); // returns true or false$("a").toggleClass("active", "inactive"); // toggle the class
  • 78. functionslookups
  • 79. .eq(index) Returns the element at the specified index number in the selection First item is zero (zero-based index)$("li").eq(4);
  • 80. .eq(-index) Returns the element at the specified index number in the selection counting from the back$("li").eq(-1);
  • 81. lookup functions.first() // select the first item from the selected elements.last() // select the last item from the selected elements.next() // select the next item in the DOM.nextAll() // select all the next items in the DOM.prev() // select the previous item in the DOM.prevAll() // select all the previous items in the DOM
  • 82. chaining
  • 83. chaining jQuery is powerful because it’s built on the concept of chaining $(selector).function().function().function()$("li").css("border", "1px solid red").first().addClass("first").children("div").hide();
  • 84. functionsevents
  • 85. $(document).ready(callback); the first event that everyone knows This callback event is triggered when the DOM is fully loaded$(document).ready(function() { alert("Welcome on this page!");});Notice: the document selector doesn’t need quotes because “document” is anative javascript object. Try console.log(document); to see the full object.
  • 86. .click(callback) Bind a mouse click event to the selected elements$("#myButton").click(function() { alert("Thank you for clicking my button");});
  • 87. “this” Within a callback function you can always use the “this” keyword to select the current element$("#myButton").click(function() { $(this).toggleClass("clicked");});
  • 88. .dblClick() Bind a double mouse click event to the selected elements$("#myButton").dblClick(function() { alert("Thank you for double clicking my button");});
  • 89. hover functions many different options of doing hoversvar over = function() { console.log("hovered over the div");};var out = function() { console.log("daddy left the div");};$("div").mouseover(over);$("div").mouseout(out);$("div").hover(over, out);
  • 90. functionseffects
  • 91. .fadeIn(speed, callback) Display or hide the selected elements by fading them in or out$("#myDiv").fadeIn(500);$("#anotherDiv").fadeOut(500, function() { // this function will be called after the fadeout});
  • 92. .slideDown(speed, callback) Display or hide the selected elements by sliding them up or down$("#slider").slideDown(1000, function() { $(this).slideUp(1000);});
  • 93. .delay(duration) Set a timer to delay the execution of subsequent items in the queue.$("#myDiv").slideDown(500).delay(300).fadeOut(500);
  • 94. .animate(map, duration) Animate CSS differences by mapping an object in the first parameter of the animate function.var cssProperties = { "border": "10px solid red", "background-color": "black", "font-size": "100px"};$("#myDiv").animate(cssProperties, 500);
  • 95. functionsAjax
  • 96. AjaxMake file requests without refreshing the pageJust like a call to an image but possibility to send andget data (xml, json, html, text, script, ...)Callbacks don’t run instantly, the callback is triggeredwhen the requested URL chooses to respond, in otherwords: you have to wait for the callback to continue(asynchronous)
  • 97. $.get(url, callback); If you want to get some data asynchronously The callback function gets a parameter with the responded data$.get("randomHtmlSnippet.txt", function(dataResponse) { $("#result").html(dataResponse);});
  • 98. ...loading... It’s always a good idea to warn the user that your Ajax call is running and he should wait for a moment$("#myButton").click(function() { $("#loader").show(); $.get("someRandomHtmlSnippet.txt", function(dataResponse) { $("#result").html(dataResponse); $("#loader").hide(); });});
  • 99. $.post(url, data, callback); Good if you want to send and receive data asynchronously The callback function gets a parameter with the responded datavar data = { "email": "stijn@thesedays.com", "name": "Stijn Van Minnebruggen"};$.post("sendEmail.php", data, function(dataResponse) { alert(dataResponse);});
  • 100. jQueryutilities
  • 101. .each(function(index){ ... }) The each function allows easy DOM looping Use the this keyword to call each element in the callback the callback gets an index parameter$("li").each(function(index) { $(this).html("This is list item number "+index);});
  • 102. $.browser Object that contains flags for the useragentif($.browser.msie) { alert("Really? :P");}
  • 103. $.support Rather than using $.browser it’s recommended to check for a specific support$("p").html("This frame uses the W3C box model:<span>"+jQuery.support.boxModel+"</span>"); // true
  • 104. need help?bookmark the docs
  • 105. docs.jquery.com
  • 106. thanks!Stijn Van Minnebruggentwitter.com/donotfoldwww.donotfold.behttp://labs.thesedays.comhttp://www.thesedays.com