Tips for changing between two texts within a button when clicked

Seeking a solution for toggling between two different texts inside a button when making an ajax call, with only one text displayed at a time.

I'm facing difficulty in targeting the spans within the button specifically. Using 'this' as context always refers to a single span.

My idea was to add a class to one of the spans after the ajax call is complete to hide it?

HTML

<button type="button" class="main-button" data-url={unfollowUrl}>
  <span class="text1">Text 1</span>
  <span class="text2">Text 2</span>
</button>

CSS

button {
  border: none;
  background-color: red;
  width: 100px;
  height: 50px;
}

button .hide-text {
  display: none;
}

JS

$('button').click(function{
  $.ajax({
    url: url,
    method: 'POST'
  }).done(function() {
    //toggling goes here

})
}

jsfiddle: https://jsfiddle.net/5rk99y6y/

Answer №1

HTML:

<button type="button" class="main-button" data-url={followUrl}>
  <span class="content1">Content 1</span>
  <span class="content2 hide-content">Content 2</span>
</button>

JS:

$('button').on('click', function() {

    $current = $(this);
    $.ajax({
        url: 'http://example.com/',
        method: 'POST'
    }).done(function() {
        $current.children('span').toggleClass('hide-content');
    });

});

CSS:

.hide-content {
  display: none;
}

Answer №2

Check out this link for a live demo: https://jsfiddle.net/5rk99y6y/1/

UPDATE: https://jsfiddle.net/5rk99y6y/26/

To customize the text inside a button, simply modify the content of the span element within the button and make any necessary updates:

HTML:

<button type="button" class="main-button" data-url={unfollowUrl}>
  <span>Text 1</span>
</button>

JS:

$('button').click(function(){
  var btn = $(this);
  var url = "/";
    $.ajax({
        url: url,
        method: 'POST'
      }).done(function() {
        var span = btn.find('span'),
            txt = span.text() ;
        if (txt == "Text 1") {
            span.text("Text 2");
        } else {
            span.text("Text 1");
        }
    });
});

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

Organizing Parsed JSON Data with JavaScript: Using the _.each function for Sorting

var Scriptures = JSON.parse( fs.readFileSync(scriptures.json, 'utf8') ); _.each(Scriptures, function (s, Scripture) { return Scripture; }); This code extracts and displays the names of each book from a collection of scriptures (e.g., Genesis, ...

Using an external script to modify or call a Vue.js method

My Vue app is constructed using Webpack and includes a few basic computed properties, such as calculating the sum amount from input values. However, I now require the capability to replace the summation function with one stored in a separate file that is n ...

Instructions for transferring files directly from one website to another

Looking at the PHP code snippet provided: <?php $image_cdn = "http://ddragon.leagueoflegends.com/cdn/4.2.6/img/champion/"; $championsJson = "http://ddragon.leagueoflegends.com/cdn/4.2.6/data/en_GB/champion.json"; $ch = curl_init();` $timeout = 0; cur ...

What could the possible reason behind the malfunctioning of my prepared statements for the insert operation?

I recently discovered that using prepared statements is a more effective method than using deprecated ones. Despite my best efforts and online tutorials, I haven't had any luck getting this to work or finding the problem. That's why I'm her ...

Show an item in a visual format of a list

Need help displaying a specific object: cars: { number': 1, 'overload': 1,'brand': {'0': {'porsche': [{'price': 10, 'id': 0}],'vw': [{'price': 20, 'id': 1}] ...

Achieving Text Centering in kableExtra Cells with CSS: A Step-by-Step Guide

Recently, I received a helpful solution that involved using the extra_css = argument in cell_spec() from the kableExtra package. This allowed me to fill the entire cell of my table instead of just the text inside it. However, even after specifying align = ...

Personalize the pagination or other elements of Splide in a Svelte component to suit your needs

I am currently integrating Splide into my Svelte application and facing an issue with the pagination styling. The pagination is appearing on top of my images and is too transparent for my liking. I'm utilizing Svelte Splide to incorporate this library ...

Activate simultaneous HTML5 videos on iOS devices with a simple click

I am currently in the process of developing a webpage that will play various videos when specific elements are clicked. Although the functionality works perfectly on desktop computers, it encounters an issue on iOS devices. The problem arises when the elem ...

Ensure that the table is padded while keeping the cells collapsed

I am currently working on creating a table with borders between each row. However, I am facing an issue where the row borders are touching the outer border of the table. Despite my efforts, I have been unable to find a solution to this problem. I feel like ...

Is it possible for an AngularJS directive to compile a fresh element that has a second directive assigned to it?

UPDATE: All directives listed below will now require ng-model bindings to be applied in the elements they generate, targeting the controller assigned to the page. The code has been modified to reflect this. I am exploring the creation of dynamic HTML usin ...

Utilizing HTML in Grails messages.properties for email delivery: A beginner's guide

When working with Grails, I have implemented a GSP template to generate an HTML email using the mail plug-in. Everything functions properly, except for one issue - the GSP template utilizes a parameter that is retrieved from my messages.properties file. I ...

Failure to connect HTML and CSS files

My HTML and CSS files are not linking even though they are in the same folder. Here is my HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatibl ...

Animate the coloring process with dynamic motion

Is there a way to dynamically fill a canvas with color and apply animation? I have successfully created a canvas cylinder that fills with color, but I'm hoping for a slow animation effect when the color is filled. I've tried searching on Google ...

To ensure a successful redirection process without information loss, it is essential to address any potential issues with data input into

How can I properly implement a page redirection? Below are the relevant code snippets. <link rel="stylesheet" type="text/css" href="payout.css"/> <font face='calibri'> <?php session_start(); $conn = @mysql_connect("localho ...

What is the most effective method to prevent the auto-complete drop-down from repeating the same value multiple times?

My search form utilizes AJAX to query the database for similar results as the user types, displaying them in a datalist. However, I encountered an issue where it would keep appending matches that had already been found. For example: User types: "d" Datali ...

What could be causing wavesurferjs to exceed the boundaries of its parent div?

I need assistance with my wavesurferjs issue The waveform is overflowing the parent div This problem occurs for the first time and upon resize of the parent div Upon resizing, it should automatically adjust to fit the parent div Question: When the pare ...

Analyzing the performance differences between HTML5 and Flash applications

Recently, I created both an HTML5 app and a Flash app for research purposes. Now, I am looking for a reliable method, possibly in the form of software, to efficiently test and compare the performance of these systems. ...

Make the text area occupy the full width of the remaining screen space

I've been struggling to make the text area fill the remaining width of the screen. Everything is set up nicely, but I just can't seem to find a solution to get it to expand and occupy the rest of the available space. I intentionally refrained fr ...

Ways to move the scroll to the bottom of the div by clicking

Can anyone help with why my scroll code isn't working? I'm trying to make the scroll go to the bottom when I click on $('#openDiv'). For example, when you enter a chat room on stackoverflow, the scroll is automatically at the bottom, a ...

Vue-bootstrap spinbutton form with customizable parameters

I am in need of a custom formatter function for the b-form-spinbutton component that depends on my data. I want to pass an extra argument to the :formatter-fn property in the code snippet below, but it is not working as expected. <b-form-spinbutton :for ...