Exercise 6
Getting Started with JavaScript and jQuery
Create an HTML page that loads the jQuery library and a .js
file you will create. Add the provided HTML for the <body>
of the page.
Create the .js
file that your HTML refers to. Add this code from the Guide to get started and make sure things are working:
say_hello = function() {
alert('Hello world!')
}
setup = function() {
jQuery('p').click(say_hello)
}
jQuery(document).ready(setup)
If you load the page and click on any paragraph, you should get an alert box. Make sure that's working before moving on.
Also create a little stylesheet for the page, so we can make some appearance changes with out JavaScript:
.highlighted {
color: red;
}
Changing the Behaviour
The behaviour from the example isn't what we really want here. Modify the JavaScript so that:
- The
alert
does not happen when you click paragraphs (but you may want to re-use the code for…). - When you click on the
<h1>
element, there is an alert “I'm a heading”. - When the mouse moves over the paragraph with
id="hoverable"
(amouseenter
event), all paragraphs should get the class “highlighted” (so it turns red with the above stylesheet). This is done by settings theclass
attribute like:.attr('class', 'highlighted')
. - When the mouse leaves the
id="hoverable"
paragraph (amouseleave
event), the class should be removed. This can be done by setting theclass
attribute to''
(the empty string). - When the
<button>
is clicked, the first list item (that's still on the page) should disappear. This can be done with the.first
function (to get the first element in a jQuery object) and.remove
function to remove it from the page. Here's a big hint:jQuery('li').first().remove()
.
Video: demo of the required functionality.
In order to do this, you should have one setup
function that configures four event handlers: click on the <h1>
, mouseenter and mouseleave on the hoverable
paragraph, and click on the button. Each should connect a function that takes the required action.
Submitting
Upload the files to the course web server, as you have before. You may want to continue organizing your files as before and create a folder exercise6
.
Submit the URL of your HTML page to the CourSys activity Exercise 6.