JavaScript Subscribe / Unsubscribe Button

I am trying to create a simple JavaScript program that allows users to like and dislike content. However, I am new to JavaScript and finding it a bit challenging. Basically, when the user clicks on the Follow button, the "countF" variable should increase by 1 and the button text should change to "Unfollow". It's a basic program but I'm struggling with making it work in reverse. In other words, when the Unfollow button is clicked, the "countF" should decrease by 1 and the button text should revert back to "Follow". I know it sounds simple, but I just can't seem to figure it out. Any help or ideas on how to complete this task?

var countF = 0;
var btnText = "Unfollow";
var countButton = document.getElementById("followButton");
var displayCount = document.getElementById("followers");
countButton.onclick = function() {
countF++;
followers.innerHTML = countF;
var countButton = document.getElementById("followButton");
countButton.innerHTML = btnText;
if(countButton.innerHTML = btnText) {
countF--;
countButton.innerHTML = "Follow";
}
}
<div id="followers">0</div>
<button id="followButton"></button>

Answer №1

If you're looking to improve your understanding of voting systems, I recommend checking out this informative tutorial video: https://www.youtube.com/watch?v=mBPURBO1kD8. Remember, when it comes to implementing a voting system, client-side handling is not enough.

Here's a suggested concept that may be useful:

let likedPost = false

function toggleVote() {
    likedPost ? removeUpvote() : addUpvote()
    likedPost = !likedPost
}

function removeUpvote() {
    //code for removing
    //may require server calls
}

function addUpvote() {
    //code for adding
    //may require server calls
}

Answer №2

Here is a sample code snippet that demonstrates how this can be achieved:

let followerCount = 0;
let followButton = document.getElementById("btnFollow");
let displayFollowers = document.getElementById("followerCount");

followButton.onclick = function() {
  if (followButton.innerText === "Follow") {
    followerCount++;
    followButton.innerText = "Unfollow";
  } else if (followButton.innerText === "Unfollow") {
    followerCount--;
    followButton.innerText = "Follow";
  }
  displayFollowers.innerHTML = followerCount;
}

Make sure to include the following text in your button element:

<button id="btnFollow">Follow</button>

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

Dividing an array into categories with typescript/javascript

Here is the initial structure I have: products = [ { 'id': 1 'name: 'test' }, { 'id': 2 'name: 'test' }, { 'id' ...

Display endless data within a set window size

I am looking to create a fixed-size window for displaying text from the component <Message/>. If the text is longer, I want it to be scrollable within the fixed window size. See screenshot below: Screenshot export default function AllMessages(){ ...

Is there a way to convert datetime format to date in a Vue component?

With my Vue component set up like this: <template> ... <td>{{getDate(item.created_at)}}</td> ... </template> <script> export default { ... methods: { getDate(datetime) { ...

Runtime Error: Invalid source property detected - Firebase and Next.js collaboration issue

Currently, I am developing a Next.js application that retrieves data from a Firestore database. The database connection has been successfully established, and the data is populating the app. However, I am facing an issue with displaying the image {marketpl ...

Build a custom Angular2 pipe to convert JSON data into an array through iteration

I am attempting to take the JSON data provided below and convert it into an array for use with *ngFor='let item of items', which will allow me to display data as item.name, etc... This is what I have tried: var out = []; for(var key1 in object) ...

Talebook: Unable to modify UI theming color

As I embark on creating my own theme in Storybook, I am closely following the guidelines outlined here: Currently, I have copied the necessary files from the website and everything seems to be working fine. However, I am facing an issue when trying to cus ...

Can someone explain the inner workings of the Typescript property decorator?

I was recently exploring Typescript property decorators, and I encountered some unexpected behavior in the following code: function dec(hasRole: boolean) { return function (target: any, propertyName: string) { let val = target[propertyName]; ...

Guide on attaching an onclick function to a search bar

I found a search bar code on this website and I want to enhance it by adding a function that redirects users to a URL when they click on the search icon. Here is the existing code: <svg xmlns="http://www.w3.org/2000/svg" style="display:none"> ...

Vue application encountering issues with the functionality of the split method in Javascript

Hey there! I am just starting out with JS and Vue. Currently, I have a Vue application that pulls date information from an open API. The tricky part is that the API response includes both the date and time in one string (for example: 2019-10-15T09:17:11.80 ...

Assign the output of a function to a variable

I am trying to retrieve data from a function call in nodejs and assign it to a variable. The desired output should be "Calling From Glasgow to Euston", but I'm currently getting "Calling From undefined to undefined". Here is the code snippet: functi ...

Creating Vue3 Component Instances Dynamically with a Button Click

Working with Vue2 was a breeze: <template> <button :class="type"><slot /></button> </template> <script> export default { name: 'Button', props: [ 'type' ], } </scr ...

The method JSON.stringify is not properly converting the entire object to a string

JSON.stringify(this.workout) is not properly stringifying the entire object. The workout variable is an instance of the Workout class, defined as follows: export class Workout { id: string; name: string; exercises: Exercise[]; routine: Ro ...

Dealing with a divided image in a separate thread: What you need to know

I am facing a challenge with incorporating a LARGE image into a website, which is affecting performance. My solution is to divide the image into smaller pieces and stitch them together using a grid upon loading. The only issue is that it must be in the ba ...

Deviations in Scriptaculous Callbacks during Movement Effects

I am looking to create a dynamic menu item that moves out 5px on mouseover and returns to its original position using Scriptaculous. I have implemented the afterFinish callback to ensure that the bump-out effect is completed before the item moves back in. ...

What is the process for transferring image attributes to the server via a URL?

My data transmission process only involves sending data. Below is the data I send: export const cabin = { name: '001', maxCapacity: 2, regularPrice: 250, discount: 0, image: './cabins/cabin-001.jpg', description: ...

What is the best way to incorporate multiple pages into a Node JS and Express application?

After completing a tutorial on Node JS for RPI (https://www.youtube.com/watch?v=QdHvS0D1zAI), I encountered an issue when trying to add multiple websites to my web app. While everything works fine locally on localhost:5000/page2, once I make the app public ...

Pass data to all routes in ExpressJS

After logging in, I am setting req.session variables as follows: req.session.loggedin = true req.session.firstname = loginDetails.firstName; I would like to streamline this process and pass this information to ALL routes without manually adding them to ea ...

"Customize your text alignment with TinyMCE's align

I'm in the process of updating from an outdated version of TinyMCE to the most recent release. In the old TinyMCE, if you inserted an image and aligned it to the left, the HTML generated looked like this: < img src="testing.jpg" align="left" > ...

Implement a grid layout for columns within the profile section

Each user on my website has a profile tab that displays their submitted posts. To showcase these posts, I utilize the following code: <?php while ($ultimatemember->shortcodes->loop->have_posts()) { $ultimatemember->shortcodes->loop-> ...

Generating an Array of objects through the use of the each method

Currently, I am in the process of developing a web scraper using node.js along with puppeteer and cheerio. Although I can successfully display the desired strings in the console.log, I am facing challenges in determining if this task is achievable. $(&apo ...