webbydevy
webbydevy

Reputation: 1220

Optimize jQuery code

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); }

Upvotes: 1

Views: 101

Answers (4)

Andy
Andy

Reputation: 30135

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');

Upvotes: 1

user113716
user113716

Reputation: 322462

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".)

Upvotes: 2

Guffa
Guffa

Reputation: 700212

How about:

$j.each(['faqs', 'cameras', 'manuals', 'downloads'], function(i, e){
  if ($j('body').hasClass(e)) {
    $j('.'+e+'-support').toggleClass(e+'-support-active');
  }
});

Upvotes: 2

Ry-
Ry-

Reputation: 224877

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.

Upvotes: 2

Related Questions