Unable to unfollow using js code

JavaScript Fiddle

In my current project, I am implementing follow and unfollow buttons. The follow functionality is working smoothly, but I'm facing an issue with the unfollow button. When I click on it, it doesn't switch back to follow. You can find the complete code snippet on JsFiddle.

$(".follow").live('click', function(e){
    e.preventDefault();
    $button = $(this);
    if($button.hasClass('unfollow')){

        //$.ajax(); Perform Unfollow

        $button.removeClass('follow');
        $button.removeClass('unfollow');
        $button.text('Follow');
    } 
    else {

        // $.ajax(); Perform Follow

        $button.addClass('follow');
        $button.text('Unfollow');
    } });

Answer №2

In order to toggle both classes, you can use the following simple method:

$button.toggleClass('unfollow').toggleClass('follow');

The button will have either of these classes specified:

<button class="follow">

or

<button class="unfollow">

After the toggle operation, you can set the button text like this:

$button.text($button.hasClass('follow') ? 'follow' : 'unfollow'); 

Don't forget to add listeners for both follow and unfollow classes.

Your complete code should resemble this (notice the use of on()):

 $("body").on('click', ".follow, .unfollow", function(e){
     e.preventDefault();
     $button = $(this); 
     $button.toggleClass('unfollow').toggleClass('follow');
     $button.text($button.hasClass('follow') ? 'follow' : 'unfollow'); 
 });

You can view a working example here: http://jsfiddle.net/ZECEN/110/

Answer №3

If you want to make your code shorter, you can use this snippet:

$(".follow").on('click', function (e) {
    e.preventDefault();
    $(this).toggleClass("Unfollow").text(($(this).text() == 'Follow' ? 'UnFollow' : 'Follow'))
});

Keep in mind that the live() method has been deprecated since version 1.7, so it's recommended to use on() instead.

Check out this Fiddle Demo for a live example!

Answer №4

live() has been deprecated, it is recommended to bind the event directly on the button element.

$('button').click(function() {
    $(this).toggleClass('follow')
           .toggleClass('unfollow')
           .text(function() {
               return $(this).hasClass('follow') ? 'Follow' : 'Unfollow';
            });
});

Check out the demo here.

Answer №5

Check out this demo

 $(".follow").on('click', function (e) {
     e.preventDefault();
     $btn = $(this);
     if ($btn.hasClass('unfollow')) {

         //$.ajax(); Perform Unfollow action

         $btn.addClass('follow'); 
         $btn.removeClass('unfollow');
         $btn.text('Follow');
     } else {

         // $.ajax(); Perform Follow action

         $btn.addClass('unfollow');
         $btn.text('Unfollow');
     }
 });


Consider using .toggleClass()

Demo Link

$btn.text( ($(this).text() == 'Follow' ? 'UnFollow' : 'Follow') ).toggleClass("Unfollow");

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

Sending personalized list attributes through JSON to JavaScript in ASP.NET

Below is a custom list I created for pagination of my results: public class PagedList<T> : List<T> { public int PageIndex { get; set; } public bool HasNextPage { get; set; } // ... } I aim to pass this list via JSON to the View: ...

Having trouble with element.scrollTo not functioning properly on mobile devices?

I have been working on creating a vertical scrolling carousel, and so far everything seems to be functioning well. I can scroll horizontally using buttons and swipe gestures successfully on the simulator. However, when I view the website on a real mobile d ...

Tips on adjusting the size of an HTML canvas specifically for the display

Currently, I am working on an innovative project utilizing HTML5 and canvas: The challenge at hand is to draw on a canvas with dimensions of 2200px/1600px (width/height), display it on my website in a smaller window sized at 600px/400px. However, post cli ...

Battle between Comet and Ajax polling

I'm looking to develop a chat similar to Facebook's chat feature. Using Comet would require more memory to maintain the connection. There seems to be a latency issue when using Ajax polling if requests are sent every 3-4 seconds. Considering t ...

What could be causing Next.js middleware to run repeatedly?

Recently, I set up a brand new Next.js project using npx create-next-app@latest --typescript. Upon completing the installation (version 13.3.4), without making any modifications to existing files, I introduced a new file named middleware.ts within the src ...

What is the proper way to utilize a variable within the translate3d function?

Currently, I am developing my portfolio and working on a function in JavaScript called translate3d(0,10px,0). My question is, how can I use a variable instead of hardcoding the value 10px? I attempted to use translate3d(0,a,0) where 'a' is a vari ...

Bootstrap alert JS refuses to slide down

Here is the JavaScript code to make a blue bar slide down on click: $('#comment').click(function(e) { e.preventDefault(); $('#comment').slideDown(); }); ...

What could be causing my Node application to give a 404 error when making a POST request?

I'm at a loss trying to debug my app for what seems like a simple error, but I just can't locate it. Here is an overview of how my Express app is structured. My routes are set up as follows: var routes = require('./routes'); ... app.g ...

Label for the checkbox is covering other content on the screen in 1024 x 768

Here is the JSP code snippet: <h:field path="configuredChannels" required="true" code="admin.menu.channels"> <div class="row-fluid" data-channel-checkboxes="#"> <form:checkboxes element="div class=&apos ...

Having trouble finding the element during Selenium JavaScript testing

I need help testing a JavaScript script using Selenium, but I am running into an issue. I cannot seem to find a specific element that I want to click on. Here is a snippet of my JS code where I am trying to click on the Shipping option. I have tried us ...

Testing Vue Component with Cypress revealed that the function getActivePinia was triggered without an active Pinia instance

Below are the code snippets I'm working with: Test.vue <template> <button v-show="store.common == 'hi'" @click="func"> hello world </button> </template> <script setup> import {mainS ...

Angular 13 does not currently have support for the experimental syntax 'importMeta' activated

Since upgrading to angular 13, I've encountered an issue while attempting to create a worker in the following manner: new Worker(new URL('../path/to/worker', import.meta.url), {type: 'module'}) This code works as expected with "ng ...

What exactly does the term "new.target" refer to?

The ECMAScript 2015 specification references the term new.target a total of three times - once in section 14.2.3: Although Contains typically does not analyze most function forms, it is specifically used to identify new.target, this, and super usage wit ...

Is it possible to apply several 'where' condition in pg-promise?

I am currently using pg-promise in combination with express 4 on node 8.2.0. I am trying to concatenate the where condition. However, I have been unable to find a way to achieve this. Can you please assist me? This is what I am aiming for. let ids = [10 ...

Where did my HTML5 Canvas Text disappear to?

I am encountering a common issue with my code and could use some guidance. Despite numerous attempts, I can't seem to figure out why it isn't functioning properly. To better illustrate the problem, here is a link to the troublesome code snippet o ...

Unveiling concealed content with JQuery

Here is a link to my pen: http://codepen.io/anon/pen/IszKj I am looking to achieve the functionality where clicking on either "any status" or "any date" will reveal a hidden div containing a list of options. My main query is about the best approach to ta ...

Tips for reading user input in a terminal using node.js

Before deploying my code to the server, I'm looking to conduct some local node testing. How can I take terminal input and use it as an input for my JavaScript script? Is there a specific method like readline that I should be using? ...

Leveraging server.ts for Development with Angular 5 Universal

I decided to give the new Angular Universal Starter a try for my latest Angular 5 project. Instead of providing multiple options, they now only offer the Angular CLI version as a starting point. I've been able to successfully run my project in product ...

Creating evenly spaced PHP-generated divs without utilizing flexbox

My goal is to display images randomly from my image file using PHP, which is working fine. However, I am facing an issue with spacing the images evenly to fill the width of my site. This is how it currently appears: https://i.stack.imgur.com/AzKTK.png I ...

Reading values from a properties file using HTML

Here's a snippet of my HTML code: First name: <input type = "text" > Last name: <input type = "text"> Instead of manually inputting the field values (First name, Last name) in the HTML, I am interested in reading them ...