I'm trying to implement upvote/downvote for forum posts. I have some Jquery code written up and it's working when you click the up-arrow or the down-arrow. But there are two issues:
There is an up arrow like I mentioned that I'm using from bootstrap and then to the right of the arrows I have a counter for how many times each post was upvoted and downvoted. There is some default spacing, that I guess comes from bootstrap. When I click the button, the arrow and the corresponding counter number lose their spacing. But go back to normal when I refresh the page.
When a user clicks the up arrow, the arrow and counter turn green. And when a user clicks the down arrow, the down arrow and counter turn red (only to the current user). When I refresh or go back to the page, the color disappears and goes back to normal. How can I get the colors of the voted posts to stay for the current user?
_forum_post.html.erb
<div class="pull-left vote-links">
<%= link_to like_forum_forum_thread_forum_post_path(@forum, @forum_thread, forum_post), class: 'glyphicon glyphicon-triangle-top upvoteButton', method: :put do %>
<%= forum_post.get_upvotes.size %>
<% end %><br />
<%= link_to dislike_forum_forum_thread_forum_post_path(@forum, @forum_thread, forum_post), class: 'glyphicon glyphicon-triangle-bottom downvoteButton' , method: :put do %>
<%= forum_post.get_downvotes.size %>
<% end %>
</div>
forum_posts.js
$(document).ready(function() {
$('.vote-links').on('click', 'a', function(e) {
e.preventDefault();
var currentTarget = $(e.currentTarget);
var voteLinksDiv = currentTarget.parents('.vote-links');
if (currentTarget.is('.upvoteButton')) {
currentTarget.css({color: 'green'});
voteLinksDiv.find('.downvoteButton').css({color: '#333'});
}
else {
currentTarget.css({color: 'red'});
voteLinksDiv.find('.upvoteButton').css({color: '#333'});
}
$.ajax({
url: currentTarget.attr('href'),
type: 'PUT',
data: { format: 'json' },
dataType: 'json',
complete: function(xhr, textStatus) {
voteLinksDiv.find('a.upvoteButton').text(xhr.responseJSON.upvote);
voteLinksDiv.find('a.downvoteButton').text(xhr.responseJSON.downvote);
}
});
return false;
});
});
forum_posts_controller.rb
def upvote
@forum_post.upvote_by current_user
respond_to do |format|
format.html { redirect_to :back }
format.json { render :json => { downvote: @forum_post.get_downvotes.size, upvote: @forum_post.get_upvotes.size } }
format.js
end
end
def downvote
@forum_post.downvote_by current_user
respond_to do |format|
format.html { redirect_to :back }
format.json { render :json => { downvote: @forum_post.get_downvotes.size, upvote: @forum_post.get_upvotes.size } }
format.js
end
end