2
\$\begingroup\$

I'm trying to keep the code as clean as possible. Is this the best approach? I don't use jQuery that often.

// ==============================================
// Trigger longer description on product page
// ==============================================
var longDescription = $j("#js-long-description");
var shortDescription = $j("#js-shortened-description");
var showHide = $j("#js-trigger-long-description");
var inSpeed = 500;
var outSpeed = 100;
longDescription.hide();
showHide.on("click", function () {
 var buttonTxt = longDescription.is(':visible') ? 'Read More' : 'Read Less';
 showHide.text(buttonTxt);
 if (longDescription.is(':visible')) {
 shortDescription.fadeIn(inSpeed);
 longDescription.fadeOut(outSpeed);
 } else {
 shortDescription.fadeOut(outSpeed);
 longDescription.fadeIn(inSpeed);
 }
});
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 24, 2015 at 17:01
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

It looks pretty clean. You are saving the values into variables so to avoid re-running the query.

A minor improvement would be to use click function instead of on('click') as it more readable.

For the toggle part, one can identify 2 phases when clicking:

  1. change button text
  2. animate the description

If you don't need to keep them separate you can remove the ternary operator (the expr1? expr2: expr3) and do:

showHide.click( function () {
 if (longDescription.is(':visible')) {
 showHide.text('Read More');
 shortDescription.fadeIn(inSpeed);
 longDescription.fadeOut(outSpeed);
 } else {
 showHide.text('Read Less');
 shortDescription.fadeOut(outSpeed);
 longDescription.fadeIn(inSpeed);
 }
});
answered Mar 24, 2015 at 19:11
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.