The show/hide toggle button is malfunctioning and not functioning properly

I'm still learning jQuery and I attempted to create a show/hide toggle button without relying on jQuery's toggle function. However, I can't seem to identify the issue in the code below.

Although the Hide button successfully hides the paragraph, the 'hide' functionality is working correctly. The class "show" is added while the class "hide" is removed, changing the button text accordingly. Upon inspecting with Dev Tools, this part seems to be functioning as expected. Yet, clicking the button again to show the paragraph doesn't work i.e the 'show' aspect.

$(document).ready(function() {
  $(".hide").click(function() {
    $(".content").hide();
    $(this).addClass("show");
    $(this).removeClass("hide");
    $(this).text("Show");
  });
  $(".show").click(function() {
    $(".content").show();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

<p class="content">If you click on the "Hide" button, I will disappear.</p>
<button class="hide">Hide</button>

Answer №1

To easily change the visibility of an element with a single button, you can use the toggle() method. Additionally, you can update the text on the button based on its current value by using the text() function. Give this a try:

$(document).ready(function() {
  $(".toggle").click(function() {
    $(".content").toggle();
    $(this).text(function(i, t) {
      return t == 'Show' ? 'Hide' : 'Show';
    })
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

<p class="content">If you click on the "Hide" button, I will disappear.</p>
<button class="toggle">Hide</button>

If you prefer not to use toggle(), another option is to utilize toggleClass() to toggle the presence of the hide class. Here's how you can achieve that:

$(document).ready(function() {
  $(".toggle").click(function() {
    $(".content").toggleClass('hide');
    $(this).text(function(i, t) {
      return t == 'Show' ? 'Hide' : 'Show';
    })
  });
});
.hide {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

<p class="content">If you click on the "Hide" button, I will disappear.</p>
<button class="toggle">Hide</button>

Answer №2

It is advisable not to change the class directly. If you do need to make changes, consider delegating the event to a static container like the document.

$(document).on("click",".hide",function() {

I recommend using the toggle function instead:

$(document).ready(function() {
  $(".but").on("click",function() {
    $(".content").toggle();
    $(this).text($(this).text()=="Show"?"Hide":"Show");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

<p class="content">If you click on the "Hide" button, I will disappear.</p>
<button class="but">Hide</button>

Alternatively, without using toggle:

$(document).ready(function() {
  $(document).on("click",".hide",function() {
    $(".content").hide();
    $(this).text("Show")
      .removeClass("hide")
      .addClass("show");
  });
  $(document).on("click",".show",function() {
    $(".content").show();
    $(this).text("Hide")
      .removeClass("show")
      .addClass("hide");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

<p class="content">If you click on the "Hide" button, I will disappear.</p>
<button class="hide">Hide</button>

Answer №3

When you change the class name of an element from 'show' to 'hide', it essentially removes it from the DOM in terms of event handling. The click event will only work if the element is present when the DOM is first created.

To ensure that the button click event triggers even after changing the class name, you need to use the on() function to assign the click event and place it on the parent container of the triggering element. In the code below, I have applied the on() method to the document object so that all elements with classes .hide or .show inherit these click events, including new dynamically created elements.

<p class="content">If you click on the "Hide" button, I will disappear.</p>
<button class="hide">Hide</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

<script>
    $(document).on('click', ".show", function(){
        $(".content").show();
        $(this).addClass("hide");
        $(this).removeClass("show");
        $(this).text("Hide");
    });
    $(document).on('click', ".hide", function(){
        $(".content").hide();
        $(this).addClass("show");
        $(this).removeClass("hide");
        $(this).text("Show");
    });
</script>

It's also recommended to utilize the toggleClass() method as suggested by @mplungjan for better optimization.

For more information on the on() function in jQuery, refer to the official documentation here.

Answer №4

$("#toggle-content").click(function() {
  $(".hidden-content").toggle();
  if($(this).text() === "Hide") {
    $(this).text("Show");
  } else {
    $(this).text("Hide");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

<p class="hidden-content">Click the button to toggle me on and off.</p>
<button id="toggle-content">Hide</button>

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

Issue with AngularJS directive: Isolated scope preventing values from being inserted into template

After setting up the directive below: angular.module('news.directives', []) .directive('newsArticle', function($location, $timeout) { return { restrict: 'AE', replace: 'true&apo ...

Is it possible to align a CSS table row with its corresponding table header even when the table row is deeply nested within the table structure?

I am looking to keep the structure of my HTML code consistent and unaltered. However, this has resulted in a form tag being nested inside a table row before the table cells can begin. The information I need to display is tabulated data, which makes CSS t ...

Issue with CSS3 calc() validation: Invalid value provided for width, resulting in a parse error

Can you help me validate a CSS3 file that contains the following code snippet? width:calc(96.3% - 312px) When I try to validate it, I get this error message: Value Error : width Parse Error - 312px) My solution might be to implement a JavaScript func ...

Unable to upload images on Phonegap ios using formdata

I am facing an issue with image upload in my Phonegap application for iOS. The image upload is not working at times and I am unsure of the exact reason behind this. I am using FormData to upload the image as shown below: <input id="uploadImage" type="f ...

Exploring Node.js Express: Understanding the Difference Between Modules and Middleware

I am working on an express rest api and need to create a PDF document with a link to download it. I have successfully generated the PDF, but now I want to create a route specifically for returning the PDF link. In addition, I also need other routes that ...

Exploring Arabic text patterns with regex and jQuery

Looking to extract Arabic numbers along with the parentheses using regex? Check out this link for a solution: http://jsfiddle.net/QL4Kr/. <span> كهيعص ﴿١﴾ </span> <span> وَإِلَيْهِ تُرْ‌جَعُونَ ...

Exploring a JavaScript object's array

Greetings, I am looking to develop a simple visual editor for my plugins. let x = { tag : "a", atts : { href : "/", class : "a", text:"link" }, com ...

Is it possible to pass a mongoDB object to all prototype functions in JavaScript/Node.js?

I am currently facing challenges while working with NodeJS and MongoDB. I am struggling to pass the mongoDB object between prototype functions within my code. Can someone provide guidance on how to effectively pass this object between prototypes? In the m ...

What mechanism does angularjs employ to detect the $dirty state in the absence of a form tag?

I have implemented $window.addEventListener('beforeunload' to detect changes on a page successfully. Additionally, I am using $transitions.onStart... to monitor navigation with the browser buttons. I find it puzzling though, as my HTML template l ...

displaying a collection of images from a designated tag on a flickr gallery

Hello, I need some help with my flickr gallery. I want to load only the first two pictures from a specific tag defined in a 'data-category' attribute into a div named 'gallery'. Here is my HTML: <div data-category="clouds ...

Is there a way to find the TextArea element on Facebook's home page using a Selenium locator? Could it possibly be using jQuery

Sign in using any of our Facebook login details. Upon successful login, you will be directed to the page below. Query: Can you spot the "What's on your mind" or "continue to post" text box? I need to find the text box, input text, and then click on ...

Incorporating external json information into an HTML form

How do I go about loading an external JSON file? Please note: External files may be blocked by server settings. Populate forms using local JSON <form id="datas-from-json"> <div class="form-group"> <labe ...

The attribute 'checked' is not a valid property for the 'TElement' type

Learning about typescript is new to me. I have a functional prototype in fiddle, where there are no errors if I use this code. http://jsfiddle.net/61ufvtpj/2/ But in typescript, when I utilize this line - if(this.checked){ it presents an error [ts] Pro ...

Refresh Entity with Real-Time Data on Cesium

I have been attempting to showcase an entity moving within Cesium through the use of live/dynamic data. After trying various techniques and consulting past forums, particularly those from 2015-2016, I am still struggling to make it work. Despite my effort ...

Updating JSON data using fetch API

Hi everyone, I'm currently working on an email application and need help with implementing an archive button for each email. It seems that the function to change the archived status to true is being called, but for some reason, it's not making th ...

What is the best way to choose distinct items from a Promise<Array[]> in Angular 2/4?

Providing some context, I am working with an API that fetches information about a competition including links to matches, and each match has links to the teams involved. My current goal is to create a standings table based on the matches of the competitio ...

Upcoming: Error in syntax: Unexpected character encountered, expected a "}"

Inserted a Google Tag Manager script into a .jsx file in the following format: <!-- Google Tag Manager --> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getE ...

Determine if a mobile application has been installed using Vue.js

I am currently developing a web application and have implemented a check to determine whether the user is accessing it from a mobile device or laptop. Let's consider the link as: my-site.com In addition to the web version, my site also offers a mobi ...

Struggling to execute a basic Typescript file

I recently embarked on a journey to learn Typescript by enrolling in this specific course. The process of setting up everything seemed simple enough. I created a new directory, executed the command npm init, and followed it up with npm install --save-dev t ...

The React component does not trigger a re-render

Using React Redux, I am able to pass values successfully. However, the component I intend to render only does so once. Interestingly, when I save my code in VSCode, it renders again and the data displays on the page as expected. return ( <div classN ...