Category Archives: JavaScript

Creating a jQuery Accordion

Share

One task that jQuery makes very easy is creating an accordion effect. To do this, we will use the jQuery UI extension library. This is useful if you have a long section of text that is broken up into subsections. By using an accordion, you only display one subsection at a time, but all the other text is available to read at any time. So, for example, on this sample page, there is a long string of information about Piratedrive, broken up in to seven subsections (General Information, Personal Piratedrive, etc.). So to make the page shorter, I’m going to put the text into an accordion. As you will see, this is very easy to do – in fact, I would say that creating the HTML structure is harder than the actual JavaScript in this case.

HTML Content

First, the content has to be formatted so that it can be converted easily. The jQuery UI library requires that the page content be formatted something like this:

<h3><a href="#">Subsection One Title</a></h3>
<div>
     Subsection One Content.  Can be text, image, links, anything you want.

     The content can be multiple paragraphs and contain any html tags that you want.
</div>

<h3><a href="#">Subsection Two Title</a></h3>
<div>
     Subsection Two Content.  Again, can be text, image, links, anything you want
</div>

The links (a href=”#”) are required, because they will be the triggers that cause the subsections to open. The subsection headings do not actually have to be h3’s, but that is the default, so for the tutorial that is what I’ll use. I’ll post a link to the documentation so if you want to do something more advanced you can. So, for step one of the tutorial, I’ve set up the sample page linked above with the content in that format.

The other next step is that all the subsections have to be wrapped in a div tag with an id that we will use to identify it. I’m going to call this one “myAccordion”, just to make it easy to see what I want it to be converted into, but you can name it any valid name.

<div id="myAccordion">
     <h3><a href="#">Subsection One Title</a></h3>
     <div>
          Subsection One Content.  Can be text, image, links, anything you want.

          The content can be multiple paragraphs and contain any html tags that you want.
     </div>

     <h3><a href="#">Subsection Two Title</a></h3>
     <div>
          Subsection Two Content.  Again, can be text, image, links, anything you want
     </div>
</div>

Remember, id’s are required to be unique on a page, so if you plan on putting two accordions on your page, you cannot name both of them “myAccordion”.

Importing jQuery UI

The next step is to include the jQuery UI library on the page. To do this, you would use the Include JavaScript Custom Element. We have the library stored on our server at http://www.ecu.edu/js/jquery-ui-1.8.13.min.js, so when you put the element on the page, put “/js/jquery-ui-1.8.13.js” (minus the quotes) in the external source text box:

Last Step

And now, there is only one more step to go. You need to add other Include JavaScript Custom Element and put this code in the Script Input box:

$(document).ready(function() {
    $('#myAccordion').accordion();
});

If you named your div something other than “myAccordion”, put that in place of the “myAccordion” (that follows the “#”) in the code.

Styling

When your page reloads, will should see that the accordion works, as here: http://www.ecu.edu/cs-training/hallwa/Accordion-Step-Two.cfm. As you can see, the style is rather plain, so you can either create your own style sheet, use one of two ECU customized one, located at /css/jquery-ui.css (very purple and gold themed) or http://www.ecu.edu/css/custom-theme/jquery-ui-1.8.2.custom.css (a subtler theme), or some combination of an existing style sheet and your own styles. There is a tutorial here on how to use a style sheet in CommonSpot.

After applying the purple and gold theme, the page looks like this: http://www.ecu.edu/cs-training/hallwa/Accordion-Step-Three.cfm

Advanced Configuration

There are several advanced configuration options that you set if you dislike the defaults. For example, as you can see, by default the first subsection is active (opened for viewing) and the height of all the subsections is the same (the height of the tallest), and one subsection is open at all times. Let’s use the advanced options (found here http://jqueryui.com/demos/accordion/ under Options) to change our accordion so that when the page loads all the tabs are closed, the user can close a subsection by clicking on it while it is open, and to have each subsection only use its own height.

To do this, we have to edit our code that called the accordion function. Right now it is

$(document).ready(function() {
    $('#myAccordion').accordion();
});

.

Within the accordion() function, we are going to change the parameters. First let’s make the accordion collapsible, i.e. not required at a subsection is open at all times. We change the code to

$(document).ready(function() {
    $('#myAccordion').accordion( { collapsible: true  } );
});

Next, let’s make all the subsections load closed:

$(document).ready(function() {
    $('#myAccordion').accordion( { collapsible: true, active: false} );
});

Last, let’s change the height as sections load.

$(document).ready(function() {
    $('#myAccordion').accordion( { collapsible: true, active: false, autoheight: false  } );
});

When all completed, the page now looks like this:
http://www.ecu.edu/cs-training/hallwa/Accordion-Step-Four.cfm

Making Collapsible Content with jQuery

Share

One thing that you might want to do if you have very long lists of content is make them collapse or not display until the user clicks on a trigger that makes the content appear. A good example of this is the ITCS Service Catalog. If the page displayed all the links at once, the page gets very long, so instead we displayed the categories, then reveal the links when the user clicks on the category name.

To do this, we use jQuery, an open source JavaScript library.  Since jQuery is loaded on every CommonSpot page, all of its library functions are readily available for you to use at any time.  This tutorial only some of the most simple tasks that  jQuery is capable of. You can read about everything it can do at the jQuery Documentation site.

Setting up the HTML Content

The first step to cover is to create the list without hiding it. This is important, because if you hide it by default, then users who have disabled JavaScript will not be able to see the links that you are creating. I made a page with the list of links that are in the tool bar on the ECU Homepage, and some text that will be the trigger for displaying and hiding the links. The HTML for the content is this:

<p>Click Here to Toggle Links</p>
<ul id="hideableContent">
 <li><a href="http://blackboard.ecu.edu">Blackboard</a></li>
 <li><a href="http://help.ecu.edu">Help Desk</a></li>
 <li><a href="http://pirateid.ecu.edu">PirateId</a></li>
 <li><a href="/csecu/links_index.cfm">A to Z Index</a></li>
 <li><a href="/banner">Banner</a></li>
 <li><a href="/cs-ecu/email_phone.cfm">Email/Phone</a></li>
 <li><a href="http://onestop.ecu.edu">OneStop</a></li>
 <li><a href="/cs-ecu/calendar.cfm">Calendar</a></li>
 <li><a href="/admin/accessibility/">Accessibility</a></li>
</ul>

The next step is to hide the links when the page loads. What we want to hide is the list element that starts with <ul id=”hideableContent”> and ends with </ul>. The id that I have given this list is important, as that will let us change this list but not others on the page that we don’t want to hide.

Selecting

So to hide this, we will use jQuery. To explain simply what jQuery does: it selects (or finds) an element or elements and then usually performs some tasks on what is selected. The code follows this pattern:

$("[what you want to select]").[what you want to do to what is selected];

We want to select the ul with the id hideableContent, so the specific code is this:

$("#hideableContent").toggle();

The string “#hideableContent” tells the selector what to look for and is made up of two parts: the pound sign, and hideableContent.

The #hideableContent select the element with an id of hideableContent. This is case sensitive, so make sure you match the id exactly.  Also, make sure that you use an id only once per page.  If you use the same id value more than once unpredictable things will happen.  The pound sign tells the selector that the next word is an id. The toggle() function hides what is visible and shows what is hidden. Since the content is visible when the page loads, this code will hide it.

You can also use a dot and the class name to select everything that has a specific class (e.g. $(‘.collapsible) would select everything that has a class of collapsible).

You can also select html tags by using just the tag with no dot or pound sign (e.g. $(‘ul’) would select every unordered list in the document).

You can select tags that are within other tags by putting them together with a space (e.g. $(‘ul li’) would select all the list items within all the unordered lists on a page).

And finally (actually this is a far from comprehensive list, but it is all I’m going to cover today) you can limit the selection to tags that have a class or id (e.g. $(‘ul.collapsible’) would select all unordered lists that have a class of collapsible. These are just a small part of the selectors. Can read about all the other options at the jQuery Documentation site.

The ready() Function

To get our code to work, the page needs to execute it. This is done by using the ready() function. It looks like this:

$(document).ready ( function () {
     [Code we want to execute goes here]
});

This is a function that is run automatically when the page is “ready”, i.e. when the DOM (Document Object Model) hierarchy has been fully constructed. So, to hide the list on page load, first you would put a JavaScript Include element on your page. Then you have two options. You could put the JavaScript code in the Script Input box, like this:

Or, you can save the code in a separate file, upload it via the tools page, and then include the location of the file, as here, where I have saved the code in file collapse-version1.js and uploaded it via my tools page. This seems the better option to me, because to update the page, all I have to do is make the changes to my JavaScript file and upload it, overwriting the previous version.

When the page reloads, you can see that the list is now hidden.

Activating the Toggle

The last step is to make the “Click Here to Toggle Links” active. I’m using a text hyperlink, but you can use anything you want, for example a button or an image. It just has to be selectable.

So first we will make that text a link, but instead of linking to a page, we set the link to be “#”. So that part of the HTML code will now look like this:

<p><a href="#">Click Here to Toggle Links</a></p>

Next, we want to add an id to the link, so that we can select it when it is clicked on. The Rich Text Editor in CommonSpot will not let you do this without switching to HTML view, so click on the button. It will show this:

Change the <a href=”#”> to <a href=”#” id=”toggleLink”>, then click the HTML button again and the Finish button.
The only thing left to do is write the jQuery code that will actually do the toggle. To do this, first you select the link, like this:

$("#toggleLink")

and add the click() function and the start of the code for the click function:

$('#toggleLink').click( function() {
     [toggling code will go here]
});

All this code does is tell jQuery to select the link and then do something when it is clicked on.
The code that will actually toggle the list is the same as we did when the document is ready:

$('#hideableContent').toggle();

So the whole JavaScript code will be:

$(document).ready( function() {
     $('#hideableContent').toggle();
     $('#toggleLink').click( function() {
          $('#hideableContent').toggle();
     });
});

And that is it. Your page should now work like this one.

As I said, this just a tiny example of what you can do. The jQuery documents cover it all. If you have any questions, feel free to ask and I will do my best to find an answer.

Rotating Images with the Cycle Element Tutorial

Share

The newest Custom Element is Cycle Images.  This element uses the Jquery Cycle plugin to create a rotating images effect.  The element has 12 different transition effects.  Several examples of the effects that this element can perform can be seen here: http://www.ecu.edu/cs-training/hallwa/Rotating-Images.cfm.

To use the element, you just need a collection of identically sized images.  The element takes all those images, lets you specify a duration and effect and then creates all the JavaScript and HTML for you.

First, log into your tools page and create a new folder.  For this example, I named my folder rotatingImages.  Then upload as many identically sized images as you want into that folder.  The images can be different types (jpegs, gifs and pngs are all allowed) but for the element to display the images properly, they must all be the same size.  For my examples, I used images 770 pixels wide and 170 high.

Next, add a Cycle Images Custom Element (listed under Custom Elements) to your page.  Then click the “Click here to define the custom element data” link.  A popup window will launch.  Fill in the appropriate fields, like so:

  • Image Directory – the folder name where you uploaded the file.  Required.
  • Time to display – the the length of time in seconds to display each image before the transition effect takes place.  Required.  Must be a number, and  decimals are valid, so you can put 3.5 to display each image for three and a half seconds.
  • Change Duration – The length of time in seconds that the transition should take.  Required.  Must be a number, decimals are valid.  In my opinion, all the effects except the Fade effect look best with short (i.e. less than one second) durations.  The fade effect looks very nice with relatively long (5 seconds or more) durations.
  • Transition Effect – the visual effect that you want as the images change.  The option are:
    • Fade – The current image fades out and the next image fades in at the same time.
    • Cover – The current image remains in place and the next image moves in from the left to cover it.
    • ScrollDown – The current image moves down and at the same time the next image moves down to replace it.
    • ScrollUp – The same as ScrollDown but upward instead of downward.
    • ScrollLeft – The same as ScrollDown but the direction is to the left.
    • ScrollRight – The same as ScrollDown but the direction is to the right.
    • SlideX – The current image appears to fold in to the left and the next image folds out to the right.
    • Turndown – Simulates somewhat the effect of turning a photocube downward.
    • CurtainY – The current image folds in toward the middle and the next folds out from the middle.
    • Wipe – The current image remains in place and the next image is revealed from the top left diagonally to the bottom right.
    • Toss – The current image moves off screen to the right, revealing the next image beneath.
    • Shuffle – The current image moves off to the left and then moves behind the next image.
  • Height – The height of the images in pixels.  Required.
  • Width – The width of the images in pixels.  Required.
  • Margin – The CSS margin desired for the element.  Optional, by default is set to 0.  When using the element as a replacement for the header image, then 0 is what you want.  If you are using the element anywhere else on a page and want to have the image use all the width of the page, you need to set this to -10 (negative 10) to compensate for the inherited properties.

cycledImages

Two final caveats:

  1. If you try to put two of these on a page, only the first will work.  This is because the JavaScript works by identifying the element by its id, and these must be unique.
  2. If you copy a page that this element is on, then if you change anything in this element, it will be changed on both pages, since those pages will be sharing one instance of the element.  You can copy the page and then remove the element and add a new one however to prevent this from happening.

As always, if you have questions, comments or suggestions, please let me know.  And be sure to check out the ITCS Learning Center for lots more information about how to use CommonSpot more effectively.

Lightbox Slide Show Element Tutorial

Share

Today’s tutorial is about the new Slide Show custom element.  This element lets you quickly and easily make a JavaScript lightbox slide show, like the one here: http://www.ecu.edu/cs-training/hallwa/Emirati-Money.cfm (opens in a new window). To make a slideshow like this, just follow these few steps:

  1. Login to your tools page and create a new folder that will contain your slide show images.  This folder must be directly within your tools page (i.e. it cannot be a subfolder of another folder).
  2. Upload your images to the folder.  The images do not have to be the same type or size, so it is fine if you want to have a 1000×500 JPG, 200×400 GIF , and a 250×250 PNG all in the same show.
  3. Add a Slide Show Custom Element (listed under the Custom Elements) to a CommonSpot page.
  4. Use the “Click here to define custom element data” link.
  5. Fill in the appropriate boxes in the form.
    1. Show Name is the display name that will appear on the page. Required.
    2. Image Folder is the name of the folder that contains your slide show images. Required.
    3. Description is free space to put whatever information you want.  This will appear above the thumbnails of your slides.  Optional.
    4. Advance Photos Automatically.  If checked, then the slides will change automatically, though the user will still be allowed to pause the show as well as move forward or back manually.
    5. Duration is the number of second to pause between slides if the “Advance Photos Automatically” option is picked.
  6. Click Finish.

ss_sc_01

The element will automatically create 60 pixel high thumbnails for you and write all the CSS and JavaScript to render the slide show.  The thumbnails are located in a subfolder of your image folder named “tn”, so do not delete this folder or the images within without reason.

At any time you can delete or add photos to your image folder.  If you add photos, be sure to view the page on author to generate thumbnails for the new images.   If you delete photos, you probably also want to delete the associated thumbnails, though this is not strictly necessary.

The order in which the images appear is alphabetical based on the file names, so you can determine the order of the images by renaming the files.

Another option to enhance your slide show is to have each slide have individual text associated with it.  For example, the sample show linked to above has a short paragraph describing each note.

To do this, go to your tools page.  You should have a link named “Slide Show Text Editor”.  Click that.

ss_sc_02

A pull down will appear with a list of all the folder sin your tools page.  Pick the folder that contains your images.  The page will create a web form, load the images and give you a text box next to each.  Enter the text to accompany each image. (If you have already created text for your show, then the boxes should contain that text so that you can edit it).  Simple HTML for formatting is ok (BR, HR, STRONG, EM, etc) but more advanced  tags like links or styles can break the JavaScript that displays your show.

ss_sc_03

When you submit the form, it will create a text file in your image directory named “content.ini” that the show will use to include your text.  Do not delete this file from your tools page unless you want to remove your text from the slide show.

Lastly, the element has applied CSS classes to many of the elements so that you can add some custom styles by including a style sheet if you wish:

  • The entire element is contained in a div with a class named “slideShowDiv”.
  • The show title has a class named “slideShowTitle”.
  • The show description has a class named “slideShowDescription”.
  • The photos are contained in a div with a class named “slideShowPhotosContainer”.

I hope that this element will be useful.  As always, if you have any questions or suggestions, please let me know.