Comm 328 Responsive Web Design

jQuery Basics

In this class, we'll focus primarily on using the jQuery library instead of vanilla JavaScript. We're doing this because you can usually accomplish some nice effects using jQuery with very little code. It also uses CSS-style selectors, which you already know.

It's important to keep in mind that you do not need to use jQuery to do any of these things. They can all be accomplished with regular old JavaScript.

Including the jQuery Library

In order to use jQuery, you must link to it first. The recommended method of doing this is to a link to a copy of jQuery that is hosted on a Content Delivery Network (CDN). CDN's are great because they will always have a much more sophisticated hosting environment than you. More importantly, when lot's of people use a CDN, the browsers can take advantage of caching and ideally the files will not have to be downloaded again each time they're used on a different site.

Google Hosted Libraries

Google offers free hosting of the most popular JavaScript libraries and is very easy to use.

We can include a Google hosted version of jQuery by using the following HTML in our page:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

This link includes the jQuery library on our page. Keep in mind, that this link is version specific. The URL we used above included version 2.2.0 of jQuery.

JavaScript Order

Any plugins or other code that relies on jQuery will have to be added after jQuery itself. In practice this means that jQuery is usually going to be the first JavaScript file you load.

In the examples below, we'll write our JavaScript in a file called intro.js. This file will be saved in a folder called js.

The links to both our jQuery and our own JavaScript go either inside the head element or just before the closing HTML body tag. Put the JavaScript links at the end of the document unless there is a requirement otherwise.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script src="js/intro.js" type="text/javascript" charset="utf-8"></script>

  </body>
</html>

Basics

With jQuery, we can easily access parts of our HTML document using a CSS-like syntax. When we're accessing our HTML through JavaScript, we interacting with what's known as the Document Object Model. It's commonly referred to as the DOM.

In order for us interact with or modify the DOM, we first have to wait for it to load in the page. We do this with the document.ready() block.

$( document ).ready(function() {
   
  // Your JavaScript goes here...
	
});

The document.ready() will run when all of the pieces of our DOM have loaded, but not necessarily the entire page. Things like large images may not have loaded yet.

If you're looking at tutorials online, you'll often see the following syntax:

$(function() {
  // Your JavaScript goes here...
});

This is simply a shortcut for the document.ready() block.

jQuery Objects

The jQuery library creates a syntax that allows us to easily access the DOM. jQuery objects: start with the dollar sign include parenthesis with a quoted string inside the string is an html element or CSS selector Here's a simple example where we find all the h1s in the document and save them to a variable. We then print that variable to the console.
var heading = $( "h1" );

console.log(heading);

You should see the result printed in the console.

A screen shot of the console

Notice the square brackets around the printed result. Also note that there is a lot of information that got printed. The heading variable is actually holding a jQuery object that contains a complete reference to all of the information about the h1 in our document.

There's only one h1 in our document. What if tried to get multiple elements? Say, all the paragraphs in the document.

var paragraphs = $( "p" );

console.log(paragraphs);

Now the jQuery object will contain a reference to each paragraph in the document.

You can check the length of the object. This tells you how many items are in the object. There are three paragraphs in our document, so our length should be three.

console.log(paragraphs.length);

Manipulating CSS Properties

You can use the css() method to either get or set a CSS property value. Let's change the color of our heading object.

Get a CSS Property Value

To get a css value, use just the CSS property name. It should be in quotes.

var h1_color = $( "h1" ).css('color');
console.log( h1_color );

You could also just type $( "h1" ).css('color'); directly into the console.

Set a CSS Property Value

If you want to set a CSS value, the css method takes two arguments. The first is the CSS property and the second is the CSS value. Both should be in quotes.

$( "h1" ).css('color', 'red');

Try using the css method to print the value of the color property to the console again to see if it changed.

Using CSS Selectors

You can use any CSS selector you want to create your jQuery object.

Here we're using the adjacent sibling selector that gets any p immediately following an h2. Then we'll set the border to something.

$( "h2 + p").css('border', '6px dotted green');

You can also use class and id selectors.

$( ".boxes .one").css('background', 'darkslategray');

Below we're using the css method to set multiple properties on the element with an id of example. Notice the syntax changes slightly to using curly braces and commas. This is what's known as object literal notation in JavaScript.

$( " #example ").css({
	'padding': '25px',
	'background': '#eee',
	'border': '1px solid black'
});

You can read more about object literal notation on Dynamic Web Coding.

Manipulating Classes

Why it's easy to add and remove css directly in jQuery, a better approach is usually to modify the actual classes on an element. This approach keeps our presentation (css) and behavior (js) more separated.

Let's say we wanted to highlight each paragraph that contained a certain word. We'll use the jQuery :contains selector for this. To find all of the paragraphs that contained the word "Simmons" in them we could do this:

$( "p:contains('Simmons')" );

Lets say we want to bold the text of each of the paragraphs in this collection. We could use the css method.

$( "p:contains('Simmons')" ).css("font-weight", "bold");

However, what if we changed our minds about the effect we wanted? We'd have to remember later that the style was applied via JavaScript and go find it again. The css method also applies styles inline in our document which gives these styles a high level of importance in our document. They'll override most other styles, which is not always what we want.

It's much cleaner to use the associated class methods.

We could simply add a class of 'highlight' to the paragraph using the addClass() method.

$( "p:contains('Simmons')" ).addClass("highlight");

In our CSS style sheet, we would have a corresponding declaration for highlight.

.highlight {
  background: rgba(0,255,0,.2);
}

If we wanted to remove the class, we could use removeClass().

$( "p:contains('Simmons')" ).removeClass("highlight");

Calling removeClass() without any arguments removes all classes on the element.

$( "p:contains('Simmons')" ).removeClass();

Exercise 1

  1. Use what you've learned to change one CSS property for each of the three boxes.

Exercise 2

  1. Each of the boxes has a class of "box" with styles that make it display like a box. Create a new CSS rule using a class called "circle" as the selector. Set the styles to make the element show as a circle instead of a box.
  2. Use the jQuery class methods to remove the box class from each of the divs.
  3. Use the jQuery class methods to add the circle class to each of the divs.
  4. When you're done, you should have three circles instead of squares.