Toggle the visibility of an element with a single button click

Below is a snippet of my sample code:

SAMPLE HTML CODE:

<ul>
  <li class="item"> item 1 </li>
  <li class="item"> item 1 </li>
  <li class="item"> item 1 </li>
  <li class="item"> item 1 </li>
  <li class="item hidden"> item 1 </li>
  <li class="item hidden"> item 1 </li>
</ul>
<button class="button">Show/Hide element</button>

SAMPLE CSS CODE:

.hidden {
  display: none;
}
.visible {
  display: block;
}

SAMPLE JS CODE:

$('.button').on('click', function (e) {
  var item = $('.item');
  item.removeClass('hidden'); 
});

I am looking to assign the class .visible to elements that previously had the .hidden class. Essentially, I aim to hide these items again when clicked, creating a toggling effect of classes.

How can I hide the last two items?

Appreciate any guidance on this matter!

Answer №1

To achieve this effect, make sure to implement the .toggle() method.

 $('.button').on('click', function (e) {
      $('.hidden').toggle('visible'); 
});

Answer №2

Here is a simple solution that doesn't require any CSS, just use the .toggle() function in jQuery.

$('.button').on('click', function (e) {
  $('.hidden').toggle(); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="item"> item 1 </li>
  <li class="item"> item 1 </li>
  <li class="item"> item 1 </li>
  <li class="item"> item 1 </li>
  <li class="item hidden"> item 1 </li>
  <li class="item hidden"> item 1 </li>
</ul>
<button class="button">Show/Hide element</button>

Answer №3

You have another option available to you as well:

Cascading Style Sheets (CSS)

.hidden {
  display: none;
}

JavaScript with JQuery

$('.button').on('click', function (e) {
      $('#anyElement').toggleClass('hidden');
});

Answer №5

If you prefer, you have the option to iterate through each element when a button is clicked and toggle the relevant classes.

$("button").click(function(){
     $("li").each(function(){
         let $this = $(this);
         if($this.hasClass('hidden')){
       $this.removeClass("hidden").addClass("visible");
         } else if($this.hasClass('visible')){
       $this.removeClass("visible").addClass("hidden");
         }
      })
})
.hidden {
  display: none;
}
.visible {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="item"> item 1 </li>
  <li class="item"> item 1 </li>
  <li class="item"> item 1 </li>
  <li class="item"> item 1 </li>
  <li class="item hidden"> item 1 </li>
  <li class="item hidden"> item 1 </li>
</ul>
<button class="button">Show/Hide element</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

How to center an HTML header

Currently working on a one-page scrollable website, aiming to have the first page consist of a navbar, image, and header. The challenge I'm facing is centered around aligning the header vertically. Although I managed to center it horizontally, the ver ...

Using jQuery to attach events and trigger them

Within my code, I have the following scenarios: $("#searchbar").trigger("onOptionsApplied"); And in another part of the code: $("#searchbar").bind("onOptionsApplied", function () { alert("fdafds"); }); Despite executing the bind() before the trigge ...

When utilizing express-formidable to retrieve multipart data, it causes basic post requests with request body to hang indefinitely

app.js const express = require('express') const app = express() const appInstance = express() const PORT = process.env.SERVER_PORT || 8080 app.use(express.json()) app.use(express.urlencoded({ extended : true })) app.use(formidableMiddleware ...

Modify a section of an HTML text's formatting

function changeEveryCharColor(id) { var part; var whole = ""; var cool1 = document.getElementById(id).innerHTML; console.log(cool1); for(var i = 0; i < cool1.length; i++) { color1 = getRandomInt(255); ...

The custom layout in NestJS version 13 failed to display

I have implemented NextJs 13 in my project for building purposes. I am trying to use CustomLayout as the primary layout for my entire website. Even though there are no errors, I am facing an issue where the CustomLayout does not display as expected. ...

To begin, formulating a blank state entity containing a collection of key-value pairs with JSON objects as the values. Subsequently, modifying the contents of

I am working on setting up a reactJS state with an empty array to start. When I receive a message in the form of a JSON object, I want to add a key-value pair to the array, using the received message as the value and a specified key. For example: We have ...

"Implementing JavaScript Validation for Textboxes: A Step-by-Step Guide

I need some help with restricting the input of a textbox within a gridview to only 'X' or 'O'. I am not very familiar with javascript, so any guidance on how to accomplish this would be greatly appreciated. It's worth noting that t ...

What steps can I take to ensure that the submenu remains visible for users to make their selection?

I'm currently working on implementing a drop-down sub-menu next to the navigation bar located in the center of the image. I have uploaded an image of a transparent box (representing the background of the sub-menu) and used the following codes: When h ...

Automatically switch tabs upon pressing/scanning the Return key (using PHP, MySQL, and JavaScript)

Seeking assistance to resolve an ongoing issue that has been troubling me for the past few weeks. I am maintaining a basic web-based database to keep track of product serial numbers leaving our warehouse. The system is secure behind our firewall, so I&apo ...

Comment sections that refresh automatically after being posted

I am determined to provide a clear explanation. Despite having some code, I am uncertain about how to make it clone comments and add new ones with user inputted text. Below is the snippet of code I am struggling with: <!DOCTYPE html> <!-- this i ...

What is the procedure for altering a particular element using ajax technology?

I have an AJAX request that updates the user information. I need to retrieve a specific value from the response and update the content of a specific element. For example, here is the element that needs to be changed: <div id="changeMe"><!-- New ...

Having trouble releasing the package on npm platform

I'm facing difficulties in publishing a public package to npm. Despite creating an organization, I'm unable to figure out how to add a new package. Any assistance on this matter would be greatly appreciated. ...

An in-depth guide on implementing debounce functionality for `keyup` events in Vue.js

I am attempting to detect when the user begins typing and stops typing using the debounce function. I experimented with Lodash and Underscore.js. On my textArea v-on:keyup="handler($event)" handler: function(e) { ...

Puppeteer: Eliminate hyperlinks on webpage

I am currently using Node.js and Puppeteer to convert a webpage into a .pdf-file. Everything functions as expected, however, I need assistance in removing all the links on the page before converting it to a .pdf. This is necessary because the resulting .p ...

What is the best method to iterate through a jQuery array variable without any errors?

I am struggling with a PHP project where I need to create a json array of data values that will be used in a jQuery script. The array looks something like this: [3,94,83,141]. My goal is to leverage these values to manipulate the visibility of rows in a ta ...

What Makes Sports Illustrated's Gallery Pages Load So Quickly?

After thoroughly examining their code, I'm still puzzled. Are they loading complete new pages, or are they utilizing jQuery to modify the browser's URL while keeping most of the page unchanged? I'm currently inspecting the source of this pa ...

react-basic-photo-carousel: adjust size and dimensions

As a newcomer to React JS, I decided to use react-simple-image-slider for my image slider component. However, I am facing an issue with making the images responsive on mobile devices. I tried setting the width and height using vw, vh or percentage units, ...

Having trouble deleting element despite having the correct ID?

Whenever I click on the map, it adds an element to the map div using this line of code: $('#map').append('<label>test:</label><input type="hidden" name="map_coords" id="' + e.latlng.lat + '" value="' + e.latlng ...

Guide for redirecting puppeteers' attention to a new pop-up interface

Currently, I am utilizing Puppeteer to carry out a test on a website. Upon clicking a button, a new popup browser window emerges displaying a report. Inside this new window lies data that I wish to extract. Is there a method for Puppeteer to switch its foc ...

Is there another way to retrieve a marketplace's product details using code?

When it comes to scraping products from various websites, I have discovered a clever method using window.runParams.data in the Chrome console. This allows me to easily access all the information without having to go through countless clicks to extract it f ...