Modify the button's text with jQuery after it has been clicked

I've been struggling to update the text of a button after it's clicked, and I'm encountering an issue where it works in one part of my code but not in another.

Could someone please guide me on what might be missing in my code?

The first block of code is functional, but in the second snippet, the button text doesn't change upon clicking. Any assistance would be greatly appreciated! Below, I have included both sets of code snippets:

$(document).ready(function () {
    $("#fold").click(function () {
        $("#fold_p").fadeOut(function () {
            $("#fold_p").text(($("#fold_p").text() == 'Hide') ? 'Show' : 'Hide').fadeIn();
        })
    })
});
....
</button>

$(document).ready(function () {
    $("#fold").click(function () {
        $("#fold_p").fadeOut(function () {
            $("#fold_p").text(($("#fold_p").text() == 'Hide ') ? 'Show' : 'Hide').fadeIn();
        })
    })
});
<button class="button">
  <div id="fold">
    <span id="fold_p">Hide</span>
  </div>
</button>

Thank you.

Answer №1

If you open the JavaScript console (by pressing F12), you'll notice an error in the second fiddle:

ReferenceError: $ is not defined

This indicates that jQuery was not imported into the second fiddle, hence the absence of the $ variable.

EDIT 2: In summary, I relocated the click event to the button and resolved the inline if issue by eliminating the trailing space in the 'Hide ' string.

EDIT 1: It appears there was also a problem with your JavaScript code, which has been rectified in this snippet:

$(document).ready(function () {
    $("button").click(function () {
        $("#fold_p").fadeOut(function () {                  
            $("#fold_p").text(($("#fold_p").text() == 'Hide') ? 'Show' : 'Hide').fadeIn();
        })
    })
});
.button {
  display: inline-block;
  border-radius: 4px;
  background-color: #f4511e;
  border: none;
  color: #FFFFFF;
  text-align: center;
  font-size: 28px;
  padding: 20px;
  width: 200px;
  transition: all 0.5s;
  cursor: pointer;
  margin: 5px;
}

.button span {
  cursor: pointer;
  display: inline-block;
  position: relative;
  transition: 0.5s;
}

.button span:after {
  content: '\00bb';
  position: absolute;
  opacity: 0;
  top: 0;
  right: -20px;
  transition: 0.5s;
}

.button:hover span {
  padding-right: 25px;
}

.button:hover span:after {
  opacity: 1;
  right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="button">
  <div id="fold">
    <span id="fold_p">Hide</span>
  </div>
</button>

Answer №2

Your java script has encountered an error:

 $("#fold_p").text(($("#fold_p").text() == 'Hide ') ? 'Show' : 'Hide').fadeIn();//there is a space after 'Hide '

The correct code should be:

 $("#fold_p").text(($("#fold_p").text() == 'Hide') ? 'Show' : 'Hide').fadeIn();//no space should be present after 'Hide'

Answer №3

Perhaps it could be structured in this manner:

$(document).ready(function () {
    $("#fold").click(function () {        
        $("#fold_p").fadeOut(function () {
           var btn_text= '';
           if($("#fold_p").text() == 'Hide'){
              btn_text = 'Show';
           }else{
              btn_text = 'Hide';
           }        
           $("#fold_p").text(btn_text).fadeIn();
        })
    })
});
.button {
    display: inline-block;
    border-radius: 4px;
    background-color: #f4511e;
    border: none;
    color: #FFFFFF;
    text-align: center;
    font-size: 28px;
    padding: 20px;
    width: 200px;
    transition: all 0.5s;
    cursor: pointer;
    margin: 5px;
}

.button1 {
    background-color: white;
    color: black;
    border: 2px solid #4CAF50;
}

.button1:hover {
    background-color: #4CAF50;
    color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="fold">
    <button class="button button1">
        <span id="fold_p">Hide</span>
    </button>
</div>

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

The generated hook in vuejs is throwing an error stating that window/localstorage is not defined

My goal is to save an authenticated user to local storage and then load them into Vuex on the next page load. created () { let user = window.localStorage.getItem('user') if(user) { this.setUser(JSON.parse(user)) } } I initia ...

Dealing with POST redirection and retrieving parameters in Next.js

In a typical scenario, browsers send GET requests and servers return pages. However, in my case, I am making requests to a remote server and need to receive responses. The issue is that the server redirects me back to my page via a POST request with some d ...

Executing a class function within the ajax success method

I am attempting to set a variable inside the success callback of an AJAX call. I understand that in order to assign the value, I need to use a callback function. However, I want that function to be within the class. Is it feasible to implement something li ...

Issue with global variable not being properly assigned within the AJAX success function

Check out this snippet of code: I'm currently utilizing the Jamal framework. Event: { getEvents: function(){ var events; $.ajax({ type: "POST", url: anchor("Events/getEvents"), ...

Show only percentages in jqplot graphical representation

Currently, I am in the process of incorporating the jqplot jQuery chart plugin into my Rails application. The example provided by jqplot includes this data: var data = [ ['Heavy Industry', 12],['Retail', 9], ['Light Industry&a ...

Incorporate custom JavaScript files that contain classes within a Vue component

i am encountering an issue with a js file that contains classes with functions. i have a vue component and i want to create an instance of that class within it. (when directly copying the file into my <script> tag, everything works smoothly) myfile. ...

The alignment feature in the center is malfunctioning

I'm currently utilizing jQuery Mobile and have the following HTML along with CSS: .ui-grid-a { padding: 0; margin: 0; margin-top: 15px; height: 380px; } .ui-block-a, .ui-block-b { padding: 0; margin: 0; height: 33.3%; } .ui-block-a a, .ui-block ...

Is it possible to restore the text to its original state?

Currently, I'm working on creating a simple website for server users to order items. However, I've encountered an issue related to the Navigator text. Here is how it currently appears: Upon inspecting the code below, you'll notice that the ...

Employing AJAX, execute a synchronous function asynchronously (Javascript)

Here's a code snippet for the sync function. I've been calling it inside an Ajax, but apparently it's deprecated because it's synchronous. Is there any way to make it run as if it were asynchronous? Or is there a way to convert it into ...

What is the best way to combine HTML and JavaScript code within a single JavaScript file?

Is there a way to include a responsive iframe without any scroll in multiple websites by using just one line of code? I found this snippet that seems promising: <script src="testfile.js"></script> The testfile.js contains the necessary HTML a ...

Utilizing Ajax to dynamically populate table columns

I have an HTML table with specific labels and styles. I am looking for a way to update the table by using the unique 'id' of each row/element and populate the data using Ajax. Can anyone provide a solution or suggestion? <table border="0" ...

Find all Mondays occurring within a specified date range using Moment.js

I need to extract all Mondays within a specific date range. let start = moment(this.absence.FromDate); let end = moment(this.absence.ToDate); The user has the option to deactivate certain weekdays during this period by setting booleans. monday = true; t ...

Setting up global color variables for React with Material UI theming is essential for ensuring consistent and

Is there a way to customize the default material-ui theme using global CSS? Additionally, how can we incorporate HEX values for colors when setting primary and secondary colors in the theme? In my App.js root file, I have defined a custom theme and want t ...

Using an overlay with figure-img in Bootstrap 4 is a visually appealing design

I need assistance with adding an overlay to only the bootstrap 4 figure-img. In order to achieve this, I inserted a div with the class overlay beneath the figure-img. Below is the code snippet: <div class="col-md-4"> <figure class="service tex ...

jQuery UI DatePicker: without any styling, no picking dates

I'm struggling to configure a jQuery UI DatePicker. I moved the development-bundle folder contents to the directory res/jqueryui and initialized two datepickers as shown below: <script src="res/jquery-2.1.0.min.js"></script> <script sr ...

Guide on selecting a <a>class within a table using Selenium for calendar interactions

My current setup involves working with 'Selenium2(WebDriver)' in Eclipse using Java. I'm trying to figure out how to click on a specific date within a table (Calendar). The issue I am facing is that every time I change the month in the cal ...

Center alignment is not being applied to the divs with the Bootstrap class .justify-content-center

I have been attempting to insert a search form into two parent divs. No matter how I apply the align or justify utility, I am unable to center the search bar in the middle of the page as desired. <div class="col"> <div class"con ...

JavaScript comparing elements within an array

I need help extracting all the names from an array with URLs containing '/blekinge' and presenting them in a list. Here's what I have so far: const allLocations = locations.map((location) => <li>{location.url}</li> ) I&a ...

Utilizing a TinyMCE editor within a text area and implementing a posting form through ajax

I am currently using tinyMCE in my textareas and submitting my form through AJAX. However, I am facing an issue where the value in the textarea is not being recorded when I try to save it. This is my text area: <textarea class="form-control" name="cont ...

Manipulate the inner HTML of a ul element by targeting its li and a child elements using JQuery

Here is the HTML code I am working with: <ul class="links main-menu"> <li class="menu-385 active-trail first active"><a class="active" title="" href="/caribootrunk/">HOME</a></li> <li class="menu-386 active"> ...