Accordion, last part, the javascript
So now we have our structure, we need the javascript to do the magic.
First create a new file and give it the js extension. Always better to put your code in a separate file than on the head of your page.
What the javascript will do:
- Hide everything except the intro of each news.
- add a link “view more”
- A click on this link should open the rest of the text
First hide your divs:
$(document).ready(function()
{
$("#news dd div.newsText").hide();
});
$(document).ready(function(){…}); is here to say “Don’t do anything before the document is loaded. If you try to interact with the html of your page it is loaded it wont work.
$(”#news dd div.newsText”).hide(); Simple, pretty much like in css, we apply the hide function on the div class newsText children of a dd element, children of an element with an id news.
Next the links:
$("#news dd div.intro").append("<a href='Javascript:;' class='more'>...more</a>");
$("#news dd div.newsText").append("<a href='Javascript:;' class='close'>close</a>");
Nothing difficult here, we append some html to the element.
End last but not least the open and close bit:
$("#news dd div.intro a.more").click(function()
{
$(this).hide();
$(this).parent().next().slideDown("normal");
$(this).parent().next().children("a.close").show();
});
$(”#news dd div.newsText a.close”).click(function()
{
$(this).hide();
$(this).parent().slideUp(”normal”);
$(this).parent().prev().children(”a.more”).show();
});
First we create a listener on the links, so when they are clicked we can do an action. The action here is to hide the link, open the next children of the parent of the link and show the close link. The other way round for the close part.
So all in all the javascript is:
$(document).ready(function()
{
$("#news dd div.newsText").hide();
$("#news dd div.intro").append("<a href='Javascript:;' class='more'>...more</a>");
$("#news dd div.newsText").append("<a href='Javascript:;' class='close'>close</a>");
$(”#news dd div.intro a.more”).click(function()
{
$(this).hide();
$(this).parent().next().slideDown(”normal”);
$(this).parent().next().children(”a.close”).show();
});
$(”#news dd div.newsText a.close”).click(function()
{
$(this).hide();
$(this).parent().slideUp(”normal”);
$(this).parent().prev().children(”a.more”).show();
});
});
And because we have done all of this in javascript, if it is not present on the client he wont even see some random links that don’t work. I think it is of good practice to first create a working page without any fancy stuff and after add the javascript. So you know that your information will always be accessible.
Here is a link the example page with all the source code you need: Accordion srouce code


