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);
}
});
1 Answer 1
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:
- change button text
- 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);
}
});