Learn how to toggle the visibility of three div elements arranged horizontally

$(document).ready(function () {
    $("#toggle").click(function () {
        if ($(this).data('name') == 'show') {
            $("#sidebar").animate({
                width: '10%'
            }).hide()
            $("#map").animate({
                width: '89%'
            });
            $(this).data('name', 'hide')
        } else {
            $("#sidebar").animate({
                width: '29%'
            }).show()
            $("#map").animate({
                width: '70%'
            });
            $(this).data('name', 'show')
        }
    });
});
html, body {
    width:100%;
    height: 100%;
}
#header {
    width: 100%;
    height: 20%;
    float: left;
    border: 1px solid;
}
#map {
    width: 80%;
    height: 80%;
    float: left;
    border: 1px solid;
}
#sidebar {
    width: 19%;
    height: 80%;
    float: left;
    border: 1px solid;
}
#toggle {
    width: 10%;
    height: 40%;
    margin-right: 6.5%;
    margin-top: 3.5%;
    float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">HEADER
    <input type="button" data-name="show" value="Toggle" id="toggle">
</div>
<div id="map">MAP</div>
<div id="sidebar">SIDEBAR</div>

I am just starting out with angularjs, jquery, and css. I'd like to arrange three divs with a toggle side by side. Can anyone provide guidance on how to achieve this in angularjs?

In the regular mode, it should look like the following:

https://i.stack.imgur.com/Ma3HG.jpg

This is how it would appear.

If I extend the center div, it should look like the following example:

https://i.stack.imgur.com/ej7V7.jpg

If I expand the last div, it should resemble this example:

https://i.stack.imgur.com/QbW8S.jpg

Thank you!

Answer №1

Give this a try! You can expand all the divs in any order and switch them back to their normal position by clicking on the expanded div again.

The width of the compressed and expanded states are represented in percentages and can be adjusted in the CSS to fit your needs. I've also included a transition property for smoother functionality.

Check out the code snippet on this codepen link.

$("a.expansion-btn").click(function () {
  classes = this.className;
  var divNumber = classes.slice(-1);
  var toGetId = "#div-" + divNumber;
  if ($(toGetId).hasClass("expanded-div")) {
    $(".normal-div").removeClass("compressed-div expanded-div");
  } else {
    $(".normal-div").removeClass("compressed-div expanded-div").addClass("compressed-div");
    ;
    $(toGetId).removeClass("compressed-div").addClass("expanded-div");
  }
});
*{
  box-sizing: border-box;
}
.container{
  margin: 0;
  padding: 0;
  width: 100%;
  height: 400px;
}
.normal-div{
  width: 33.33%;
  height: 100%;
  position: relative;
  border: 2px solid black;
  float: left;
  -webkit-transition: all 0.5s ease-in-out;
  -moz-transition: all 0.5s ease-in-out;
  transition: all 0.5s ease-in-out;
}
.expanded-div{
  width: 80%;
}
.compressed-div{
  width: 10%;
}
#div-1{
  background-color: green;
}
#div-2{
  background-color: red;
}
#div-3{
  background-color: blue;
}
a.expansion-btn{
  position: absolute;
  top: 10px;
  right: 10px;
  font-weight: bold;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="normal-div" id="div-1">
    <a class="expansion-btn exp-1">click</a>
  </div>
  <div class="normal-div" id="div-2">
    <a class="expansion-btn exp-2">click</a>
  </div>
  <div class="normal-div" id="div-3">
    <a class="expansion-btn exp-3">click</a>
  </div>
</div>

Answer №2

If you're looking to switch between different divs, you can use the following code snippet.

// define variable to track div index
var i = 0,
  // cache all div elements
  $div = $('.div');

// attach click event handler
$('.toggle').click(function() {
  $div
    // remove active and nonactive classes from all elements
    .removeClass('active nonactive')
    // select element by index
    .eq(i)
    // add active class
    .addClass('active')
    // select siblings
    .siblings()
    // add nonactive class
    .addClass('nonactive');
  // update index 
  i = ++i % $div.length;
})
.div {
  height: 300px;
  width: 30%;
  border: solid 1px black;
  display: inline-block
}
.active {
  width: 75%;
}
.nonactive {
  width: 10%;
}
.active,
.nonactive {
  -webkit-transition: width 1s ease-in-out;
  -moz-transition: width 1s ease-in-out;
  -o-transition: width 1s ease-in-out;
  transition: width 1s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="toggle">toggle</button>
<br>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>


Alternatively, if you prefer to toggle when clicking a button inside the div, consider this approach.

$('.toggle').click(function() {
  $(this)
    // find parent div
    .parent()
    // remove nonactive class from clicked element
    .removeClass('nonactive')
    // toggle active class
    .toggleClass('active')
    // get sibling divs
    .siblings()
    // remove active class from siblings
    .removeClass('active')
    // toggle nonactive class based on the clicked element 
    .toggleClass('nonactive', $(this).parent().is('.active'));
})
.div {
  height: 300px;
  width: 30%;
  border: solid 1px black;
  display: inline-block
}
.active {
  width: 75%;
}
.nonactive {
  width: 10%;
}
.div,
.active,
.nonactive {
  -webkit-transition: width 1s ease-in-out;
  -moz-transition: width 1s ease-in-out;
  -o-transition: width 1s ease-in-out;
  transition: width 1s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div class="div">
    <button class="toggle">toggle</button>
  </div>
  <div class="div">
    <button class="toggle">toggle</button>
  </div>
  <div class="div">
    <button class="toggle">toggle</button>
  </div>
</div>

Answer №3

    <div id="header">HEADER
        <input type="button" data-name="show" value="Toggle" id="toggle">
    </div>
    <div id="maincont">
        <div id="map" class="active">MAP</div>
        <div id="sidebar" class="inactive">SIDEBAR</div>
        <div id="sidebar1" class="inactive">SIDEBAR1</div>
    </div>

script:

    $(document).ready(function () {     
            $("#toggle").click(function () {

                        var $div = $('#maincont').find(".active");
                        $div.removeClass('active').addClass("inactive").next().addClass("active");      

                        $('#maincont').find(".inactive").animate({
                            width: '10%'
                        })

                        $('#maincont').find(".active").animate({
                            width: '79%'
                        });           

             });

    });

css.

         html, body {
            width:100%;
            height: 100%;
        }
        #header {
            width: 100%;
            height: 100px;
            float: left;
            border: 1px solid;
        }
        #map {  
            height: 80%;
            float: left;
            border: 1px solid;
        }
        .active{
          width:78%;
           float: left;
           height: 100px;
        }
        .inactive{
          width:10%;
           float: left;
           border: 1px solid;
            height: 100px;
        }
        #sidebar {   
            height: 80%;
            float: left;

        }
        #toggle {
            width: 10%;
            height: 40%;
            margin-right: 6.5%;
            margin-top: 3.5%;
            float: right;
        }

Link to the fiddle

Answer №4

Including the angularjs tag in your question led me to provide a straightforward solution without any complex CSS:

Assume you have an array of objects in the controller that define the panels/divs like this:

$scope.panels = [{
    title: "One",
    expanded: true
  }, {
    title: "Two"
  }, {
    title: "Three"
  }];

The expanded flag keeps track of which panel is currently expanded, defaulting to the first one.

When you click on a panel, this function updates the flag for the selected panel:

$scope.expandPanel = function(panel) {
     $scope.panels.forEach(p => p.expanded = false);
     panel.expanded = true;
}

To display this, use an ng-repeat loop and dynamically set the class based on the expanded flag using ng-class:

<div class="panel" 
     ng-class="{'expanded': panel.expanded, 'reduced': !panel.expanded}" 
     ng-repeat="panel in panels" ng-click="expandPanel(panel)">
  <span>{{panel.title}}</span>
</div> 

You can view this implementation live on this plunker link.

Note: The classes .panel, .expanded, and .reduced are defined in the plunker's CSS file.

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

Toggle the visibility of the navigation bar in Angular based on the user

I have implemented rxjs BehaviorSubject in my login page to transmit data to auth.service.ts, enabling my app.component to access the data stored in auth.service.ts. However, I now require the app.component to detect any changes made to the data in auth.se ...

What are the steps to achieve the desired PrimeFaces theme appearance for selectOneMenu?

Need help with a JSF Primefaces project using the omega theme. The selectOneMenu dropdowns are not displaying correctly (missing line). Current look: https://i.stack.imgur.com/vF4ms.png Expected look: https://i.stack.imgur.com/hXsIB.png Any suggestion ...

Eliminating an element from an array without the need for iteration

I've been reviewing some documentation, but I have a hunch that there may be a simpler way to eliminate one element from an array without having to utilize an iteration loop. http://jsfiddle.net/G97bt/1/ Check out the updated jsFiddle example: http: ...

Concurrent Openlayers maps in Rails - A Viable Option

I've been playing around with Openlayers maps on my website. The map functionality is working perfectly, but I'm having trouble getting the maps to display correctly on my page. My goal is to show a map in each search result on my screen - one m ...

Spacing between products in Woocommerce product list

Welcome to my website! Check it out here: I am facing an issue with a long margin at the bottom of my woocommerce product list. I have tried using CSS to change it as shown below: .woocommerce .products ul, .woocommerce ul.products { margin-bot ...

Transfer information from one Angular JS page to another pager based on ID

In my use of the mobile angular js UI framework, I am a beginner in angular js and looking to transmit data from one page to another using city id. When a user clicks on a city, the data should be displayed according to that specific city. HOME PAGE: ht ...

What is the process for retrieving a jQuery AJAX response from a NodeJS endpoint?

After successfully initiating an ajax call to a set up endpoint, I sent a raw certificate as JSON and had the backend decode it. While I am able to display the decoded result using console.log, I am struggling to figure out how to return it as the final ou ...

What steps can be taken to ensure express Node.JS replies to a request efficiently during periods of high workload

I am currently developing a Node.js web processor that takes approximately 1 minute to process. I make a POST request to my server and then retrieve the status using a GET request. Here is a simplified version of my code: // Setting up Express const app = ...

How can I place a submit button on a separate line using CSS?

Is there a way to position an input type=submit below a text area without relying on br tags or div elements? I'd prefer a solution using CSS. ...

progressing both forward and backward through every month

I am currently working on a project that involves creating a calendar using JavaScript. I have implemented functionalities where I can navigate back and forth through months, fetching the days within each month. However, I am facing an issue where if I go ...

Unusual actions when making a $.ajax call using the PUT method

When making a call to $.ajax, I use the following code: $.ajax({ type: 'PUT', url: model.url(), data: {task: {assigned_to: selected()}}, contentType: 'application/json' }) The function selected() returns an array. However, th ...

Loading content from external sources on the dashboard

I'm trying to figure out how to load an external URL () within the content of a Dashboard. My current code looks like this: .state('app.urlloading', { url: '/url-loading', controller:function($window){ $window.locat ...

Encountering issue while static generating project: Cannot find resolution for 'fs' module

I am encountering an issue in my Next.js app when trying to serve a static file. Each time I attempt to use import fs from 'fs';, an error is thrown. It seems strange that I have to yarn add fs in order to use it, as I thought it was not necessa ...

Can AdonisJS 4.1.0 support conditional queries?

I am exploring the capabilities of AdonisJs query builder by referring to their documentation at Currently, I am attempting to replicate a scenario similar to the one demonstrated under the 'Conditional Queries' section: const query = Database. ...

JavaScript was unable to locate the requested URL on the server

After successfully deploying and accessing the URL using Firebase's hosting feature, everything seems to work fine. However, when I try to access a specific endpoint like this: https://*******.web.app/api/send, I encounter the following error message: ...

Switch out the rowspan attribute in HTML for a CSS alternative

Hello there, I've been experimenting with replacing my table layout with divs and CSS, but I'm struggling to find a way to replicate the behavior of the rowspan attribute. Here is the original code snippet: <table> <tr> <td> ...

Implementing cross-app module injection in Node.js

I have two node apps/services that are currently running together: 1. the main app 2. the second app The main app is responsible for displaying all the data from different apps in the end. Currently, I have taken some code from the second app and integra ...

Tips for utilizing c# datatable in jquery ajax on asp.net webform

Hey guys, I'm trying to send a datatable from C# to jQuery using Ajax. It seems that when I send a string, everything works fine, but when I try to send a datatable, I encounter the error below: [WebMethod] public static DataTable getGuestByGuestIDFr ...

Stripping away HTML tags from a JSON output

I'm attempting to retrieve a JSON result using jQuery. $.ajax({ type: "GET", url: "http://localhost:8080/App/QueryString.jsp?Query="+query, contentType:"text/html; charset=utf-8", dataType: "json", success: function(json) { if(data!="") ...

Having trouble with jQuery validation: Seeking clarification on the error

I have implemented some validations on a basic login page and added jQuery validation upon button click. However, the code is not functioning as expected. I have checked the console for errors but none were displayed. Here is the code for your review: ...