Richard
Richard

Reputation: 445

Shorten JQuery Snippet

I have the following JQuery snippet:

(someVar.next().length == 0)?someVar.fadeOut().end().find("ul").first().fadeIn():someVar.fadeOut().next().fadeIn();

There is a fair amount of code duplication between the two results of the conditional - i.e. someVar.fadeOut() and .fadeIn() on both.

I would ideally like something like this:

someVar.fadeOut().((someVar.next().length == 0)?end().find("ul").first():next()).fadeIn();

But that doesn't work :) Safari developer tools reports a syntax error but I'm not skilled enough to work out how to do it properly.

If it can't be shortened, then just saying that is fine :)

Upvotes: 1

Views: 135

Answers (3)

user113716
user113716

Reputation: 322562

I removed the .end() because I don't see a use for it.

Otherwise, I just moved .fadeOut() into the conditional test.

(someVar.fadeOut().next().length == 0) 
?  someVar.end().find("ul:first").fadeIn()
:  someVar.next().fadeIn();

Or maybe this?

var $in = (someVar.fadeOut().next().length == 0) 
           ? someVar.end().find("ul:first")
           : someVar.next();
$in.fadeIn();

EDIT: As noted by @T.J. Crowder, I was not correct in removing .end(). I didn't realize that it continues to work if you start a new chain with the previous result. Makes sense though. Fixed.

Also, I had somehow reversed the second example. Fixed.


Another EDIT:

The second example could be further simplified like this:

((someVar.fadeOut().next().length == 0) 
           ? someVar.end().find("ul:first")
           : someVar.next()).fadeIn();

One more EDIT:

Another possibility is to simply .fadeIn() the .next() either way, which will have no effect if its length is 0:

if(someVar.fadeOut().next().fadeIn().length == 0)
     someVar.end().find("ul:first").fadeIn();

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075189

Perhaps somewhat off-topic and so I'm making it a CW, but: When things get long like this, can I just put in my bid for good old-fashioned if/else statements?

someVar.fadeOut();
if (someVar.next().length === 0) {
    someVar.end().find("ul").first().fadeIn();
}
else {
    someVar.next().fadeIn();
}

About eight times easier to read and maintain, IMHO.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075189

Not by much, no — or at least, not in a reasonable way (there are games you can play with strings and bracketed notation, but they would make your example worse, not better). You could move the fadeOut to its own statement:

someVar.fadeOut();
(someVar.next().length == 0)?someVar.end().find("ul").first().fadeIn():someVar.next().fadeIn();

...but after that, the chaining goes in different directions.

See also my community wiki answer.

Upvotes: 0

Related Questions