Show / Hide content by clicking another div

I need help figuring out how to create a collapsible div that expands and collapses when a different div is clicked. The expanding/collapsing effect that I've been experimenting with is similar to what I want, but I'm not sure how to modify the code to make it work the way I need it to.

For example, I want to be able to click on a div in a sidebar and have another div below the header expand or collapse, pushing all content below it downwards. The div that expands and collapses could contain a search bar that the user can show or hide by clicking a button in the sidebar.

$(".sidebar-div").click(function () {

    $sidebar = $(this);
    //getting the corresponding content element
    $content = $sidebar.next();
    //open up the content needed - toggle the slide- if visible, slide up, if not slide down.
    $content.slideToggle(500, function () {
        //change text of sidebar button based on visibility of content div
        $sidebar.text(function () {
            //change text based on condition
            return $content.is(":visible") ? "Collapse" : "Expand";
        });
    });

});
.container {
    width:100%;
    border:1px solid #d3d3d3;
}
.container div {
    width:100%;
}
.container .header {
    background-color:#d3d3d3;
    padding: 2px;
    cursor: pointer;
    font-weight: bold;
}
.container .content {
    display: none;
    padding : 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div class="container">
    <div class="header"><span>Expand</span>

    </div>
    <div class="content">
        <ul>
            <li>Here goes the content inside the collapsible div.</li>
            
        </ul>
    </div>
</div>

Answer №1

$(".header").click(function() {
  $('.content').slideToggle().toggleClass('active');
  if ($('.content').hasClass('active')) {
    $('.header span').text('Collapse');
  } else {
    $('.header span').text('Expand');
  }
});
$('button').click(function(){
$(".header").trigger('click');
})
.container {
    width:100%;
    border:1px solid #d3d3d3;
}
.container div {
    width:100%;
}
.container .header {
    background-color:#d3d3d3;
    padding: 2px;
    cursor: pointer;
    font-weight: bold;
}
.container .content {
    display: none;
    padding : 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div class="container">
    <div class="header"><span>Expand</span>

    </div>
    <div class="content">
        <ul>
            <li>Adding a search bar here.</li>
            
        </ul>
    </div>
</div>
  <button>another click</button>

Answer №2

$(".toggle").click(function () {

    
    //grabbing the content 
    $content = $(".content")
    //expand the content - toggle the slide- if visible, slide up, if not slidedown.
    $content.slideToggle(500, function () {
        //perform this after slideToggle is complete
        //modify text of header depending on visibility of content div
        $header.text(function () {
            //adjust text based on condition
            return $content.is(":visible") ? "Collapse" : "Expand";
        });
    });

});
.container {
    width:100%;
    border:1px solid #d3d3d3;
}
.container div {
    width:100%;
}
.container .header {
    background-color:#d3d3d3;
    padding: 2px;
    cursor: pointer;
    font-weight: bold;
}
.container .content {
    display: none;
    padding : 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div class="container">
    <div class="header"><span>Expand</span>

    </div>
    <div class="content">
        <ul>
            <li>I'm placing a search bar here.</li>
            
        </ul>
    </div>
<div class="toggle">click me</dov>
</div>

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

Switching React Icons when Clicked

I'm struggling to understand this. I want the React icons below to be filled and remain filled when clicked, changing back to outlined when another is clicked. Here's the code: import { useState } from "react"; import { Link } from "react-router- ...

Sending emails with SMTP in JavaScript using the mailto form

I'm facing a challenge with my form. I am looking for a way to have the Send-email button trigger mailto without opening an email client, instead automatically sending via JavaScript (smtp). I'm not sure if this is achievable or if I'm askin ...

Quirks and nuances when using p5's pixel fill function

I am currently utilizing the p5.js library to work on a program that is designed to automatically fill closed spaces. However, I am encountering an issue where the program sometimes fills half-closed loops for reasons unknown to me. If anyone could provide ...

Enable hovering only on the actual content within the box, not on the empty space

Currently, I am working on creating a navigation bar using flexbox. Everything seems to be functioning correctly except for one issue: when I hover over the space between my logo and the navigation links, it changes the color of my logo to the hover state ...

What is the best way to incorporate a mongoose model into another model?

I have two different models that I am working with. In the user model, I want to include an array of Requests, and in the Request Model, I want to have User as an attribute (without including the password). How can I achieve this? var userSchema = new S ...

Creating seamless shading effects using three.js with Blender integration

When I import a Blender scene into a three.js environment, the curved faces appear flat. Is there a method to ensure that these surfaces remain smooth as intended? Despite calculating vertex normals and activating the smoothShaded option, the issue persis ...

Utilizing Angular JS to Manage Controller Events

I am currently working on an application that requires saving a large amount of data in cascade, similar to a typical master-detail view. Within this view, there is a "Save All" Button which saves each row in an iteration. This process triggers jQuery cus ...

AngularJS - Custom directive to extract a property value from an object

Currently, I am using the following for loop to retrieve the parent category: angular.forEach(queryTicketCategories, function(category) { if(category.id === $scope.ticketCategory.parentId) { $scope.parent = category; } }); I am looking fo ...

issue with deploying a software package and getting it installed

I developed a basic package containing only a simple <div> x </div> and published it using npm publish. When I attempted to install it in a project using npm i, I encountered the following error message: Support for the experimental syntax &apo ...

Endless loop issue in Reactjs encountered when utilizing React Hooks

Delving into React Hooks as a newcomer, I encountered an error that has me stumped. The console points to an infinite loop in the code but I can't pinpoint the exact line responsible. Too many re-renders. React limits the number of renders to prevent ...

Error: Bootstrap/CSS not functioning properly on IE and ED browsers

Currently, I am tackling a web application project, and much to my surprise, I discovered that the CSS/bootstrap is not functioning properly on Internet Explorer and Microsoft Edge. Despite attempting various solutions found on Stack Overflow, none seem to ...

Retrieve the overall number of job openings from the Github Job API

I have successfully created an Angular application that mirrors the functionality of However, I encountered a limitation where only 50 positions are available per page, To fetch additional jobs beyond the initial 50, I need to append "?page=X" to another ...

Using the Slim framework to communicate through JSON

When attempting a simple POST request, I am having trouble reading the JSON data no matter what I try. $.ajax({ url: 'server/account/session', type: 'POST', data: { "username": name, "password": password} , ...

Navigate up to the ancestor element before moving back to the previous two sibling elements using Xpath

Here is an example of HTML code: <span class="state"> <label class="state button start" ...>"Start"</label> </span> <span class="name tracker_markup"> <span class="labels pre ...

What exactly does "blocking and tackling" refer to in the Angular2 documentation?

As I delved into the online documentation for angular2, I stumbled upon a puzzling term - "blocking and tackling" in the ADVANCED - Angular Module chapter (https://angular.io/docs/ts/latest/guide/ngmodule.html). ... "It's all just basic blocking and t ...

AngularJS- issue with button visibility on 'toolbar' widget

In my angularJS application, there is a page with multiple widgets displayed. When a user clicks on the 'Settings' button on the page (separate from the widgets), a toolbar for each widget appears showing different buttons depending on the widget ...

Obtaining table data and HTML elements using the correct code - Selenium and Python

I've been attempting to extract the ticker symbol, stock name, price, sector, and market cap columns from this website. I'm facing challenges in identifying the correct HTML elements using the appropriate code. Although I've used Selector Ga ...

Difficulty displaying images on an HTML canvas

Currently, I have a function named next that is designed to retrieve the time (just the hours) and then compare the hours using an if statement to determine which clock image to load into the imageURLs[] array. Based on my observations, this part seems t ...

Flexslider optimized for mobile devices

I am currently using the Sparkling theme on a Wordpress website. This particular theme utilizes Flexslider within a div at the top of the page. Each slide featured in the slider includes an image, as well as a div containing a post title and excerpt. The ...

Design a layout consisting of a grid with items that maintain a set maximum width while being evenly distributed across the entire width of the device

I'm trying to create a grid with 2 rows and 3 columns, each cell having an image with a max-width of 512px. I added margin to the grid but now the cells are larger than the content. How can I achieve the same visual appearance as flexbox's justif ...