Presentation is loading. Please wait.

Presentation is loading. Please wait.

JQuery 10/21. Today jQuery Some cool tools around the web JavaScript Libraries Drawing libraries HTML Frameworks Conventions.

Similar presentations


Presentation on theme: "JQuery 10/21. Today jQuery Some cool tools around the web JavaScript Libraries Drawing libraries HTML Frameworks Conventions."— Presentation transcript:

1 jQuery 10/21

2 Today jQuery Some cool tools around the web JavaScript Libraries Drawing libraries HTML Frameworks Conventions

3 JavaScript in the Real World You need to make sure your code works on all browsers. Some very popular browsers don’t implement basic things according to a standard. Therefore, you often need to have special cases for basic things like event handling.

4 Why People Use Libraries… People use JavaScript libraries to avoid needing to take care of all these special cases themselves. Libraries handle different browser cases so you don’t have to.

5 jQuery One of the most popular JavaScript libraries. If you don’t use it, you will at least need to deal with it. What it does. Allows you to easily select HTML elements Allows you to manipulate these elements, define event handlers, do animation, and do AJAX calls more easily

6 Getting jQuery Download the JavaScript library from http://jquery.com http://jquery.com Can also use hosted locations like Google Library API http://code.google.com/apis/libraries/ Also links you to some of the most popular JavaScript libraries.

7 Things jQuery can do 1.Make it easy to run a function when your page loads. 2.Select a bunch of DOM elements and do something with them 3.Handle events 4.Do AJAX calls easily

8 1. Run something when the page loads There are 4 overloads total, I will only discuss 2 today. jQuery(function (){…}): function passed in gets executed when the DOM loads. Equivalent to calling document.ready(); which is when all the DOM elements have loaded (but not necessarily all images). similar to window.onload = function() {…} except window.onload waits for images to load too.

9 Loading example… $(document).ready(function() { alert("hello world"); });OR$(function(){ alert("hello, world!"); });OR function helloWorld() { alert("hello world"); }$(helloWorld); Pop up an alert saying “hello, world!” once the document loads.

10 2. Select a bunch of DOM elements and do something with them jQuery has a focus on queries: You do a query to get a list of objects back (jQuery objects). You can then do interesting things with these objects. jQuery defines one global function: jQuery() So commonly used that jQuery defines a global symbol, $ for it.

11 jQuery Basics jQuery() function (or, $() ) is ‘overloaded’ Remember when I said JavaScript doesn’t support overloading? Well, you can write overloading yourself by checking your parameters. Most basic parameter to $() : string representing a “css selector” A “CSS Selector” is a string (query) which selects some subset of elements in your DOM. For example, $("div") gets all divs, $(".className") gets all elements whose class is className.

12 jQuery example For loop that turns all h1 elements red var h1s = $("h1"); for (var i = 0; i < h1s.length; i++) { h1s[i].style.color="red"; h1s[i].style.color="red";}

13 css() css() allows you to either get the css properties of an element or set the css properties of an element. Method is overloaded by checking for existence of variables. Setting the text color of element with myId to red: $("#myId").css({color: "red"}); If multiple elements returned, executes on all elements found. Returns list of modified elements (chainable!)

14 Getting the text color of element with id “myId”: $(“#myId”).css(“color”); If multiple elements returned, executes on first element found. Does not return a list (terminates your chain). Setting the text color of element with id “myId” red: $(“#myId”).css({color: “red”}); css()

15 More Useful CSS Functions Add a CSS class to an element: $("#myId").addClass("myClassName"); Toggle a CSS class: If element has the class, remove it. If it doesn’t have the class, add it. $("#myId").toggleClass("highlight"); More at http://api.jquery.com/category/css/ http://api.jquery.com/category/css/

16 Getting/Setting HTML Content text() gets/sets the inner text of an element and its children. html() gets/sets the inner HTML of an element and its children. Example: Get the text of the first h1 element: $(“h1”).text(); Example: Set the text of each h1 element to be “foobar” $(“h1”).text(“foobar”); Example: Add section numbers to each header element $(“h1”).text(function(n, current){ return “section “ + (n+1) + “: “ + current });

17 Getting/Setting Element Position offset() gets/sets the position of an element relative to the entire document. position() gets/sets the position of an element relative to its parent. Example: scroll all elements with class “scrolling” left to right: function scrollText(){ $(".scrolling").offset(function(index, curpos){ return { left: (curpos.left + 5) % $(window).width(), top: (curpos.top) }; }); setTimeout(scrollText, 30); }

18 data() Allows you to associate data with any jQuery object (i.e. object that’s a result of a query). Example: set some data for all div elements: $("div").data("x",5); Example: query data: $("div").data("x") : get “x” property $("div").data() : return object with all properties.

19 Manipulating Document Structure Methods that add/remove elements to your HTML document. You can either pass in Element objects or HTML strings. $("#myId").append(document.createElement("h r")); Adds an element at end of element with id myId $("#myId").after(" ") Inserts an element directly after element with id myId.

20 Method Chaining Example Most jQuery methods operate on a list of objects, then return the modified list. This allows you to chain methods, i.e. do multiple things on one line Example: Set text color of all h1 elements to green and add an hr element before and after these elements:

21 Method Chaining Example Most jQuery methods operate on a list of objects, then return the modified list. This allows you to chain methods, i.e. do multiple things on one line Example: Set text color of all h1 elements to green and add an hr element before and after these elements: $(“h1”).css({color: “green”}).before(“ ”).after(“ ”);

22 Method chaining explained $(“h1”).css({color: “green”}).before(“ ”).after(“ ”);

23 Method chaining explained $(“h1”). css({color: “green”}).before(“ ”).after(“ ”);

24 Method chaining explained $(“h1”). css({color: “green”}). before(“ ”).after(“ ”);

25 Method chaining explained $(“h1”).css({color: “green”}). before(“ ”). after(“ ”);

26 Method chaining explained $(“h1”).css({color: “green”}).before(“ ”). after(“ ”); end result

27 3. Event Handlers in jQuery Event handling is especially annoying because IE implements a different event API than other browsers. Instead of addEventListener, uses attachEvent Makes it a big pain to do event handling cross-browser. jQuery makes it much easier for us to do event handling.

28 Event Registration in JQuery Example: clicking on element toggles its background color. Define class “highlighted” to have a grey background color. $("p").on("click", function(){ $(this).toggleClass("highlighted");})

29 Event Registration Details jQuery does pass in parameters to the event handler First argument is the event object, contains info about the event. Stuff like target, clientX, etc. For more information: http://api.jquery.com/category/events/event-object/ http://api.jquery.com/category/events/event-object/ Return value of your event handler is important: If it returns false the default action of event and any future propagation are canceled

30 Types of events handlers scroll()click()change()dblclick()focus()hover()keypress()load() Many more at http://api.jquery.com/category/events/ http://api.jquery.com/category/events/

31 Event Handler example Useful debugging blurb that shows you the position of your mouse relative to the window.

32 Animations in jQuery jQuery has pretty powerful animation framework which allows you to smoothly change css properties of DOM elements. Animations add polish to your site. Examples of animations: http://api.jquery.com/fadeIn/

33 Animation Basics Every function has a duration that says how long the effect should last for. Specify in ms or a string. “fast”, “slow”. Animations are asynchronous. Can specify a second parameter to your animation: the function to execute when your animation is complete.

34 Basic Visual Effects fadeIn(speed, callback): $("div").fadeIn(); fades in all divs. $("div").fadeIn("fast"); fades in all divs fast. fadeOut(speed, callback) fadeTo({fade options such as opacity to fade to}, speed, callback);

35 Basic Visual Effects hide(): Animates width and height to 0 show(): Animates width and height from 0 Toggle() Toggles between show and hide.

36 Queueing Animations You can execute one animation after another by doing: $("#myElement").fadeIn().fadeOut();

37 Custom Animations Use animate() to specify custom animation of css styles. $("img").animate({height: 0}, {duration: "fast", complete: function(){…})) quickly animates all images to have a height of 0 and executes a specified function on completion. The first parameter specifies what properties you should animate to. The second parameter (function object) is optional.

38 Stopping and Delaying Animations Some people find animations jarring. jQuery.fx.off = true disables all jQuery animations. To stop a current element from animating, you can use stop(). This stops the current element from animating. You can also use delay(ms) to delay animations

39 Example Fading images on mouseover $("img").mouseover(function(){ $(this).stop().fadeTo(300, 1.0); };$("img").mouseout(function(){ $(this).stop().fadeTo(300, 0.5); } Example taken from JavaScript: the definitive guide by David Flanagan

40 Example Fading images on mouseover $("img").mouseover(function(){ $(this).stop().fadeTo(300, 1.0); };$("img").mouseout(function(){ $(this).stop().fadeTo(300, 0.5); } Example taken from JavaScript: the definitive guide by David Flanagan

41 4. AJAX calls getting or saving data from servers somewhere not getting into it in this class but check out $.ajax, $.get, $.post if you're interested.

42 Shout out to other useful JavaScript Libraries UnderscoreJSjQueryPrototypeJSMooTools

43 UI Frameworks jQuery UI jQuery Mobile BootstrapYUI

44 MVC Framework Tools AngularJSBackbone

45 Drawing Libraries RaphaëlProcessingJSPaperJS

46 Web Effects http://acko.net/blog/this-is-your-brain-on-css/ http://www.nike.com/jumpman23/aj2012/ http://www.inception-explained.com/


Download ppt "JQuery 10/21. Today jQuery Some cool tools around the web JavaScript Libraries Drawing libraries HTML Frameworks Conventions."

Similar presentations


Ads by Google