webbydevy
webbydevy

Reputation: 1220

Shorten code using Ternary Operators

How would one shorten the following using ternary operators?

if ((pos - maxPos) == (c.clientWidth)) {
    $j("#next").addClass("filter");
} else {
    $j("#next").removeClass("filter");
}

Upvotes: 0

Views: 266

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318498

No need to use a ternary operator, .toggleClass() accepts a second argument to determine if the class should be added or removed:

$j('#next').toggleClass('filter', ((pos - maxPos) == c.clientWidth))

However, for the sake of answering your question exactly like you asked (don't use it!):

$j('#next')[((pos - maxPos) == c.clientWidth) ? 'addClass' : 'removeClass']('filter');

Upvotes: 7

elclanrs
elclanrs

Reputation: 94101

Even better than a ternary, using the switch param in toggleClass()

$j("#next").toggleClass("filter", pos - maxPos === c.clientWidth);

Upvotes: 1

Related Questions