Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to jQuery

Similar presentations


Presentation on theme: "Introduction to jQuery"— Presentation transcript:

1 Introduction to jQuery

2 Document Object Model

3 Document object model (DOM)
To get the most out of jQuery, we should review how an HTML page is put together An HTML document is structured according to the Document Object Model, or DOM. By interacting with the DOM, jQuery is able to access and modify HTML.

4 Document object model (DOM)
The Document Object Model (DOM) is standardized and is specific to current HTML document The DOM consists of every element on the page laid out in a hierarchical way that reflects the way the HTML document is ordered elements in the DOM can have parents, children, and siblings

5 DOM and HTML DOM sees an HTML (or XML) document as a tree or as a group of trees. The document's root element is the <html> element (the primary source) Can see the node structure with a browser, by inspection

6 The DOM tree The DOM hierarchy depends on a document's contents

7 “This is a picture of my pet”
What do we mean by DOM? HTML HEAD TITLE “My Pets” DIV P “This is a picture of my pet” IMG BODY UL LI Dog Cat Fish

8 jQuery element selection

9 jQuery implementations
jQuery, at its core, is a Javascript library designed for DOM manipulation The DOM is a tree structure representation of all the elements of a web-page, and jQuery makes finding, selecting, and manipulating these DOM elements simple and convenient jQuery Mobile is a version of the core, that is a touch-optimized HTML5 UI framework. It is designed to make responsive web sites and apps that are accessible on all smartphone, tablet and desktop devices jQuery UI is a version of the core, that is a widget and interaction library built on top of the jQuery JavaScript Library - used to build highly interactive web applications (drag, drop, datepicker, slider, tabs, etc.) jqueryui.com.

10 Introduction to jQuery
jQuery is a commonly used library Enables developers to implement common JavaScript tasks with minimal code jQuery is a popular Javascript framework specialized for changing web page documents on the fly create impressive animations and interactions simple to understand and easy to use cross-browser compatibility

11 What is jQuery? jQuery is a script file
Lets you find elements using CSS-style selectors Lets you do something to the elements using jQuery methods jQuery object has many methods to work with the elements you select

12 Implementing jQuery Cross-browser library
jQuery 1.x supports IE 6, 7, and 8 jQuery 2.x supports only IE 9 and later Requires less extra code, so smaller file

13 Including the Library Link .js file containing the jQuery library to HTML document Download at Refer to it in your page <script src=scripts/jquery min.js></script> -OR- Refer to one of the online versions (public location on CDN) <script src=" </script>

14 Starting a jQuery Statement with $
All jQuery code conforms to JavaScript rules Uses shortcuts that can look like different language Every jQuery statement begins with $ Specifies that any code that follows should be interpreted using jQuery library

15 Selecting Elements with jQuery
$ is followed by a reference to the elements on which statement operates Reference is contained in parentheses Can think of the structure as selector.action state the selector, then using dot notation, attach the action to perform on the selector

16 jQuery selectors

17 Selecting Elements with jQuery
Use CSS selectors in quotes to select elements (specific HTML tags on a web page) Example–to operate on h1 elements: $("h1") Example—to select elements in odd class: $(".odd") Concise version of querySelectorAll() method: document.querySelectorAll(".odd")

18 Dual Functionality 1 $(".odd").width();
Many jQuery methods serve dual function Look up a value Set that value 1 $(".odd").width(); 2 /* returns the computed width value for the first 3 element with the class name "odd" */ 4 $(".odd").width("5em"); 5 /* sets the width of all elements with the class name 6 "odd" to 5em */

19 Lets see some examples

20 How jQuery compares to CSS
CSS selectors TAGS H1 { text-align: left;} CLASSES .my_class { position:absolute;} ID’s #my_id { color:#0033ff; } jQuery selectors TAGS $(“h1”) CLASSES $(“.my_class”) ID’s $(“#my_id”)

21 jQuery using the #id selector

22 jQuery using the .class selector

23 jQuery Actions

24 $(document).ready(); $() references jQuery
Putting document between the parentheses references the HTML document itself. .ready(); is a function, or basic action, in jQuery It indicates the following code will run once the browser has fully loaded the HTML document Whatever goes inside .ready()'s parentheses is the jQuery event that occurs as soon as the HTML document is ready Note that .ready(); ends with a semicolon

25 jQuery functions Functions are the basic unit of doing work in jQuery
A function is made up of three parts the function keyword any inputs that function takes (they go between the ()s and are separated by commas if there are more than one) whatever actions the function should perform (these go between the {}s).

26 jQuery functions A traditional function looks like this: function() {
statements…; } A jQuery function looks like this: $(document).ready(function() { statements; }); In jQuery you can give a function just about anything as an input—even another function!

27 jQuery actions $('div').slideDown('slow'); });
Between the { };s of the function(), is where the html is turned into a jQuery object so jQuery can manipulate it $(document).ready(function() { $('div').slideDown('slow'); });

28 Try it In script.js, put document into a jQuery object and call .ready() include a function keyword and two new actions together on the div tag, mouseenter() and fadeTo() mouseenter() produces a change when your mouse enters a given HTML element fadeTo() takes 2 inputs between its parentheses, separated by a comma: the speed at which to fade the opacity (or transparency) to fade to ex. fadeTo('fast', 0.25);

29 Solution $(document).ready(function() { $('div').mouseenter(function(){ $('div').fadeTo('fast',1); }); $('div').mouseleave(function(){ $('div').fadeTo('fast',0.5); or

30 javascript HTML element(TAG) selection

31 Accessing Elements using Document Object methods
Several methods of the Document object available for JavaScript to reference web page elements getElementById() getElementsByTagName() getElementsByClassName() getElementsByName()

32 Accessing Elements by id value
Set the id value in HTML getElementById() method Returns the first element in a document with a matching id attribute Example: HTML element with id value <input type="number" id="zip" /> JavaScript to reference HTML element var zipField = document.getElementById("zip");

33 Accessing Elements by Tag Name
getElementsByTagName() method Returns array of elements matching a specified tag name Tag name is name of element Method returns a set of elements The elements returned is actually and array and can be indexed like any array Example: Index numbers start at 0, so second element uses index number 1 To work with the second h1 element on a page: var secondH1 = document.getElementsByTagName("h1")[1];

34 Accessing Elements by Class Name
getElementsByClassName() method Returns an HTML array of elements with a class attribute matching a specified value Example All elements with class value side: var sideElements = document.getElementsByClassName("side");

35 Accessing Elements by Name
getElementsByName() method Returns an HTML array of elements with a name attribute matching a specified value Not as useful as preceding options But creates more concise code when accessing set of option buttons or check boxes in a form: var colorButtons = document.getElementsByName("color");

36 Accessing an Element's Content
textContent property Accesses and changes text that an element contains Unlike innerHTML, textContent strips out HTML tags function getText() {     var x = document.getElementById("myList").textContent;     document.getElementById("demo").innerHTML = x; } function getHTML() {     var x = document.getElementById("myList").innerHTML;     document.getElementById("demo").innerHTML = x; }

37 Accessing an Element's CSS Properties
Can access CSS properties through DOM Use dot notation to reference element's style property followed by the name of CSS property Example: change value of CSS display property to none for element with id value logo: document.getElementById("logo").style.display = "none";

38 Accessing an Element's CSS Properties (cont'd.)
When CSS property includes hyphen (-), remove hyphen and capitalize letter following hyphen font-family becomes fontFamily To remove a style you previously added with a DOM reference set its value to an empty string var font = document.getElementById("logo").style.fontFamily; document.getElementById("navbar").style.color = "";

39 Accessing Element Attributes
Access element attribute using dot notation and the name of the attribute after the element reference Reference element with id value homeLink: Reference href attribute of same element: document.getElementById("homeLink") document.getElementById("homeLink").href

40 jquery HTML element(TAG) selection

41 Selecting HTML Elements
By element name - ex. $('div') By CSS class selector If we have class="red" in our HTML, we can target it in CSS with .red In jQuery, all we need to do is put '.red' in quotes, and we can pass it to $() to make a jQuery object Ex. $(.red) By CSS ID selector If we have ID="red" in our HTML, we can target it in CSS with #red In jQuery, all we need to do is put ‘#red' in quotes, and we can pass it to $() to make a jQuery object Ex. $(#red)

42 Changing styles Can fine-tune individual CSS property values, specifically $("div").height("100px"); $("div").width("50px"); Or use a general-purpose .css() function that takes two inputs: the first is the CSS element to alter, and the second is the value to set it to $("div").css("background-color","#008800");

43 Flexible actions Anything you can target with CSS, you can modify with jQuery Using compound operators, can target more that one element $('p').fadeTo('slow', 0); $('li').fadeTo('slow', 0); $('p, li').fadeTo('slow', 0);

44 this keyword the this keyword refers to the jQuery object you're currently doing something with The action will only affect the element you're currently doing something with (for example, clicking on or mousing over). $(document).ready(function() { $('div').click(function() { $(this).fadeOut('slow'); });

45 variables store information for use at a later time
can hold any type of information The = sign is used to assign values var lucky = 7; var name = "Codecademy"; //javascript variable var $p = $('p'); //jQuery variable Example: $(document).ready(function() { var $target = $(‘div'); $target.fadeOut('fast'); });

46 DOM: Inserting Elements
.append inserts the specified element as the last child of the target element .prepend() inserts the specified element as the first child of the target element $(".info").append("<p>Stuff!</p>"); $(".info").prepend("<p>Stuff!</p>"); .appendTo() does the same as .append() the order of "what to add" and "where to add it“ is reversed $('<p>Stuff!</p>').appendTo('.info');

47 DOM: Before and After can specify where in the DOM to insert an element Syntax: $('target').after ('<tag>To add</tag>'); 'target' is the element after which you want to add something and the content between <tag> and </tag> is the HTML element you want to add $(document).ready(function(){ $('#one').after('<p>I am a paragraph</p>'); });

48 DOM: Removing Elements
.empty() and .remove(), delete content from our pages .empty() deletes an element's content and all its descendants .remove(), not only deletes an element's content, but deletes the element itself $(document).ready(function(){ $('#one').after('<p id=“two”>I am a paragraph</p>'); var $para = $('p'); $('#one').after($para); $('#two').after($para); $('p').remove(); });

49 DOM: Adding and Removing Classes
Functions .addClass() and .removeClass(), can be used to add or remove a class from an element Syntax: $('selector').addClass('className'); $('selector').removeClass('className'); 'selector' is the HTML element you want 'className' is the class name you want to add or remove NOTE: You aren't selecting anything, you are modifying your element. This means that you do not need # or . before your class. EX: $(document).ready(function(){ $('#text').click(function(){ $(this).addClass('highlighted'); });

50 DOM: Toggling Classes toggleClass() function can change a class back to its original state If the element it's called on has the class it receives as an input, .toggleClass()removes that class if the target element doesn't have that class, .toggleClass() adds it $(document).ready(function(){ $('#text').click(function(){ $(this).toggleClass('highlighted'); });

51 Modifying Content can update the contents of our HTML elements
Put content between the opening and closing tags .html() function get the HTML contents of the first element it finds, and will set the contents of that element Ex: $('div').html("I love jQuery!"); .val() function gets the value of form elements Ex: $('input:checkbox:checked').val(); gets the value of the first checked checkbox


Download ppt "Introduction to jQuery"

Similar presentations


Ads by Google