I have this jQuery handled buttons. But I think I overdid it with the if else statements.

I am wondering if the code can be more efficient in some way than what I have. It's mainly voting up and down. So what is does is toggle buttons and inserts HTML.

function handleVote(commentid, voted, type){
      url: endpoint + commentid + "/update/",
      method: "PATCH",
      data: { commentid: commentid, voted: voted,  type: type},
      success: function(data){
        if(type === 'down' && voted === 'True'){
          $('.comment-item .down-vote .i-down-'+commentid+'').toggleClass('active-color');
          $('.comment-item .down-vote .i-down-'+commentid+'').toggleClass('opacity-initial');
          $('.comment-item .down-vote .i-down-'+commentid+'').css('opacity', '0.2')
        } else if(type === 'down' && voted === 'False'){
          $('.comment-item .down-vote .i-down-'+commentid+'').toggleClass('active-color');
          $('.comment-item .down-vote .i-down-'+commentid+'').toggleClass('opacity-initial');
        } else if(type === 'up' && voted === 'True'){
          $('.comment-item .up-vote .i-up-'+commentid+'').toggleClass('primary-color');
          $('.comment-item .up-vote .i-up-'+commentid+'').toggleClass('opacity-initial');
          $('.comment-item .up-vote .i-up-'+commentid+'').css('opacity', '0.2')
        } else if(type === 'up' && voted === 'False'){
          $('.comment-item .down-vote .i-up-'+commentid+'').toggleClass('primary-color');
          $('.comment-item .down-vote .i-up-'+commentid+'').toggleClass('opacity-initial');

        $(".comment-vote-down .vote-count-down-" + commentid +"").html(`-${data.num_vote_down}`);
        $(".comment-vote-up .vote-count-up-" + commentid +"").html(`+${data.num_vote_up}`);
      error: function(data){
        var msg = formatErrorMsg(data.responseJSON)
        $("[data-id='" + commentid + "']").closest('div .comment-wrapper').after(msg);

1 Answer 1


Use variable for element, toggle can take multiple classes, use minimal selector.

var voteButton;
if(type === 'down'){
    voteButton = $('.i-down-' + commentid);
    voteButton.toggleClass('active-color opacity-initial');
} else {
    voteButton = $('.i-up-'+commentid);
    voteButton.toggleClass('primary-color opacity-initial');    
if(voted === 'True'){
    voteButton.css('opacity', '0.2')

or you could stack functions

$('.comment-item .down-vote .i-down-'+commentid+'')
  .toggleClass('active-color opacity-initial')
  .css('opacity', '0.2')
  • \$\begingroup\$ If you're able to use ES6 syntax, or transpile with Babel, you can also use string literals to make the selector dynamic, e.g. `.comment-item .${type}-vote .i-${type}-${commentid}` \$\endgroup\$ Feb 18, 2020 at 22:53

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.