In this tutorial we will review:
- Basic document jQuery preparation
- Binding jQuery actions to an anchor (A) tag
If you want some more basic information you can check out some of my other jQuery basic tutorials:
- Basic AJAX Tutorial: jQuery toggle and slide – Includes AJAX definition, Introduction to jQuery
- Basic AJAX Tutorial: Smooth Scrolling Text Marquee with a jQuery plugin – Includes plugin definition, how to install a plugin
Basic document jQuery preparation
The foundation of any jQuery tutorial is setting up the page to work with jQuery.
The first thing we need to do is incorporate the jQuery library in our page. So download jQuery (direct link to the Google Code location).
Now that we have our JS library, we need to tell our document where it is (I renamed my js file to jquery.js, and threw it in the js folder):
We inserted the SCRIPT tag to include the jquery library when the page is loaded.
Binding jQuery actions to an anchor (A) tag
Lets create two basic links in our document, one to “Fade In” and another to “Fade Out”:
We now have 2 links that do nothing. We are preparing to bind jQuery to the anchor.
Fadein and Fadeout: Fading a div in and out
First, we need to create a DIV to fade, and second we will do the fading.
For fading in and out, we will be using the jQuery command: fadeTo
fadeTo takes 2 required parmeters — duration, and opacity. Duration can be a number (in milliseconds, 1000 is 1 second) or a string (such as “fast”, 200 ms and “slow”, 600 ms). Opacity is a value from 0 – 1, with 0.5 being 50% opacity (and 0 being invisible).
To do this, we change our code below:
In the past step, we accomplished 3 things.
First we added IDs to the hrefs, so we can bind to them. You can see [id=”fadeinButton”] applied to the “Fade In” text, and [id=”fadeoutButton”] applied to the “Fade Out” text. Using a jQuery selector we can access these with [#fadeinButton].
Second, we added the “fadeSection” DIV to the document. We will be controlling this with the jQuery code.
Third, we added code to the document to handle the fading. On two lines we use the fadeTo command, [ $(‘#fadeSection’).fadeTo(‘slow’, 1.0); ] and [ $(‘#fadeSection’).fadeTo(‘fast’, 0.1); ]. The first one tells the [#fadeSection] to fade to 100% alpha slowly, it is bound to clicking on the [Fade In] text. The second one tells the [#fadeSection] to fade to 10% alpha quickly, bound to click on the [Fade Out] text.
You can see a working example here — jQuery Fadein and Fadeout example
Remember, after you fade out once, clicking “fade out” won’t do anything. You have to click on “fade in” again.