Increment and decrement the like count on fa-heart multiple times

Is there a way to increment the count of a fa-heart value on click and decrement it on the second click?

The issue I'm facing is that I have multiple fa-heart elements on the same page, making it challenging to increment or decrement the clicked fa-heart appropriately.

You can find my fiddle below:

https://jsfiddle.net/mehbub/d9e2qotg/1/

### Code Snippet:
(function() {
  const heart = document.getElementById('heart');
  heart.addEventListener('click', function() {
    heart.classList.toggle('red');
  });
})();
*(jQuery code for incrementing/decrementing likes)*
$count.text(function(idx, txt) {
   *(convert text to number and increment by one)*
   return +txt + 1;
});
#heart {
  color: grey;  
  font-size: 20px;
}

#heart.red {
  color: red;
}
*(HTML structure for fa-hearts with names and like counts)*

I am looking for a solution where each fa-heart can be individually clicked to either change its color to red (increment) or grey (decrement).

Thank you!

Answer №1

To optimize your code, consider removing the duplicate id heart. Since you already have a class heart, attach the click event to this common class and toggle the classes liked/notliked. These classes can be used as rules in your CSS, eliminating the need for red/grey classes. Here's an example:

$(document).on('click', ".heart", function() {
  var count = $(this).next('span');

  $(this).toggleClass('notliked liked');

  if ($(this).hasClass('liked')) {
    count.text(Number(count.text()) + 1);
  } else {
    count.text(Number(count.text()) - 1);
  }
});
.heart.notliked {
  color: grey;
  font-size: 20px;
}

.heart.liked {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<p>robert stephen</p>
<i class="fa fa-heart liked heart" value="1"></i>
<span class="likes-count"> 100 </span><br>

<p>James Camroon</p>
<i class="fa fa-heart liked heart" value="1"></i>
<span class="likes-count"> 101 </span><br>

<p>John Wick</p>
<i class="fa fa-heart liked heart" value="1"></i>
<span class="likes-count"> 37 </span><br>

<p>James Bond</p>
<i class="fa fa-heart liked heart" value="1"></i>
<span class="likes-count"> 22 </span><br>

<p>Avengers</p>
<i class="fa fa-heart liked heart" value="1"></i>
<span class="likes-count"> 90 </span>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Disabling an HTML attribute on a button prevents the ability to click on it

In my React application, I have a button component that looks like this: <button onClick={() =>alert('hi')} disabled={true}>test</button> When I removed the disabled attribute from the browser like so: <button disabled>test& ...

"Using the power of jQuery to efficiently bind events to elements through associative

I am attempting to link the same action to 3 checkboxes, with a different outcome for each: var checkboxes = { 'option1' : 'result1', 'option2' : 'result2', 'option3' : 'result3', }; ...

Bootstrap struggles to create panels of uniform size

Here is the code snippet I am currently working with: <div class="col-md-4"> <div class="panel panel-default"> <div class="panel-heading"> <h4><i class="fa fa-fw fa-tasks"></i> Extreme Performance</ ...

Exploring the functionality of the PageIndicator for Wearable Technology

Exploring the Page Indicator within a Tizen Wearable Application for Gear S3 Frontier has been an interesting journey. Despite successful implementation with text content, adding controls to each section or incorporating background images has proven challe ...

Enhance your Vue PWA by utilizing ServiceWorker to efficiently cache remote media assets fetched from an array of URLs

In my PWA development project, I am looking to provide users with the option to download and cache all media assets used in the application. However, the default behavior of PWAs only caches assets when they are requested during app navigation. My goal is ...

Is it possible to implement the SCSS CSS preprocessor in Angular 1.6.6, even though it is already utilizing LESS as the current CSS preprocessor?

Is it necessary to compile SCSS and Stylus files into CSS before importing them into my Angular version 1 app? Are there any other alternatives available? Context: I have two applications, one using Angular 4 with SCSS and the other using Angular 1 with L ...

Determining the selected input from numerous checkboxes in a React code and saving them within a blank array

I am currently working on a React project where I have multiple checkboxes that interact with a single component. The data in this component is supposed to change based on the checkbox that is selected. However, I am struggling to keep track of which check ...

Efficiently Extracting Data from an Array of Objects Using JQuery

What is the best method to extract information from the array below? How can I retrieve data categorized by specific categories? Is there a way to access only the key values? How do I retrieve just the data values? var main = [{ "key": "all", "dat ...

Executing Javascript prior to Gatsby page load

Currently, I am in the process of converting an HTML template using Bootstrap 5 into a Gatsby template. While the CSS and pages are functioning as expected, I have encountered an issue with the inclusion of a main.js file within the HTML template that need ...

Update the state within a callback to display corresponding content in a React component

Struggling with rendering conditional content based on the presence of a value. In my component, if an API key is not provided, I want to display an input field with a button. Once the API key is stored using `electron-json-storage` and set as a state, the ...

Showing a div with a smooth fade-in effect while switching its display property to inline using jQuery

Currently, I am working on a project that involves implementing a "side pop up". To ensure it doesn't flicker like it does with jQuery's "hide()" method, I want to start by setting the display property to none using CSS. My main question is: - Ho ...

Expanding and hiding content using jQuery while also utilizing cookies for persistence

Hey there! I have a piece of code that I'm working on and could use some help. I'm trying to create a cookie that can remember the current state of a div even if the user reloads the page. Any assistance would be greatly appreciated! jQuery(fun ...

Is there a way to allow an HTML page rendered by node.js to communicate back to its corresponding node.js file?

I am currently in the process of developing a registry system using node.js and HTML. However, I have encountered an issue where my HTML page is rendered by node.js, but when trying to call it back to the node.js file, it appears that the JS file cannot be ...

The Flask AJAX request is returning an empty ImmutableMultiDict, whereas the same AJAX request successfully works with http.server

Making the switch from http.server to Flask has caused issues with my image upload functionality using AJAX. This is being done in Python 3. Attempts at troubleshooting that have failed: I have ensured multipart/form-data is included in the Ajax req ...

What is the method of posting to PHP using JavaScript without utilizing Ajax?

My current code involves a drag and drop file uploader to PHP using ajax, but it seems that my web host does not support ajax. Is there an alternative method to achieve this without using ajax? Specifically, I am facing issues with the UploadFile functio ...

The Bootstrap 4 card component is a versatile and stylish

Currently working on a display layout using Bootstrap 4, specifically utilizing cards. The issue I'm facing is that the text exceeds the limit of the card, causing it to overflow. Is there a solution to make the text automatically wrap to the bottom ...

Transform jQuery code to its equivalent in vanilla JavaScript

While I am proficient in using jQuery, my knowledge of pure JavaScript is somewhat limited. Below is the jQuery code that I have been working with: $(document).ready(function() { $.get('http://jsonip.com/', function(r){ var ip_addre ...

Setting properties on functions and defining their prototype

My task involves working on the following block of code: function Vector(x, y) { this.x = x || 0; this.y = y || 0; } Vector.add = function(a, b) { return new Vector(a.x + b.x, a.y + b.y); }; Vector.sub = function(a, b) { return new Vecto ...

Retrieving Json data results in a boolean outcome

I am working on a code snippet that includes a switch statement which returns true or false, as well as an if and else statement for further validation. The goal is to send a value through an input field using ajax and have PHP return true or false based o ...

Having difficulty including my JavaScript file located in /app/assets/javascripts when using Rails 4 and "//= require_tree ." in application.js

I'm currently attempting to implement a d3.js graph into my Rails 4 application by following a tutorial found on this website. The example application provided on GitHub works perfectly as expected. The issue I am facing is that when I try to recreat ...