jquery cleanup

Soldato
Joined
12 May 2007
Posts
3,896
Location
Bristol
I will come right out and admit that I'm still trying to learn jquery and am only able to do fairly basic stuff with it without resorting to a premade solution.

Today, I needed to create an accordion-like FAQ. It needed to be able to do three things.
- It needed to be done with a definition list and an open answer needed to close if another question was clicked.
- It needed to have the question change color when clicked (to act as :visited).
- It needed to have the question change color on hover.

I was able to find a decent enough accordion which used nested unordered lists so I edited it to work with unnested definition lists instead.

For the last two, I knew enough jquery to be able to create them individually but not sure how I would go about combining them, or even better, combining all three.

Anyone who's better with jquery than I am able to help? It all works exactly how I want it to but it just seems sloppy to do them all seperately.


Jquery
Code:
function initMenu() {
  $('#faq dd').hide();
  $('#faq dt').click(
    function() {
      var checkElement = $(this).next();
      if((checkElement.is('dd')) && (checkElement.is(':visible'))) {
        return false;
        }
      if((checkElement.is('dd')) && (!checkElement.is(':visible'))) {
        $('#faq dd:visible').slideUp('normal');
        checkElement.slideDown('normal');
        return false;
        }
      }
    );
  }
$(document).ready(function() {initMenu();});

$(document).ready(function() { 
  $('#faq dt').click(  
    function() {  
      $(this).addClass('selected');  
    }  
  );  
}); 

$(document).ready(function() { 
  $('#faq dt').hover(  
    function() {  
      $(this).addClass('hover');  
    },  
    function() {  
      $(this).removeClass('hover');  
    }  
  );  
});

HTML
Code:
<dl id="faq">
  <dt>Question</dt>
  <dd>Answer</dd>
</dl>
 
Last edited:
If you're just trying to learn JQuery then ignore this post but if it's for a website couldn't you do it with CSS if your trying to do what i'm imagining. Would work for people with JS disabled then.

Just a suggestion
 
If you can figure out how to do this with CSS, you're certainly better at it than I am.
(I may be fairly new to doing my own jquery but CSS is something I know very well)

This is essentially what I've done except mine automatically contracts an expanded item when another is clicked rather than keep everything open.
http://www.dscoduc.com/page/FAQ-Plugin.aspx

The hover I can do with css obviously but as there are no <a> elements, it doesn't work in IE6 hence using jquery to add a class to the <dt> on hover and on click.

Mine also displays fully expanded with js disabled so it degrades just fine.
 
Back
Top Bottom