JQuery, Day #2

Adding Content to a Page: Changing HTML

Viewing your changes

The 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() function

JQuery's html() function can:

1. return the HTML of an element.

2. set the HTML value of an element.

Example

Create a new HTML5 project called Page18JQ01. Add the following in the head of your document:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"> </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). Be careful with parentheses! This will retrieve the HTML from your document.

alert("HTML: " + $("#stuff").html());

This returns <p>Hello</p>

Example

Add 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() function

The append() function adds HTML as the last child element of the selected element.

Example

Add this below your previous jQuery statement:

$('#stuff').append("<p>Goodbye!</p>");

This will add the paragraph to the end of the stuff element.

The prepend() function

The prepend() function adds HTML as the first child element of the selected element.

Example

Leave the previous jQuery instruction as it is and add this:

$('#stuff').prepend("<p>Hello!</p>");

The remove() function

The remove() function is used to remove an element from a web page.

Example

Add 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() function

The 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() function

The 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.


Classes

The addClass() function

You 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="http://www.yahoo.com" >Yahoo</a></p>

<p><a href="http://www.google.com">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() function

You 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() function

The 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 properties

The css() function

The css() function lets you

1. read an element's CSS property,

2. set a single CSS property for an element, or

3. 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(255, 0, 0)

To set the value of an element's CSS property

You 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 once

To 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() function

Whereas 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:

1. To retrieve the value of an attribute.

2. 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. Note: The picture of Bill Gates doesn't appear right away. Any ideas why?

<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() function

The 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() function

If 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 statement

This 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 quotes

Create a new HTML5 project called Page18JQ02PullQuotes.html. Copy the text from the PullQuotesOriginal.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="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></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.


Day18-JQuery02.docx 6 4/1/2013