Shorten code with ternary operators

How can I reduce the following operations using ternary operators?

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

No need to use the ternary operator, .toggleClass()takes a second argument to determine whether to add or remove a class:

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

However, to answer your question as you asked (do not use it!):

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

Even better than a triple, using the parameter switchintoggleClass()

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

Source: https://habr.com/ru/post/1533087/


All Articles