Brianfidler wrote: > Can anybody offer some advice on how to make the following > code more efficient? I'm reusing a lot of the same code and I > know it can be streamlined quite a bit. > > $(document).ready(function() { > $('#question1').click(function() { > $('#contentblock #answer6, #contentblock > #answer5, #contentblock #answer4, #contentblock #answer3, > #contentblock #answer2, #contentblock #answer1').addClass('hidden'); > $('#contentblock #answer1').removeClass('hidden'); > }); > > $('#question2').click(function() { > $('#contentblock #answer6, #contentblock > #answer5, #contentblock #answer4, #contentblock #answer3, > #contentblock #answer2, #contentblock #answer1').addClass('hidden'); > $('#contentblock #answer2').removeClass('hidden'); > }); > > $('#question3').click(function() { > $('#contentblock #answer6, #contentblock > #answer5, #contentblock #answer4, #contentblock #answer3, > #contentblock #answer2, #contentblock #answer1').addClass('hidden'); > $('#contentblock #answer3').removeClass('hidden'); > }); > > $('#question4').click(function() { > $('#contentblock #answer6, #contentblock > #answer5, #contentblock #answer4, #contentblock #answer3, > #contentblock #answer2, #contentblock #answer1').addClass('hidden'); > $('#contentblock #answer4').removeClass('hidden'); > }); > > $('#question5').click(function() { > $('#contentblock #answer6, #contentblock > #answer5, #contentblock #answer4, #contentblock #answer3, > #contentblock #answer2, #contentblock #answer1').addClass('hidden'); > $('#contentblock #answer5').removeClass('hidden'); > }); > > $('#question6').click(function() { > $('#contentblock #answer6, #contentblock > #answer5, #contentblock #answer4, #contentblock #answer3, > #contentblock #answer2, #contentblock #answer1').addClass('hidden'); > $('#contentblock #answer6').removeClass('hidden'); > }); > });
Add a "question" class to each of your clickable questions and an "answer" class to each of your hidable answers. Then use: $(document).ready(function() { $('.question').click(function() { var answerNum = this.id.replace('question',''); $('#contentblock .answer').addClass('hidden'); $('#contentblock #answer' + answerNum).removeClass('hidden'); }); }); This hides all answers based on class and then unhides the desired answer based on id. I use this.id.replace('question','') instead of this.id.substr(8,1) to make it more obvious what I'm doing. Also, I tend to use underscores to cleanly separate naming from numbering in ids, but it's just a style I like: $(document).ready(function() { $('.question').click(function() { var answerNum = this.id.replace('question_',''); $('#contentblock .answer').addClass('hidden'); $('#contentblock #answer_' + answerNum).removeClass('hidden'); }); }); HTH and LMK if it gives you what you need. -- -Mike Schinkel http://www.mikeschinkel.com/blogs/ http://www.welldesignedurls.org http://atlanta-web.org