Lesson 13

The Power of Libraries

Using jQuery and CSS to change image

Our next task is to add a CSS image background instruction to our canvas elements from JavaScript. This is complex stuff, but luckily for us we can use an open source JavaScript library to help.

For more information see *jQuery.

1. Connect jQuery Library

To include jQuery we are going to use a CDN, or 'Content Delivery Network'. Insert the code above in your index.html, above where you link to script.js. This will give us the power to use all the functions within the jQuery library.

What is a 'content delivery network'?

A content delivery network is a network of servers all over the world that host files for developers to use. In this instance we’re using a CDN to hold our jQuery file. As lots of developers probably want to use jQuery it makes sense for us to all link to the same file.

2. ID canvas elements

We're adding these unique identifier attributes, or IDs, to each canvas element in our HTML so we can apply different image backgrounds.

What is an ID attribute?

An ID is a way of targeting one specific element on a web page. For more information see *IDs.

3. Change canvas background image from script.js

Now we have added unique IDs to our canvas elements we can use the code above in script.js to change their backgrounds from our JavaScript file (pretty cool huh!).

We are using a jQuery function here called '.css' which adds css to an element.

The '$' is shorthand for jQuery - to save developers from typing 'jQuery' each time they can use a $ instead.

Have a look at the preview and you should see you images displaying. When you press refresh the images should change randomly!

How does jQuery work?

jQuery is a ‘code library’ written by lots of developers all over the world. By creating a list of the most commonly used functions - things like showing and hiding things on a page - jQuery can be included on your page to make programming in JavaScript a lot faster.


jQuery is a JavaScript library that makes using JavaScript quicker and easier to use.

jQuery provides lots of easy-to-use functions which help you quickly manipulate and add interactivity to your HTML page. jQuery UI is a library that contains many reusable components such as date pickers, progress bars, tooltips and lots more.


The "id" attribute can be added to any element to uniquely identify that element. This allows JavaScript or CSS to be used to manipulate the style, behaviour and content of the element.

The HTML specification states that the ID of an element should be unique. This means that one element should not have the same ID as another. In practice, in most cases you'll probably get away with using duplicate IDs.

Go to the next lesson



the web page

New Window
Next Lesson