1

If you use jQuery this code should be self-explanatory:

//fade the show-data class in or out of view
if($(this).hasClass('open')){
    $(obj).find('.show-data').hide(250);    
}else{
    $(obj).find('.show-data').show(250);
}

what I'm wondering if there's some way to do this in fewer lines as follows:

$(obj).find('.show-data').fn[$(this).hasClass('open') ? 'hide' : 'show'](250);

Thanks

8
  • 1
    You can, as @dystroy's answer shows. A better question is whether you should. Is that kind of code really clearer? Commented Sep 8, 2014 at 9:09
  • It's too bad the version of .toggle() that takes a showOrHide parameter doesn't also allow a duration. Commented Sep 8, 2014 at 9:14
  • thanks for both of your replies, as you can see i was "close" with .fn but the answer below solved that. My criteria for doing something like this (since this is a forum) is if I believe that the logical ternary will only affect one action (in this case hide/show). If more actions will be done, then I would go with my original curly brace logic. Not sure why but to my brain this is actually clearer. Commented Sep 8, 2014 at 9:14
  • @SamuelFullman SO is not really a forum.... Commented Sep 8, 2014 at 9:15
  • 1
    Shortening the code makes it faster to read and thus helps readability. I find this especially important if it can make some consistent unit of code be seen at a glance. Of course the gain is void if the shortening made it harder to understand... Commented Sep 8, 2014 at 9:49

1 Answer 1

1

Simply this :

$(obj).find('.show-data')[$(this).hasClass('open') ? 'hide' : 'show'](250);
Sign up to request clarification or add additional context in comments.

Comments

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.