\$\begingroup\$
\$\endgroup\$
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){
$.ajax({
url: endpoint + commentid + "/update/",
method: "PATCH",
data: { commentid: commentid, voted: voted, type: type},
success: function(data){
console.log(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);
}
})
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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')
answered Feb 17, 2020 at 9:00
-
\$\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\$Adam Taylor– Adam Taylor2020年02月18日 22:53:13 +00:00Commented Feb 18, 2020 at 22:53
default