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);

    }
});
\$\endgroup\$
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);
    }
});
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.