Princely
Princely

Reputation: 1

Thumbs up and thumbs down, saves locally, and continues counting any time new user clicks

I need help creating a thumbs up thumbs down button. My challenge is: 1: it does not count for both thumbs, instead counts for one 2. There is no space between the word "Bad" and the counter. 3. I want it to continue counting if anyone clicks on it when they come to the site. Here is a link to the pen: https://codepen.io/abdulhaldu/pen/RwWpKGV

<button onclick="clickCounter()" type="button" class="btn btn-success"><i class="fa fa-thumbs-up"></i><span class="vl"></span><div id="result"></div></button> <button onclick="clickCounter()" type="button" class="btn btn-danger"><i class="fa fa-thumbs-down"></i><span class="vl"></span> <div id="secondresult"</div></button>

Many thanks

Upvotes: 0

Views: 61

Answers (1)

Nikita Skrebets
Nikita Skrebets

Reputation: 1542

I made 1 function out of 2, accepting variable either it's like or dislike.

<button onclick="clickCounter('like')" type="button" class="btn btn-success">
  <i class="fa fa-thumbs-up"></i>
  <span class="vl"></span>
  <div id="like-count"></div>
</button>

<button onclick="clickCounter('dislike')" type="button" class="btn btn-danger">
  <i class="fa fa-thumbs-down"></i>
  <span class="vl"></span>
  <div id="dislike-count"></div>
</button>
function clickCounter(reaction) {
  const id = reaction === 'like' ? 'like-count' : 'dislike-count';
  
  if (typeof Storage === "undefined") {
    document.getElementById(id).innerHTML =
      "Sorry, your browser does not support web storage...";
  }
  
  localStorage[reaction] = localStorage[reaction] ? +localStorage.[reaction] + 1 : 1;
  const reactionName = reaction === 'like' ? 'good' : 'bad';
  document.getElementById(id).innerHTML = reactionName + ' ' + localStorage[reaction] + " time(s).";
}

codepen

Upvotes: 0

Related Questions