0
\$\begingroup\$

I have the following js code and am wondering how I can make it clean. It works fine but there are few repetitions. Is there a way to make it more clean?

$('.js-decline-button').click(function() {  
    $('.js-confirmation').show().stop(true).animate({ left : '0' }, 500);
});

$('.js-confirmation-yes').click(function() {
    $('.js-confirmation').stop(true).animate({ left : '-100%' }, 500);
    $('.container').delay( 500 ).fadeOut( 200 ).hide(200);
});

$('.js-confirmation-no').click(function() {
    $('.js-confirmation').stop(true).animate({ left : '-100%' }, 500);
});

jsFiddle

\$\endgroup\$
2
\$\begingroup\$

I would add a couple of named functions:

var hideConfirmationMessage,
    showConfirmationMessage;

hideConfirmationMessage = function () {
    $('.js-confirmation').stop(true).animate({ left : '-100%' }, 500);
};

showConfirmationMessage = function() {  
   $('.js-confirmation').show().stop(true).animate({ left : '0' }, 500);
};

Then your event handler attachment becomes much simpler:

$('.js-confirmation-yes').click(function() {
    hideConfirmationMessage();
    $('.container').delay(500).fadeOut(200).hide(200);
});

$('.js-confirmation-no').click(hideConfirmationMessage);
$('.js-decline-button').click(showConfirmationMessage);

I'm not sure if that's "cleaner" to you but I think it's easier to read and doesn't repeat itself.

\$\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.