Steps for concealing a div element upon clicking on it

Is there a way to create an accordion where all the tabs start off closed, but open when clicked and close when clicked again? I have managed to open one tab, but I am struggling to figure out how to close it and how to make the opening and closing process generalizable.

I have created a codepen example to illustrate what I have accomplished so far. Click on the blue div to reveal the hidden paragraph.

<http://codepen.io/anon/pen/qbMBXd>

[Edited: Additionally, when one tab is open and I click on another tab, the first tab should close, leaving only the currently open tab visible]

Answer №1

Revise your javascript code to resemble the following structure

    function adjustSize(x){
    var container = document.getElementById(x);
    if (container.style.height == "50px"){
      switch (container.id){
        case("box1"):
          container.style.height = "auto";
          document.getElementById("box2").style.height = "50px";
          document.getElementById("box3").style.height = "50px";
          document.getElementById("box4").style.height = "50px";
          document.getElementById("box5").style.height = "50px";
          break;
        case ("box2"):
          container.style.height = "auto";
          document.getElementById("box1").style.height = "50px";
          document.getElementById("box3").style.height = "50px";
          document.getElementById("box4").style.height = "50px";
          document.getElementById("box5").style.height = "50px";
          break;
        case ("box3"):
          container.style.height = "auto";
          document.getElementById("box1").style.height = "50px";
          document.getElementById("box2").style.height = "50px";
          document.getElementById("box4").style.height = "50px";
          document.getElementById("box5").style.height = "50px";
          break;
        case ("box4"):
          container.style.height = "auto";
          document.getElementById("box1").style.height = "50px";
          document.getElementById("box3").style.height = "50px";
          document.getElementById("box2").style.height = "50px";
          document.getElementById("box5").style.height = "50px";
          break;
        case ("box5"):
          container.style.height = "auto";
          document.getElementById("box1").style.height = "50px";
          document.getElementById("box3").style.height = "50px";
          document.getElementById("box4").style.height = "50px";
          document.getElementById("box2").style.height = "50px";
          break;


      }
    } else {
     container.style.height = "50px";
     }
   }  

Not the prettiest code but it gets the job done.

You can trigger the function from your HTML when the div is clicked

<div class="colorbox" id="box1" onclick="adjustSize('box1')">

Best of luck

Answer №2

Alright, there are numerous approaches to accomplishing this. Taking inspiration from your codepen example, have you considered the following solution?

    var element = document.getElementById('box1');
    element.addEventListener("click", function() {
      if (document.getElementById("box1").style.height == "auto") {
        document.getElementById("box1").style.height = "50px";
      } else {
        document.getElementById("box1").style.height = "auto";
      }
    });

Answer №3

Give this a shot!:)

.hide > * + *{
  display:none;
}
.hide > *{
  cursor:pointer;
}
.hide:focus{
  outline:none;
}
.hide:focus > * + *{
  display:block; 
}
<div class="hide" tabindex="1">
  <h2>Secret Box</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt ultrices arcu, ut pulvinar risus maximus sed. Quisque dolor nisl, iaculis id sem eget, molestie mollis est. Phasellus scelerisque sagittis ex, nec vestibulum turpis euismod eu. Aliquam aliquet orci et sapien euismod, vitae pellentesque velit porttitor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin rhoncus, felis non elementum ultrices, dui nisl tincidunt risus, sit amet sodales nunc dolor semper lacus. Vivamus egestas lectus id imperdiet pharetra. Nulla non sem elit. Fusce porta velit leo, nec gravida ligula auctor vitae. Sed justo sem, sodales ut imperdiet at, fringilla pharetra neque.</p>
</div>

Answer №4

Here is my second post, hope you find it helpful..:)

$('div.accordion-body').on('shown', function () {
    $(this).parent("div");

});

$('div.accordion-body').on('hidden', function () {
    $(this).parent("div");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet"/>
<body>
    <div class="accordion-group">
        <div class="accordion-heading"><a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#jai">
 <span class="pull-right"></span>
Boxinum
</a>

        </div>
        <div id="jai" class="accordion-body collapse in">
            <div>
                <div class="accordion-inner">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt ultrices arcu, ut pulvinar risus maximus sed. Quisque dolor nisl, iaculis id sem eget, molestie mollis est. Phasellus scelerisque sagittis ex, nec vestibulum turpis euismod eu.
    Aliquam aliquet orci et sapien euismod, vitae pellentesque velit porttitor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin rhoncus, felis non elementum ultrices, dui nisl tincidunt risus, sit amet
    sodales nunc dolor semper lacus.</div>
            </div>
        </div>
    </div>
    <div class="accordion-group">
        <div class="accordion-heading"><a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo">
  <span class="pull-right"></span>
Boxinum
</a>

        </div>
        <div id="collapseTwo" class="accordion-body collapse">
            <div>
                <div class="accordion-inner">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt ultrices arcu, ut pulvinar risus maximus sed. Quisque dolor nisl, iaculis id sem eget, molestie mollis est. Phasellus scelerisque sagittis ex, nec vestibulum turpis euismod eu.</div>
            </div>
        </div>
    </div>
    <div class="accordion-group">
        <div class="accordion-heading"><a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse3">
  <span class="pull-right"></span>
Boxinum
</a>

        </div>
        <div id="collapse3" class="accordion-body collapse">
            <div>
                <div class="accordion-inner">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
            </div>
        </div>
    </div>
</body>

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

Repetition of UTM Parameters

I created a web page with a donation form embedded in it. Donors visiting the page come through a link that includes a source code at the end. I managed to include this source code in the URL of the embedded form using the following code: $(document).ready ...

Locate an item based on the `Contains` criterion by utilizing Express and Mongoose

Looking to find items in my collection that have userName containing adm. Expecting 2 results based on having records with userNames like admin0 and admin2, but the search returns nothing. The query being used is: Person .find({ userName: { $in: &a ...

Customize the yellow background color of Safari's autofill feature by following these simple

When I open this image in Safari, this is what I see: https://i.stack.imgur.com/KbyGP.png However, this is the code I have: https://i.stack.imgur.com/4wEf0.png References: How to Remove WebKit's Banana-Yellow Autofill Background Remove forced ye ...

Using the position property of relative on a DIV element causes a gap to appear between the DIV and the next

Two div elements are placed consecutively. When I move the first div using position: relative and top: -60px, it creates a gap between them. Take a look at this example here: https://codepen.io/dusannis/pen/oNgBpoK If you notice, there is a noticeable ga ...

Animation not properly synced with Bootstrap 4 Dropdown hide event

Could you please check out my codepen for clarification: http://codepen.io/anon/pen/oLZOyp Essentially, I have integrated two animations using animate.css into Bootstrap 4 show.bs.dropdown and hide.bs.dropdown events. The animations work on the first show. ...

Tips for successfully integrating .dae files into three.js for online execution on a web browser

Hey everyone, I'm an HTML developer who has never worked with WEBGL technology before. I've been trying to figure out how to pass a .dae file into 'three.js' by searching through numerous websites, but I haven't been successful. C ...

Tips for incorporating a spinner during content loading within AngularJS

When the user clicks on the "Search" button, content will load and the button label will change to "Searching" with a spinner shown while the content is loading. Once the content has loaded (Promise resolved), the button label will revert back to "Search" ...

AngularJS Interceptors for secure page management

I recently started working with AngularJS and I'm facing an issue with my interceptor that catches 401 errors from server responses. When a 401 status is detected, it triggers a "loginRequired" message broadcast and redirects to the login page. Howev ...

Transform the JSON object into a different JSON format

I am in the process of restructuring the JSON data which is currently organized by categories, with each category containing multiple locations. Each location consists of latitude/longitude coordinates and an area code: { "cat1":[ {"location":{ ...

Automatically trigger a page reload using a jQuery function

Currently facing an issue with jQuery. I created a drop-down menu and would like it to expand when the li tag within the menu is clicked. Even though I am using the jQuery click function successfully, there seems to be a problem where the webpage refreshe ...

Navigating on a stationary object: CSS Styling

I have a main div with another nested div inside. The nested div contains cards, but I am unable to scroll through them due to the fixed positioning of the main div. I need a way to enable scrolling for the cards within the nested div. Note that the presen ...

Effectively implementing an event observer for dynamically loaded content

I want to set up an event listener that triggers when any of the Bootstrap 3 accordions within or potentially within "#myDiv" are activated. This snippet works: $('#myDiv').on('shown.bs.collapse', function () { //code here }); Howeve ...

Can HTML be transferred between browser tabs using Angular?

I'm in the process of developing a unique Angular (v17) application that allows users to drag and drop HTML elements, even across multiple browser tabs. I am inspired by the capabilities demonstrated by neo.mjs, as shown in this demo: https://www.yout ...

Error: Attempted to call $scope.map.control.getGMap function when clicking on the Map, but it is not defined

I'm currently working with Angular-Google-MAP and I'm trying to add a marker to the map. However, whenever I click on the map, I receive an error message saying $scope.map.control.getGMap is not a function. This error is occurring within the geoc ...

The function form.parse() in node.js is always overlooked

I'm having an issue where form.parse() is never called. When I delete bodyparser, my session variable throws an error. How can I resolve this and make it work? logcat The write(string, encoding, offset, length) method is deprecated. Use write(st ...

What steps can be taken to resolve this issue?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ut ...

Reorganizing an array using a custom prioritized list

Is it possible to sort an array but override precedence for certain words by placing them at the end using a place_last_lookup array? input_place_last_lookup = ["not","in"]; input_array = [ "good", "in", "all&qu ...

Show SVG in its ViewBox dimensions

Currently, I am utilizing the img-Tag to showcase SVG images that have been uploaded by users onto my Amazon S3 storage. <img src="http://testbucket.s3.amazonaws.com/mysvg.svg" /> An issue arises once the image is displayed as it does not retain i ...

Discover the steps to implement a live user list in a chat application with the help of angular.js, socket.io, and node

Currently, I am in the process of developing a chat application with AngularJS and Socket.io. The current status of my project allows users to send and receive messages from different individuals. To gain access to the chatbox, users need to input their na ...

The function crypto.randomUUID() does not exist in the Vitest library

vite.config.ts import { sveltekit } from '@sveltejs/kit/vite'; const config = { plugins: [sveltekit()], test: { include: ['**/*.spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], environment: 'jsdom', glo ...