Topic 5: Further jQuery
This is a relatively advanced topic. You should complete the
basic exercises from Topics 1, 3 and 4 before attempting these.
Exercises
- Write a simple drag and drop demo with two <div>s. The
second div should disappear when dragged into the first.
- Change the code so that the div being dragged changes colour
when dragged, and the div acting as the receiver for being dropped
changes colour when the other is dropped in.
Note that if you use the .ui-draggable-dragging class to change the colour
of your div while being dragged,
you should not give the div an initial background-color in your CSS. This
is because of CSS precedence rules: ID styles take precedence over class
styles as IDs are more specific. Instead, give your div a border so you can
see it, or implement it via the start and stop methods
which run when a draggable starts and stops being dragged.
Advanced - for students comfortable with programming ONLY!
- Imagine you are writing a social network in which the user can
customise their profile by moving sections around the page. Write this,
using jQuery to manage the dragging and also to manage saving the div
positions to the server with AJAX. You will need to write a server-side
script to receive the new positions and save them to the database, which
also means that you will need to set up a database table
containing a record of divs and their positions.
- Write PHP code to recreate the saved positioning of the social
network. There are a number of ways you can do this:
- Dynamically re-create the stylesheet from PHP by querying the
database;
- Position the div using jQuery: when the page loads, send an
AJAX request to a server-side script to obtain the saved position of
the div, and then set the appropriate properties (the
top and left CSS properties)
- Extend your code to allow the div to be resized, and save the new size
to the server.