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

Avoiding unlimited re-renders when using useEffect() in React - Tips and Strategies

As a new developer, I recently built a chat application using socket io. In my code, I have the useEffect hook set to only change when the socket changes. However, I also have setMessage within the body of useEffect(), with socket as a dependency. Unfortun ...

Updating Rails record using Ajax with select_tag and onchange functionality

I'm working on an index view where I want to update a table data dynamically using select_tag onchange feature without the need to refresh the page. Do I need to use Coffeescript to detect the onchange event, capture the new value, and then send it to ...

Transitioning from Event-driven Object Oriented design to Redux structure

I currently have a structure that is mostly object-oriented and I am considering migrating to React/Redux due to handling issues with events. I have various modules with objects structured like this: User { getName() getSurname() etc... } These obj ...

Selecting an entire row in a Kendo grid

Is there a way to configure kendoGrid to highlight the entire row when clicked on? I have tried setting: scrollable: { virtual: true } and disabled paging, but it doesn't seem to work as intended. You can view an example here: Kendo UI Dojo When ...

issues with jquery progress bar not updating value

How can I display two progress bars with the same value specified in the data attribute? Here is the HTML code: <div> <div class="p" data-value="54"></div> </div> <div> <div class="p" data-value="45"></div> < ...

The message "jest command not recognized" appears

My test file looks like this: (I am using create-react-app) import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Calculator'; import { getAction, getResult } from './actions/' ...

The dimensions of text that wraps itself around multiple lines are distinct from those of text that remains on a single line

Hello everyone, I need some assistance with setting up my WordPress blog. I have integrated both Facebook and native WordPress comments on my website: . My aim is to make the formatting of the WordPress comments resemble that of Facebook comments as closel ...

The act of coming back with just one array

I'm having trouble grasping the concept of returning a single array from a function that calls another function multiple times. The issue I'm facing is that each time the scrapingfunction runs, the console.log in the code provided outputs an arra ...

Receiving an unanticipated value from an array

Actions speak louder than words; I prefer to demonstrate with code: //global variable var siblings = []; var rand = new Date().getTime(); siblings.push('uin_' + rand); alert(siblings['uin_' + rand]); // undefined Why is it coming up ...

Troubleshooting: Issue with Ajax Post Request in Django Version 1.10.5

For the past week, I've been facing difficulties in successfully executing a jQuery ajax request to transfer data from a JavaScript function within my annualgoals.html file to a Django view for database storage. Currently, I'm just trying to veri ...

Make sure two elements are siblings in JavaScript / jQuery

Looking at the HTML structure below: <div class="wrap"> <div id="a"></div> <div id="b"></div> </div> A statement is presented as false: ($('#a').parent() == $('#b').parent()); //=> false ...

What causes "this" to exhibit distinct behavior from the selected name?

Although I'm still getting the hang of using jquery, I've been experimenting with it for a few weeks now. So please bear with me if my question seems basic to you. Recently, I put together a jquery script that seems to be working well. <scri ...

Sharing environment variables between a React app and an Express.js server that hosts it as a static site can be achieved by setting

My static site react app is hosted under an express server project in a folder called client/build. The oauth redirect uris point to the express server for token retrieval. The react app redirects users to the oauth endpoint, which is also referenced by th ...

Struggling with getting the JavaScript, scss, and CSS television animation to turn on and off properly? Seeking assistance to troubleshoot this

After finding this javascript code on Codepen and seeing that it worked perfectly in the console there, I tried to run it on my computer with jQuery but it didn't work outside of Codepen. Even when attempting to use it on JSfiddle or compile the SCSS ...

Upon reloading the page, the Vue getter may sometimes retrieve an undefined value

My blog contains various posts. Clicking on a preview will direct you to the post page. Within the post page, I utilize a getter function to display the correct post (using the find method to return object.name which matches the object in the array). cons ...

Angular 2: Implementing a Universal CSS Style Sheet

Is there a way to include a universal CSS file in Angular 2 applications? Currently, I have multiple components that share the same button styling, but each component has its own CSS file containing the styles. This setup makes it difficult to make changes ...

Placing a materialUI circular progress bar on top of the circular icon

I'm striving to add a circular progress bar that surrounds a circular icon with a visible space between the two elements, just as depicted in the image below. Although I successfully positioned the circular progress bar around the icon, creating adequ ...

Using TypeScript, apply an event to every element within an array of elements through iteration

I have written the code snippet below, however I am encountering an issue where every element alerts the index of the last iteration. For instance, if there are 24 items in the elements array, each element will alert "Changed row 23" on change. I underst ...

Trouble with Material-UI Textfield Hinttext Functionality

When designing a textfield according to job requirements, I encountered an issue. After assigning a background color to the TextField, the hintText disappeared. To resolve this, I had to manually set the z-index of the label. Now, the hintText is visible, ...

Application unable to save data to file with no indication in error logs

Recently, I've been experimenting with the Capture-Website package, which is designed to save website screenshots to a file. Initially, everything was working smoothly until I decided to restart the server. Now, although my code is running without a ...