Reputation: 49
Im trying to make an accordion with toggle which seems to work pretty good now. What i would like to get some help with as a newbie to javascript is the way it is put together.
This isnt pretty i know...
$(document).ready(function() {
$('#contact').click(function() {
$('#content2, #content3').hide(200, 'linear');
$('#content').toggle(700, 'linear');
});
});
$(document).ready(function() {
$('#services').click(function() {
$('#content, #content3').hide(200, 'linear');
$('#content2').toggle(700, 'linear');
});
});
$(document).ready(function() {
$('#about').click(function() {
$('#content, #content2').hide(200, 'linear');
$('#content3').toggle(700, 'linear');
});
});
Upvotes: 1
Views: 4205
Reputation: 5128
your code isn't very extensible, you might want to try it like this: http://jsfiddle.net/PzYvA/
$(document).ready(function() {
var $menu = $("#menu");
$menu.children("a").click(function(){
var $content = $(this).next("div");
$menu.children("div").not($content).hide(200, 'linear');
$content.toggle(700, 'linear');
});
});
also add the following css
#menu > a {
display:block;
}
and remove the <br />
after the a tags
Upvotes: 1
Reputation: 7427
You can see that your 3 fonctions have quite the same code.
Then, you have to use html class to define the functios of your html element, and then with javascript/jquery, defined how theses fonctions works.
It will simplify your CSS and your javascript:
Upvotes: 0
Reputation: 253318
I'd suggest:
$('#menu > a').click(function() { // specifies which a elements
var that = $(this), // caching the selectors for performance
divs = $(this).siblings('div'),
div = $(this).nextAll('div:first');
divs.not(div).hide(200, 'linear'); // hides all the sibling divs *except* for the
// immediately following div element
div.toggle(700, 'linear'); // toggles the immediately-following div
});
References:
Upvotes: 2