Tomkleen.com



JQueryNotes taken from JavaScript and JQuery: The Missing Manual.Download the Day17JQ01.zip file and extract its contents.Create a new HTML5 project called Day17JQ01.JQueryJQuery () is a JavaScript library. It was written to make writing JavaScript easier and faster. Some other jQuery libraries:Dojo Toolkit: : : of jQuery:Small file sizeFriendly to web designersWell-testedFreeLarge developer communityUsing jQueryMethod 1You can put a link to an external jQuery library in your HTML file.ExampleThis links to Google's copy:<script src=""></script>The "cdn" stands for Content Distribution Network. There are other sites you can link to as well. Search for JavaScript CDN.Method 2You can download a copy of jQuery to your web site and link to it. To download:Go to . Note that this file name is case-sensitive (must be on a Linux server).Right-click on Download the compressed, production jQuery 2.1.3. (Current version as of March, 2015).Click on Save Link As…Create a folder named JS in your project and save the file there.Add the following to the end (after any CSS) of the head element of your HTML file:<script src="js/jquery-2.1.3.min.js"></script>Using jQueryAdd the following below the existing <script> tag:<script> $(document).ready(function(){ alert("Page loaded!");});</script>The (document).ready() function is a built-in jQuery function that waits until the HTML for the page has been downloaded before it executes.A lot of JavaScript will be used for adding content to a page on the fly, changing the HTML content of a page, or changing the CSS rules for a page. In general, you will (1) select an HTML element on the page, and then (2) modify the element in some way (change its content, change its style, etc.).The Document Object ModelThe elements of an HTML document are represented as a tree. This tree is the Document Object Model (DOM).SelectorsJQuery uses selectors, just as CSS does. Element SelectorsTo select every <a> element on a page:var links = $('a');To select every <h1> element on a page:var headings = $('h1');Just like CSS!ID SelectorsID selectors in jQuery use the same format as CSS selectors. If an HTML element has an ID attribute, it can be selected using the # syntax. If the HTML looks like this:<p id="stuff">Stuff </p>You can select this element using jQuery like this:var myStuff = $('#stuff');Just like CSS!Class SelectorsIf you have HTML elements that have the class attribute, you can select every element in the class. If the HTML looks like this:<a class="button" href="">Yahoo!</a><a class="button" href="">Google</a>You can select all elements that belong to the class button like this:var myButtons = $('.button');Just like CSS!Descendent Selectors: spaceThis is the same as CSS. Give the top-level selector followed by a space, followed by the lower-level selector. To select all list items in an unordered list:$('ul li')Just like CSS!Child Selectors: >This is the same as CSS. Give the top-level selector followed by a greater-than sign (>), followed by the child selector. The difference between a child and a descendent is that a child is on the next lower level in the DOM tree. A descendent is an element that is at a lower level in the DOM tree. To select all <p> tags that are children of the <body> tag:$('body > p')Just like CSS!Adjacent Sibling Selectors: +An adjacent sibling is one that immediately follows an element. To create an adjacent selector, put a plus sign between the element and its adjacent sibling. To select the adjacent sibling of a heading (<h1>) that is immediately followed by (adjacent to in the document tree) a paragraph (<p>):$('h1 + p')Just like CSS!Attribute Selectors: [ ]An attribute selector is one that selects elements based on whether the element has a particular attribute, or whether it has a particular attribute that has a particular value. To create an attribute selector, give the tag name followed by the attribute name in square brackets. To select all <img> tags that have an alt attribute:$('img[alt]')Just like CSS!Attribute Selectors with a specific valueTo find all text boxes, you would select all <input> tags that have a type attribute whose value is text:$('input[type="text"]')Just like CSS!Attribute Selectors whose value begins with a specific string: ^=If you want to find an attribute value that begins with a specific string, use "^=". To find all links that point outside of your site:$('a[href^="http://"]')The ^ indicates that jQuery is to match only those href attributes that begin with "http://".NOT like CSS! CSS uses "|=" instead of "^=".Attribute Selectors whose value contains a specific string: *=If you want to find an attribute value that has a specific string anywhere in the value, use "*=". To find all hyperlinks that point to edu sites:$('a[href*=".edu"]')NOT like CSS! CSS uses "~=" instead of "*=".jQuery FiltersJQuery also lets you select elements based on certain characteristics (rather than a specific value as above).:even and :oddThe :even and :odd selectors allow you to select the even-numbered elements or the odd-numbered elements. Remember that all lists are 0-based in JavaScript, so choosing :even will select every other element beginning with the first element (which is element number 0!). And :odd will select every other element beginning with the second element. To select the even numbered rows in every table:$('tr:even'):first and :lastThe :first and :last selectors allow you to select the first or last element in a group. For example, to select the first paragraph on a page:$('p:first')Or the last paragraph:$('p:last'):notYou can also select elements that do not match the selector. For example, to select all anchor elements that are not elements of a class named navList:$('a:not(.navList)'):hasThe :has selector selects elements that contain another selector. For example, to select all <li> tags that have an <a> element inside of them:$('li:has(a)'):containsThe :contains selector selects elements that contain specific text. For example, to select all links that have the text "Click me!":$('a:contains("Click me!")'):hiddenThe :hidden selector selects elements that are hidden. These include elements whose CSS display property is set to none, elements that have been hidden by jQuery, elements with a width or height of 0, and hidden form fields. To select all paragraphs that are hidden:$('p:hidden'):visibleThe :visible selector is the opposite of the :hidden selector. It selects all elements that are not hidden. To select all paragraphs that are visible:$ ('p:visible')jQuery Automatic Loops and Chained FunctionsTo make the JavaScript programmer's job easier, jQuery does two things: (1) automatic loops, and (2) chained functions. Automatic loopsNormally when you select more than one element on a page, JavaScript provides a list of those elements and the programmer is responsible for looping through every element in that list. JQuery performs that looping for you! For example, to hide every image in the class slideshow:$('.slideshow').hide();Chained functionsYou may want to perform several operations on a selection (list) of elements. JQuery allows you to chain those operations (functions) using the dot notation. For example, if you want to set the width and height of a <div> tag with an ID of stuff:$('#stuff').width(200).height(200);This is easier than:$('#stuff').width(200);$('#stuff').height(200);Adding Content to a Page: Changing HTMLViewing your changesThe examples below will change the DOM of your page. However, if you choose "View source" in your browser, it only shows the original HTML that was downloaded, not the modified HTML. To view the modified HTML in Chrome, press F12 to make the developer tools window open. Click on the Elements tab to see the modified HTML.The html() functionJQuery's html() function can:return the HTML of an element.set the HTML value of an element.ExampleCreate a new HTML5 project called JQ01. Add the following in the head of your document:<script?src=""></script><script>$(document).ready(function(){});</script>Add the following to the body of your HTML document:<div id="container"> <div id="stuff"> <p>Hello</p> </div></div>Now add the following jQuery command (embedded in an alert box command). Put it in the document.ready function. Be careful with parentheses! This will retrieve the HTML from your document.alert("HTML: " + $("#stuff").html());This returns <p>Hello</p>ExampleAdd the following jQuery command immediately after the alert command that you just added. This will set the HTML inside of the #stuff division.$('#stuff').html('<h1>Hello, my name is <i>Tom Kleen</i></h1>');The append() functionThe append() function adds HTML as the last child element of the selected element. ExampleAdd this below your previous jQuery statement:$('#stuff').append("<p>Goodbye!</p>");This will add the paragraph to the end of the stuff element (but still inside of the stuff element, not after it!)The prepend() functionThe prepend() function adds HTML as the first child element of the selected element.ExampleLeave the previous jQuery instruction as it is and add this:$('#stuff').prepend("<p>Hello!</p>");This will add the paragraph to the beginning of the stuff element (but still inside of the stuff element, not before it!)The remove() functionThe remove() function is used to remove an element from a web page.ExampleAdd the following to your HTML:<div id="message"> <p>This is a message.</p></div>Preview your page. The message should appear.Add the following command to your script:$('#message').remove();This will remove the message from the document.Adding Content to a Page: Changing Text The text() functionThe text() function works just like the html() function except that it doesn't accept tags. If you send it a string with tags in it, those tags will be displayed as text instead of being interpreted as HTML.Add the following to your jQuery:$('#stuff').text('<b>Hello, my name is Fred Flintstone</b>');This will replace the entire stuff element (everything between the <div> tags) with the given text. If you want to replace the content of the <h1> tags, you must specify the <h1> tag. Replace the previous command with this:$('#stuff h1').text('Hello, my name is Fred Flintstone.');The before() and after() functionThe before() and after() functions are used to put text before or after the selected element. $('#stuff').before("This stuff goes before");$('#stuff').after("This stuff goes after");Examine the code (F12, Elements tab) to see if this goes inside of the #stuff element or outside. ClassesThe addClass() functionYou can set the class for an element on the fly with the jQuery addClass() function. Add the following CSS:<style> .button{ background-color:red; }</style>Add the following HTML:<p><a href="" >Yahoo</a></p><p><a href="">Google</a></p>To add all hyperlinks to the button class, add the following:$('a').addClass('button');The hyperlinks should get a red background color.The removeClass() functionYou can remove an element from a class on the fly with the jQuery removeClass() function. Add the following below your addClass statement:alert("Waiting for buttons to go back to white background");$('a').removeClass('button');The toggleClass() functionThe toggleClass() function will remove the element from the class if it is currently in the class, and add it to the class if it is currently not in the class. Add the following: alert("Waiting to go back to red background.");$('a').toggleClass('button');alert("Waiting to go back to white background.");$('a').toggleClass('button');Reading and Changing CSS propertiesThe css() functionThe css() function lets you read an element's CSS property, set a single CSS property for an element, or set multiple CSS properties at once for an element. Add the following element to the body of your HTML document:<div id='main'> Hello, this is my web page. </div>Add the following to the style element of your HTML document:#main{ background-color:lightgreen; }To determine the value of an element's CSS property:var bgColor = $('#main').css('background-color');alert (bgColor);This will return the background color of the element whose ID is main. Colors in jQuery are always returned as a string representing the rgb value or the rgba value of the color. Like this: rgb(144, 238, 144)To set the value of an element's CSS propertyYou can set the value of an element's CSS property by providing (1) the property name as a string, followed by a comma, and followed by (2) the property value as a string. Example:Add the following below the alert statement you entered previously:$('#main').css('background-color', 'lightblue');var bgColor = $('#main').css('background-color');alert(bgColor);You can also set multiple values for a property, just as in CSS. Add the following:$('#main').css('border', '2px solid #FF0000');And later, you can change part of the border. Add the following: $('#main').css('border-top', '5px solid blue');To set multiple CSS values at onceTo set multiple CSS properties at once, list each property as a string, followed by a colon, followed by the property value as a string, followed by a comma (if there are more properties to be set). Enclose all of these within a single pair of curly brackets. Example:$('#main').css({'background-color':'lightgreen', 'color':'green'});Note that except for making every argument a string and enclosing all of the arguments in parentheses (which makes sense because they are the arguments to a function), the syntax is exactly the same as it is in CSS. Also note that we have a series of property/value pairs all enclosed in curly brackets. This is a JavaScript object.For readability, you may want to put the pairs on separate lines, just as you do with your CSS style rules:$('#main').css({ 'background-color' : 'lightgreen', 'color' : 'green'});The text between curly brackets is called an object literal. An object literal always consists of property/value pairs with a colon between the property name and the property value, commas separating the pairs, and curly brackets surrounding the whole thing. The property name and property value are always strings. The attr() functionWhereas the css() function retrieves CSS property values, the attr() function retrieves the value of a specific attribute of an HTML element. It can be used in two ways:To retrieve the value of an attribute.To set the value of an attribute.Use these two pics for the next example. Copy them to your images folder. Name them Woz.png and Gates.png. Add the following to the top of your HTML file.<img id="nerd" src="images/gates.png">To get the name of the file, add the following to your jQuery:alert($('#nerd').attr('src'));You can also use the attr() function to set the value of a specific attribute of an HTML element. Just provide two arguments: the first argument is the attribute name (as a string) and the second argument is the attribute value. To change a picture, add the following:$('#nerd').attr('src', 'images/Woz.png');The fadeout() functionThe fadeOut() function causes the selected element to slowly fade away. Without any arguments, the fadeOut function fades away to nothing very quickly. You can control the length of time it takes by passing in a duration argument that gives the number of milliseconds that the fadeout should last. To make the picture of The Woz fade out:$('#nerd').fadeOut(5000);The argument is the number of milliseconds that the fadeout should last. The each() functionIf you want to select a list of objects in your DOM and execute the same instructions on each, you can use the each() function. The each function must be passed the function that you want to execute on each element that has been selected.Syntax:$('selector').each(function(){ // function code} // end of anonymous function) // end of each function; // end of jQuery statementThis unnamed function is called the anonymous function. It doesn't need a name because it will never be called from anywhere else.To access the current element in your function, the name of the current element is $(this).Example: Automatic pull quotesCreate a new HTML5 file called JQ02PullQuotes.html and add it to your project. Copy the text from the PullQuotes.zip file into your index page (1 HTML file, 1 CSS file). Note that there are two <span> tags with the class "pq". View the page.Change the class from "pq" to "pullquote" and view the page again. We have pull quotes, but they are no longer in the document body! We need a way to copy the text and create a separate pull quote. Change the class back to "pq" for both pull quotes.Add in a link to a jQuery library:<script?src=""></script>Add a pair of blank script tags:<script></script>Add the jQuery ready function:$(document).ready(function(){});In the jQuery ready function, add:$("span.pq")Add the each function right after it:$("span.pq").each(function(){});Now add to the body of the each function:var quote=$(this).clone();quote.removeClass("pq");quote.addClass("pullquote");$(this).before(quote);The clone() method create a copy of the element. Then we change its class from "pq" to "pullQuote".Then we put the quote before the current text. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download