How do I use jQuery to make a div appear when the previous one closes?

I've been experimenting with some code and it's gotten pretty lengthy. It works fine with just a few divs, but what if I need to implement this on 20 or more...?

Is there a way to condense the code I've written?

(I'm still new to jquery and trying to create complex functions.)

Can anyone offer assistance?

You can view the fiddle here: http://jsfiddle.net/Ud574/27/

The code is shown below.

      $(document).ready(function(){

      $('.button').click(function() {
      $('.content').hide(500)
  $('.headOne').addClass("classRight");
 $('.content1').show(500)
 });
     $('.button1').click(function() {
     $('.content1').hide(500)
 $('.headTwo').addClass("classRight");
 $('.content2').show(500)
 });

 $('.button2').click(function() {

     $('.content2').hide(500)
 $('.headThree').addClass("classRight");
 $('.content3').show(500)
 });
 $('.button3').click(function() {

     $('.content3').hide(500)
 $('.headFour').addClass("classRight");

    $('.buttonLast').click(function() {
    $('.content').show(500)
 $('.headOne,.headTwo,.headThree, .headFour').removeClass("classRight");});
});

   });

       <doctype html>
        <html>
        <head>
        <title> div collapse</title>
        </head>
        <body>


   <div class="headOne"> Employee personal record</div>
   <div class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum bibendum <br />
    <div class="button">Click me</div> 
   <br />
   </div>
  <div  class="headTwo"> Employee personal record</div>
   <div class="content1">Pellentesque felis elit, tempor vitae dapibus facilisis, sollicitudin id diam.  <br />
  <br />
  <div class="button1">Click me</div>
  </div>
  <div  class="headThree"> Employee personal record</div>
  <div class="content2">Aliquam  id lectus pellentesque viverra<div class="button2">Click me</div></div> 
   <div  class="headFour"> Employee personal record</div>
   <div class="content3">Aliquam a magna ac lacus eget porta. Maecenas viverra mi id lectus pellentesque viverra</div>
  <div class="button3">Click me</div><br />
 <br />
  <div class="button4">Go To Previous section </div></div>


  <div class="buttonLast">Go To Previous section </div>




    </body>
  </html>

Answer №1

It appears that what you're looking for is a solution similar to the Accordion control.

You might find the jQuery UI Accordion tool useful. Here's where you can check it out: http://jqueryui.com/accordion/

Do you think this could be a suitable option for your needs?

Answer №2

I made some adjustments to your code and streamlined it by utilizing jQuery's built-in functions. Check out the updated HTML below:

    <div class="closable"> Employee profile
<div class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum bibendum ullamcorper convallis.
</div></div>
<div  class="closable"> Employee profile
<div class="content">Pellentesque felis elit, tempor vitae dapibus felis eu erat. <br />
</div></div>
<div  class="closable"> Employee profile
<div class="content">Aliquam eget porta. Maecenas viverra mi id lectus pellentesque viverra</div></div> 
<div  class="closable"> Employee profile
<div class="content">Aliquam a magna ac justo accumsan porttitor.</div></div>
<div class="button4">Go To Previous section </div></div>

Here's the JavaScript snippet I added:

$(document).ready(function(){
$('.content').first().show();
$('.closable').click(function() {
if ($(this).find('div').first().is(':visible')){
    $(this).find('div').first().hide();
    $(this).next().find('div').first().show();
}else{
    $(this).find('div').first().show();
}
});

Hope this revised version works better for you!

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

Manipulating the DOM using Vue.js and jQuery can significantly improve the

I'm seeking advice on how to handle a situation where I need direct access to DOM elements while using VUE.JS. Currently, I am using the Fomantic-UI framework (a fork of Semantic UI) and it takes around 100ms (?) for an element to be created, making i ...

URGENT Inquiry - How does jQuery insert the DOM Element SPAN for tag suggestions?

Check out this awesome plugin at: ** it's super compact Source: I've been trying to pinpoint where in the plugin JS file the code is placing the SPAN element that contains the tags... There seems to be something related around line 73: var t ...

Submission handling with JQuery forms is not functioning

Currently troubleshooting my jQuery contact form submission handler. For some reason, the code isn't working as expected and I'm not sure where the issue lies. Upon form submission, there should be a success or error alert displayed, but nothing ...

Applying a gradient overlay to an image using CSS

Feeling a bit frustrated with this issue. I'm working on my Joomla website utilizing Phoca Gallery, and the code it generates includes the following: <img class="pg-image" src="/images/phocagallery/other/thumbs/phoca_thumb_m_something.jpg" alt="So ...

Steps to create a thumbnail image following the insertion of an image into an input type="file" within a form, and subsequently submitting both elements on the form together

Currently, I am working on a form that enables users to upload images. Once the user submits the form, my goal is to create thumbnails for each image on the front-end and save them on the server afterwards. Due to security restrictions, changing the value ...

Adjust link when scrolling through the webpage

I am looking to update the URL while scrolling instead of changing the menu class. Here's the reference I found: https://codepen.io/anon/pen/LdLgNo I made some modifications by adding push state, but I'm facing an issue with a fixed header. I ...

Including extra js files disrupts the jQuery IntelliSense functionality

After enjoying the benefits of jQuery IntelliSense in VS2008, I decided to add a reference to jQuery UI. However, upon doing so, I noticed that the jQuery IntelliSense disappeared. It seems that referencing another .js file in the document causes this is ...

Tips for arranging a group of objects based on a nested key within each object

i have a collection of objects that I need to sort based on their id. here is the information: { 1918: { id: "1544596802835", item_id: "1918", label: "Soft Touch Salt Free Mint 500 ml (000001400045)", combo_items: false } 6325: { ...

Restricting the input field in jQuery to only accept the maximum value based on the

There are two input fields: discountType and discountAmount. My goal is to set restrictions based on the value of discountType: if it's percentage, the discountAmount input should only accept numbers between 0 and 100; if it's absolute, any numbe ...

Guide to updating the date format using ReactJS hooks

I am facing a challenge with formatting dates in my project. I need to convert the date format from mm/dd/yyyy to dd/mm/yyyy. If this is not possible, what other options do I have? I want to avoid using jQuery in my React Project if possible. <input ty ...

Transforming PHP MySQL date into a Javascript timestamp for plotting time series data with FLOT

Currently, I am in the process of developing a Flot JavaScript Time Series Line Graph that analyzes the registration activity of users over time. The graph depicts the number of users registering accounts against the timestamp of when the account was creat ...

Incorporating dynamic content changes for enhanced user experience can be achieved more effectively with AngularJS

I am utilizing a REST service to retrieve information for a banner. The goal is to dynamically update the slider on the main page using this data. Currently, I am using $http.get to fetch the data, and then implementing interpolation with additional ng-if ...

Once a unique email address has been created, I aim to reuse it for future correspondence

Issue: During the application process, I encounter a dilemma when prompted to input an email address and confirm it in a separate text field. To automate this task, I rely on webdriverJS for coding. My approach involves generating a random email address u ...

Guide on creating a fluid line in Three.js by connecting two points while clicking the mouse, using buffer geometry

Looking for assistance with drawing dynamic lines on mouse events in a threejs webgl canvas using buffergeometry and raycasting. Any help would be greatly appreciated! ...

Stop the slideshow when hovering

I have successfully implemented a script for running a slideshow. The script works well and does the job perfectly. jQuery(document).ready(function ($) { setInterval(function () { moveRight(); }, 5000); var slideCount = $('#slider ul li' ...

React is currently in the process of downloading images that were not fetched during

(Update: Initially, I suspected React Router was the cause of this issue. However, after eliminating React Router from the codebase, the problem persists. Therefore, I have extensively revised this inquiry.) Situation: I am dealing with paginated pages th ...

Is it possible to reset only certain data values in Vue without re-initializing the entire set?

In the development process, we often encounter the need to re-initialize data structures. One common method is as follows: function initialData() { return { is_active: true, is_collapsed: true, resetable_data: 'value' ...

Intercommunication of variables among components

My scenario involves two components, namely App and SomeComponent. I'm aiming to access a variable in App from SomeComponent. App: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css& ...

Click on a link to open it in the current tab with customized headers

In my Angular project, I am attempting to open a link by clicking a button that redirects to the specified URL using the following code: window.open(MY_LINK, "_self"); However, in this scenario, I also need to include an access token in the header when t ...

Color Your Plone Website with a Custom JavaScript Colorscheme

Currently, I have implemented a custom theme by registering the javascript in the skin.xml file and then creating a specific folder within the browser to store the script. Below is the script shared by one of the users: $(document).ready(function(){ ...