Ways to implement reclick functionality in a JQuery dropdown

I'm starting my JQuery scripting journey and to test my skills in the basics, I am working on a simple dropdown menu using JQuery. The code is functioning perfectly, but there's a small issue - I want the text to close when I click again on the button that opened it. Here is the code snippet:

$( ".select1" ).click(function() {
  $(".content1").css("display", "block"); 
});

$( ".select2").click(function() {
  $(".content2").css("display", "block");                   

})

$(".select3").click(function() {
  $(".content3").css("display", "block");
})

$(".select4").click(function() {
  $(".content4").css("display", "block");
})
article {
  display: none;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <title>JS Bin</title>
</head>
<body>
<div class="dropdown-wrapper">
  <p class="select1">Select 1</p>
  <article class="content1">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae mollitia aliquid quas doloremque, repudiandae vel odio nisi repellendus accusantium temporibus distinctio labore, debitis tenetur, in assumenda. Odio possimus pariatur, vitae!</article>
  <p class="select2">Select 2</p>
  <article class="content2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas iure, doloribus qui quasi est, quo obcaecati modi ab nesciunt pariatur a id rerum reprehenderit, beatae corrupti consequatur ut placeat ipsa!</article>
  <p class="select3">Select 3</p>
  <article class="content3">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque voluptate beatae placeat nobis porro, id ipsum. Incidunt minima deserunt, delectus. Ad unde obcaecati natus quo excepturi, tempore consectetur odio explicabo.</article>
  <p class="select4">Select 4</p>
  <article class="content4">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil praesentium ex ipsa dolor alias ratione repellat eos? Eveniet architecto officiis, veniam reiciendis animi, enim aperiam error dignissimos expedita laborum eius.</article>
</div>
</body>
</html>

Answer №1

If you want to toggle the visibility of an element, you can achieve that using .toggle() or .toggleClass(). I prefer using .toggleClass() because it allows you to start with the element hidden:

/** Just one line of code using a common selector - class .select in this example **/
$( ".select" ).click(function() {
  $(this).next().toggleClass('visible'); // toggle the class on the next element (the article) when clicked
});
article:not(.visibile) { /** Hide all articles that do not have the class visible **/
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <title>JS Bin</title>
</head>
<body>
<div class="dropdown-wrapper">
  <p class="select">Select 1</p>
  <article class="content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae mollitia aliquid quas doloremque, repudiandae vel odio nisi repellendus accusantium temporibus distinctio labore, debitis tenetur, in assumenda. Odio possimus pariatur, vitae!</article>
  <p class="select">Select 2</p>
  <article class="content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas iure, doloribus qui quasi est, quo obcaecati modi ab nesciunt pariatur a id rerum reprehenderit, beatae corrupti consequatur ut placeat ipsa!</article>
  <p class="select">Select 3</p>
  <article class="content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque voluptate beatae placeat nobis porro, id ipsum. Incidunt minima deserunt, delectus. Ad unde obcaecati natus quo excepturi, tempore consectetur odio explicabo.</article>
  <p class="select">Select 4</p>
  <article class="content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil praesentium ex ipsa dolor alias ratione repellat eos? Eveniet architecto officiis, veniam reiciendis animi, enim aperiam error dignissimos expedita laborum eius.</article>
</div>
</body>
</html>

Answer №2

Your code has been simplified for easier understanding. By using the slideToggle() method, you can easily show or hide the next article on click.

$("p" ).click(function() {
  $(this).next().slideToggle(); 
});

Check it out here

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

Ensuring continuous focus on a textarea

Looking to keep a textarea always focused? Check out these two methods: <textarea id="textarea"></textarea> var textarea = document.getElementById("textarea"); Method 1: textarea.addEventListener("blur", function() { textarea.focus(); ...

The SubMenu icon in Android disappears when creating a menu dynamically

I'm currently working on creating a dynamic menu list, and I've managed to create the menu options successfully. However, every time I run my code, the icon for the main item disappears. Below is a snippet of my code: private static final int SU ...

When the checkbox is unchecked

Is it possible to remove the Checkbox element from the array once it is unchecked? { columns.columnNames && columns.columnNames.map(el => { return ( <div> <input type="c ...

The jQuery attr() method is universally compatible across platforms and stands independent

I have a jQuery statement that is currently working for me, but I am unsure if it is cross-platform independent. Can anyone confirm? $("input[name='confirmed']").attr("checked",false); It is functioning correctly on the latest version of Firefo ...

Using Browserify on files that have already been browserified

When trying to use browserify to require an already browserified module, I am running into an issue where the bundle cannot resolve the module that has already been browserified. For instance, I have a file called bundle-1.js that was bundled using the co ...

Express along with Cheerio and JSDOM

I'm currently exploring the integration of Cheerio with Express to enable server-side DOM manipulation. I haven't had much luck beyond basic web scraping techniques. There are specific requirements I need to meet for this project. Currently, I ...

Display a limited number of characters along with a button on the blog tag pages. Clicking on the button will reveal the complete text description

Hey, I am looking to replicate the way WooCommerce tags descriptions are displayed on my WordPress blog. I want it to show only a certain number of characters with a "show all" link, similar to how it appears on this site: I have found some code that work ...

In search of the HTML code for the forward button when extracting content from a webpage

While using Power Automate Desktop to scrape a webpage, I encountered an issue with clicking the next button. Even after copying the HTML code within the developer tools of the webpage, I found that both the previous and next buttons had the same path, mak ...

Vue fails to receive updates from Firestore until the page is manually refreshed

I set out to develop a task tracker app using Vue. As I neared completion of the project, I encountered an issue - when adding a new task, it would not change the reminder status unless I reloaded the page. Here is the code snippet from my Home.vue file: & ...

Struggling to implement CSS variables across different browsers

I'm struggling to make CSS variables function properly, here is what I have so far: :root { --primary-color: #ffcd600; --spacing: 10px; --blur: 10px; } img { padding: var(--spacing); background: var(--primary-color); } When I check the el ...

Incorporating middleware in Next.js to remove route protection

Looking to remove the protection for the login page, and here is how my folder structure looks: https://i.stack.imgur.com/klPYV.png This is the middleware I am using: import { NextResponse, NextRequest } from "next/server"; export async functi ...

XSL is the key component in creating a unique Custom Slider that remains stationary

I am currently working on a jQuery slider project and I am encountering an issue with getting the images to slide properly. The arrows seem to be functioning as expected, indicating that the necessary classes have been added, but the actual sliding action ...

What could be the reason for my inability to transmit Express response object through SocketIO?

I'm attempting to send the response of an express request by transmitting it to a ws client and awaiting its feedback. This requires sending the res object to the client as I couldn't find an alternative method. This is what I have implemented: ...

I'm having trouble with my Express server routes not being accessed. The browser is displaying an error message saying 'No Data Received ERR_EMPTY_RESPONSE

I've encountered an issue with my express server while setting up an email service. Despite troubleshooting and simplifying the code to a basic 'hello world' example, the problem persists. No routes are functioning properly – requests made ...

Adding a dynamically generated dropdown button: Steps to trigger a delegated event

I am currently using bootstrap 3.3.7 in my project. On a particular page, there is a table with a dropdown button in one of the columns. I am dynamically adding rows to this table, and each new row also contains a dropdown button. However, these added butt ...

What is the best way to end a column early using a media query?

I need some help with adjusting the card layout in my project. I want the cards to break at a specific window size of 700px, but it's not working as expected. Can anyone provide guidance on how to achieve this? Thank you in advance for your assistance ...

Using a JavaScript file within a webpage that has already been loaded

Seeking assistance as I encounter a dilemma: providing code would be overwhelming, but perhaps someone can assist me in brainstorming a solution. Here's the issue: I have an index.php file with a div that dynamically loads (via jQuery .load()) another ...

Exploring the contrasting behaviors of CSS in Codepen and Bootstrap

I am attempting to adjust the text to fit into divs of varying sizes that are responsive due to viewport units. There seems to be an issue: the code below works well in a Codepen, at least for the four examples I have: https://codepen.io/gramm/pen/VJPavg ...

How to dynamically add events to a JQuery FullCalendar using a loop

When utilizing the jQuery full calendar, I need to dynamically set events based on data obtained from a database. To achieve this, I am using data attributes to assign values and then display them on the calendar. Below is an example of my html twig code: ...

function to draw a table row in JavaScript with eloquent and descriptive arguments

I came across this code in chapter 6 of a programming book called "Eloquent JavaScript". I am struggling to understand where the arguments for the function 'drawRow' are coming from. If the outer function drawTable was a method, it would make sen ...