Using JavaScript in Wordpress to specifically select and follow the user that was just clicked on

I have implemented the "User Follow System" plugin on my website. I need help in modifying the JavaScript code to select only one user when the current user clicks on the follow button.

Currently, I am displaying a list of followers and following users using the get_users function within a foreach loop.

The issue I'm encountering is that when I click on the follow link for one user, the loading images for all users appear and all the follow links toggle. The code responsible for this behavior is

$(‘.follow-links a’).toggle();

Upon reaching out to the plugin owner for assistance, they suggested adjusting the selector used in the JS to target only the clicked user. Originally, the plugin was designed to display only one user's links on the page.

Despite the advice, I haven't been successful in resolving the issue!

jQuery(document).ready(function($) {
    /*******************************
    follow / unfollow a user
    *******************************/
    $( '.follow-links a' ).on('click', function(e) {
        e.preventDefault();

        var $this = $(this);

        if( pwuf_vars.logged_in != 'undefined' && pwuf_vars.logged_in != 'true' ) {
            alert( pwuf_vars.login_required );
            return;
        }

        var data      = {
            action:    $this.hasClass('follow') ? 'follow' : 'unfollow',
            user_id:   $this.data('user-id'),
            follow_id: $this.data('follow-id'),
            nonce:     pwuf_vars.nonce
        };

        $('img.pwuf-ajax').show();

        $.post( pwuf_vars.ajaxurl, data, function(response) {
            if( response == 'success' ) {
                $('.follow-links a').toggle();
            } else {
                alert( pwuf_vars.processing_error );
            }
            $('img.pwuf-ajax').hide();
        } );
    });
});

display-function.php

<?php
/**
 * Retrieves the follow / unfollow links
 *
 * @access      public
 * @since       1.0
 * @param       int $user_id - the ID of the user to display follow / unfollow links for
 * @return      string
 */

function pwuf_get_follow_unfollow_links( $follow_id = null ) {

    global $user_ID;

    if( empty( $follow_id ) )
        return;

    if( ! is_user_logged_in() )
        return;

    if ( $follow_id == $user_ID )
        return;

    ob_start(); ?>
    <div class="follow-links">
        <?php if ( pwuf_is_following( $user_ID, $follow_id ) ) { ?>
            <span><a href="#" class="unfollow followed" data-user-id="<?php echo $user_ID; ?>" data-follow-id="<?php echo $follow_id; ?>"><span>Following</a></span>
            <a href="#" class="follow" style="display:none;" data-user-id="<?php echo $user_ID; ?>" data-follow-id="<?php echo $follow_id; ?>">Follow</a>
        <?php } else { ?>
            <a href="#" class="follow" data-user-id="<?php echo $user_ID; ?>" data-follow-id="<?php echo $follow_id; ?>">Follow</a>
            <span><a href="#" class="followed unfollow" style="display:none;" data-user-id="<?php echo $user_ID; ?>" data-follow-id="<?php echo $follow_id; ?>"><span>Following</a></span>
        <?php } ?>
        <img src="<?php echo PWUF_FOLLOW_URL; ?>/images/loading.svg" class="pwuf-ajax" style="display:none;"/>
    </div>
    <?php
    return ob_get_clean();
}

Answer №1

By not specifying a single child in the query selector, the line $('.follow-links a').toggle() is toggling all follow links found. This causes the toggle method to be applied to each child.

To fix this issue, simply use $this.toggle() instead of $('.follow-links a').toggle().

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

Tips for eliminating unnecessary data in written content

Could anyone provide a recommended method for removing unnecessary symbols from text strings? For instance, transforming "CWC%20-%20Maint%20Eng%20-%20El" into the more readable format of "CWC - Maint Eng - El". ...

How do I retrieve the value of a class that is repeated multiple times?

In the HTML code I am working with, there are values structured like this: <div class="item" onClick="getcoordinates()"> <div class="coordinate"> 0.1, 0.3 </div> </div> <div class="item" onClick="getcoordinates() ...

Inserting a variable into a JSON string

Within my code, I have a basic variable containing strings that are converted into a JSON object. My goal is to create an input field where a person's name can be entered and added to the text. The current setup looks like this var text = '{"st ...

The list attribute in AngularJS seems to be malfunctioning when used in Internet Explorer 11

My current issue involves using the 'find' method within a scope. While it works perfectly fine in Chrome, there seems to be compatibility issues with Internet Explorer 11. How can I resolve this and make it work smoothly on IE 11? $scope.NameLi ...

Building a Node.js view to display an OpenLayers map

I'm new to working with node.js and am currently trying to incorporate an OpenLayers map onto a webpage. However, I'm facing an issue where the map is not displaying as expected. Code: app.js var express = require('express'); var ap ...

"Enhance Your Website with a WordPress Plugin: The Sticky News Footer

Currently seeking a plugin that can smoothly scroll text, preferably from posts, located at the end of the page in a sticky footer format. I am going for a news-style appearance with clickable links included. In the past, I utilized the Ditty News Ticker ...

Puzzled by the unexpected error I encountered while using Node.js (require.js)

My script was running smoothly until I encountered a sudden error: undefined:3 <!DOCTYPE html> ^ SyntaxError: Unexpected token < at Object.parse (native) at Request._callback (C:\Users\Tom\Pictures&bso ...

What steps can I take to expand this on a grander level?

I have a code snippet for a personality quiz, but I'm facing an issue with increasing its size. Here's the HTML code: <h3>1. What is your favorite color?</h3> <input type="radio" name="q1" value="A" /> A. Red. <input type="r ...

The gem 'remotipart' does not display any server errors in Rails 4

Currently, I have included the 'remotipart' gem in my Gemfile like this: gem 'remotipart' This is defined in my form view new.html.erb <%=form_for @user, remote: true, html: { multipart: true, class: 'user-form' } do |f| ...

Ember - connecting to a JSON data source

Recently, I have been following a tutorial/example from codeschool and everything is going well. However, the example code includes the line: App.ApplicationAdapter = DS.FixtureAdapter.extend(); Now, I want to maintain all the existing functionality but ...

JS Issues with generating accurate dates in JS/JS Date perplexities

Creating a custom datepicker has been a challenging task for me. I'm facing difficulties in understanding how JS Date works and need some assistance to bridge this knowledge gap. The issue arises when I attempt to generate dates using a for loop, resu ...

Change the HTML table's toggle element to either 'on' or 'off' based on the specified value using jQuery

I am looking to modify the appearance of an HTML/CSS/jQuery toggle element based on the value of a cell within a table, either displaying "YES" or "NO". The required functionality includes: If the text in the table cell is "yes", the toggle element sh ...

Ways to conceal the label without using JavaScript when focusing

I am trying to find a way to hide the label "phone number" when the input is in focus by simply clicking on it. I have attempted using CSS but I need a more effective solution. Please let me know if you can help. <div class="form-row"> ...

Tips for receiving feedback when uploading multiple images

I've been facing challenges with receiving a response when uploading multiple images using the API. Despite getting a valid response when uploading a single image, I'm not getting the expected response for multiple uploads. Below is my code: fil ...

Plotting data with both line and nested plot in d3

My plot graph has the correct color scheme, but I need to connect each plot with lines. There are two groups of plots that need to be nested into separate line groups. I'm unsure how to proceed with this task. <!DOCTYPE html> <html> < ...

The angular event broadcaster controller is currently unavailable

In my app, there is a search box and a list of results. The search box is controlled by SearchCtrl, while the list of results is managed by DocListCtrl. When a user submits a query, SearchCtrl emits an event that DocListCtrl listens for in order to update ...

In React-router, I aim to transmit the location of a Link to a Route

When setting the Link in a child component like this: <Link className="article-link" to={`/newsarticle/${title}`}> I expect the Route to reflect that in the App.js component: <Route path=`/newsarticle/${title}` component={NewsPage}/> The pu ...

eslint alert: The aria-current attribute must have a value that is a single token from the following list: page, step, location, date, time, true

<div role="button" tabIndex="0" className="nav-link pad-0-r" aria-current={'${selectedTab === item ? 'page' : 'false'}'} onClick={()=> onClick(item)} onKeyDown= ...

Sequentially run jQuery functions

function functionOne() { $('#search-city-form').trigger('click'); } function functionTwo() { $("form input[name='tariffId']").val("137"); $('#search-city-form').trigger('click'); } function funct ...

Refreshing a component using a sibling component in React

Currently, I am delving into the realm of React and embarking on a journey to create a ToDo App. However, I've hit a snag while attempting to add a new task to the list. Despite successfully adding an item to the list upon clicking the add button, upd ...