1

What would be a better to state the following:

 var active = '-active';
 if ($j('body').hasClass('faqs')) { $j('.faqs-support').toggleClass('faqs-support' + active); }
 if ($j('body').hasClass('cameras')) { $j('.camera-support').toggleClass('camera-support' + active); }
 if ($j('body').hasClass('manuals')) { $j('.manuals-support').toggleClass('manuals-support' + active); }
 if ($j('body').hasClass('downloads')) { $j('.downloads-support').toggleClass('downloads-support' + active); }
1
  • 1
    please mark it as code so it could be readable Commented Jun 30, 2011 at 20:40

4 Answers 4

2

How about:

$j.each(['faqs', 'cameras', 'manuals', 'downloads'], function(i, e){
  if ($j('body').hasClass(e)) {
    $j('.'+e+'-support').toggleClass(e+'-support-active');
  }
});
Sign up to request clarification or add additional context in comments.

2 Comments

You should cache $j('body') so it doesn't have to find elements by tag name a bunch of times, only to get the same result and throw things away.
@minitech: Yes, that is a possible further improvment, depending on whether you want simplicity or efficiency. Right now it just does it the same way as the original code.
2
var $body = $j('body');
var arr = ['faqs', 'cameras', 'manuals', 'downloads'];
$j.each(arr, function(index, item) {
    if($body.hasClass(item)) $j('.' + item + '-support').toggleClass(item + '-support-active');
});

Is about how I would write that. Not much shorter or much more efficient, but clearer.

1 Comment

exactly what i was just about to write
2

If that's the only class on the body, just grab the full className, and use it for the DOM selection and the .toggleClass():

var body_class = document.body.className + '-support';
$j('.' + body_class).toggleClass(body_class + '-active');

Just one change you'd need to make would be to change '.camera-support' to '.cameras-support'. (Adding the "s".)

Comments

1

if the body can only have one of those classes then you could do:

var cls = $j('body').attr('class');
if(cls)
    $j('.'+cls+'-support').toggleClass(cls+'-support-active');

1 Comment

+1 Looks like we were on the same track. :o) I'd just change cls+'-support'+active to cls+'-support-active'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.