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

What is the proper location to place the CSS I wish to implement for a module?

As I embark on creating my inaugural DotNetNuke website, I find myself faced with the task of adding an HTML module to a page. To style the text within it, I have been advised to utilize CSS classes. I'm curious about where .css files should be place ...

What could be the reason for the lack of definition of the `pieceOfText

My latest project involves a fun guessing game centered around decrypting text, but I've hit a snag with a variable in my JavaScript code. This variable, known as pieceOfText, should be assigned a random piece of text from an array containing 3 encode ...

Issues with Bootstrap Navbar Dropdown functionality, including flickering or unresponsiveness

While working on a project, I incorporated the FlexStart Bootstrap Template. However, I encountered an issue with the Dropdown feature on the navbar. When hovering over the menu and submenu, they flicker incessantly. Despite investing a considerable amount ...

I am facing an issue with the Ionic Framework where the Javascript function for JWPlayer only works after the page is reloaded. Can anyone help

I'm currently troubleshooting the use of JWPlayer for streaming videos in an Ionic app. However, I've encountered a problem. The player only seems to load when I refresh the page, rather than when I navigate through the list of videos. Here is ...

Why isn't the content of the initial tab in a <section> shown when clicking a link in the side-drawer?

View the JSFiddle here. Within this MCVC, a side drawer is implemented (opened by clicking the top left button) that contains three labeled links: Link One, Link Two, and Link Three. Each link has an href attribute value that starts with "#" concatenated ...

The controller in Angular uses the $scope symbol _

App.controller('todoController', function ($scope) { // create a message to display in our view $scope.todos = [{ name: 'angular', done: false }]; $scope.clearTodo = function () { $scope.todos = _.filter($scope.tod ...

The qTip comment box vanishes when focused on by IE/Edge browsers using touch devices

A unique JavaScript library called qTip is being utilized in my project. The application includes a StarRating and Comments feature, both of which are enabled by this plugin. After selecting a rating using the stars, users have the option to add comments, ...

ng-required is ineffective when used with number inputs that have a minimum value requirement

In my form, I have implemented a checkbox that, when checked, toggles the visibility of a div using AngularJS's ng-show. Within this div, there is an input field of type "number" with a validation setting of min="10000". I am trying to prevent the f ...

The Ajax request returned empty data

Is there a problem with retrieving data based on user selection from a drop-down menu in an MVC 5 controller? I am able to capture the selected value, but when passing it to the controller, the data appears to be null. Any suggestions or solutions? jQuery ...

What causes the width of unrelated cells to change when the contents of colspan'd cells expand in IE7?

Before we delve into the details, I invite you to take a look at this fiddle using IE7. It's quite intricate and not something I want to repeat here. The main issue is that clicking on the red block should display additional information. The top row ...

Is there a way to align the navigation menu options to the right side of the navbar?

I'm having trouble aligning the options in the navbar to the right side. Can anyone help me identify where I'm going wrong in my code? Here is the snippet I'm working with: <div> <nav class="navbar navbar-expand-lg navb ...

Is there a way to change OTF/TTF file formats into EOT?

Is there a simpler way to convert my OTF/TTF fonts to EOT format for Microsoft browsers' @font-face feature? I attempted using the WEFT tool but without success. Any alternative methods available? ...

Deleting an element from an array stored in local storage with the help of jQuery

Summary: Developing a front-end wish list feature Tech Stack: Utilizing HTML5 (localStorage), CSS, and jQuery Key Features: Ability to add and delete items dynamically with real-time count display Challenge: Issue encountered when trying to remove added ...

The jQuery dropdown menu smoothly expands to reveal all hidden submenu options

I'm currently encountering an issue with jQuery. I am trying to create a responsive drop-down menu with sub-menus. The behavior I want is that if the window width is less than 700px, the submenus will trigger onClick. And if the window is wider than 7 ...

Place a Button or Link Right Below the Title on the Custom Post Type Editing Page

I am currently working on customizing the backend of a WordPress site for a client by adding multiple custom post types. These custom posts are only meant to be displayed on the front-end through a specific loop on one page, preventing users from accessing ...

What could be causing a hydration error when utilizing a table in Next.js?

When attempting to use the tr tag in my code, I encountered an error message that reads: Unhandled Runtime Error Error: Hydration failed because the initial UI does not match what was rendered on the server. import React from 'react' import {useS ...

Utilizing Vue CLI's sourcemaps to pinpoint the styling within a Vue component file

Currently, I am working on a Vue CLI project. After setting up the project and making some development changes, my package.json file now includes: package.json "dependencies": { "bootstrap": "^4.3.1", "core-js": "^3.0.1", "preload-it": "^1.2. ...

Classic ASP encountering issue with accessing data from Ajax call

I am having trouble retrieving data from a classic ASP file that is sent from a jQuery AJAX call. Below is the AJAX call I am making: $.ajax({ type: "GET", url: "mymessage.asp?phone=" + $( "#mobile1" ).val() + "&message=" + $('textarea#m ...

What is the correct way to align labels to the right in a column layout?

I just started learning React JS and I'm using Material-UI. One issue I encountered is that when I use the column layout with an 'xs' value, the component inside the column appears aligned to the left. To align it to the right, I tried incr ...

Consecutive AJAX requests triggered by previous response

While there are numerous resources available regarding making synchronous AJAX calls using deferred promises, my specific issue presents a unique challenge. The process I am attempting to facilitate is as follows: Initiate an AJAX call. If the response i ...