From 679cccc893ef3bc77ca6d5fd63734324411c06a5 Mon Sep 17 00:00:00 2001 From: zPlus <-> Date: Mon, 27 Mar 2017 20:00:47 +0200 Subject: [PATCH] Fix #47 Some issues with voting mechanism --- javascript/freepost.js | 44 ++++++++++++++++++++++++++++++++---------- template/vote.twig | 4 ++-- 2 files changed, 36 insertions(+), 12 deletions(-) diff --git a/javascript/freepost.js b/javascript/freepost.js index 82379683..bce08069 100644 --- a/javascript/freepost.js +++ b/javascript/freepost.js @@ -33,7 +33,11 @@ * to the user after clicks. */ -function vote (action, dom_element) { +/** + * Change arrows class when voting. + */ +function vote (action, dom_element) +{ var arrow_up = dom_element.children[0]; var vote_counter = dom_element.children[1]; var arrow_down = dom_element.children[2]; @@ -41,18 +45,18 @@ function vote (action, dom_element) { // Voted/Upvoted var current_status = 0; - if ("upvoted" == arrow_up.className) + if (arrow_up.classList.contains('upvoted')) current_status = 1; - if ("downvoted" == arrow_down.className) + if (arrow_down.classList.contains('downvoted')) current_status = -1; // Current vote var current_vote = Number (vote_counter.textContent); // Remove class from arrows - arrow_up.className = ""; - arrow_down.className = ""; + arrow_up.classList.remove ('upvoted'); + arrow_down.classList.remove ('downvoted'); // Toggle upvote class for arrow if ("up" == action) @@ -60,11 +64,11 @@ function vote (action, dom_element) { { case -1: vote_counter.textContent = current_vote + 2; - arrow_up.className = "upvoted"; + arrow_up.classList.add ('upvoted'); break; case 0: vote_counter.textContent = current_vote + 1; - arrow_up.className = "upvoted"; + arrow_up.classList.add ('upvoted'); break; case 1: vote_counter.textContent = current_vote - 1; @@ -80,11 +84,31 @@ function vote (action, dom_element) { break; case 0: vote_counter.textContent = current_vote - 1; - arrow_down.className = "downvoted"; + arrow_down.classList.add ('downvoted'); break; case 1: vote_counter.textContent = current_vote - 2; - arrow_down.className = "downvoted"; + arrow_down.classList.add ('downvoted'); break; } -} \ No newline at end of file +} + +// Wait DOM to be ready... +document.addEventListener ('DOMContentLoaded', function() { + + /** + * A "vote section" is a containing + * - up arrow + * - votes sum + * - down arrow + */ + let vote_sections = document.getElementsByClassName ('vote'); + + // Bind vote() event to up/down vote arrows + for (var i = 0; i < vote_sections.length; i++) + { + vote_sections[i].children[0].addEventListener ('click', function () { vote ('up', this.parentNode) }); + vote_sections[i].children[2].addEventListener ('click', function () { vote ('down', this.parentNode) }); + } + +}); diff --git a/template/vote.twig b/template/vote.twig index c3f3c74d..88435789 100644 --- a/template/vote.twig +++ b/template/vote.twig @@ -12,14 +12,14 @@ {% if user %} - + bump {# Show number of votes #} {{ vote_count }} - + sink