Display or conceal div elements using JavaScript

Is there a way to hide certain divs when clicking on a specific div box?

Clicking on the box will trigger the hiding of some application divs. See the first image below:

When the boxes are hidden, the other divs will readjust in place of the current divs and then revert back to their standard view. Second image:

Code:

<div class="container">
   <div class="row">
      <div class="col-md-4" style="text-align: center;">
    <button onclick="projectCollab()"><div id="decisionTreeBox" style="font-size: larger;">Collaborate on Projects</div></button>
    </div>
        <div class="col-md-4" style="text-align: center;">
        <div id="decisionTreeBox" style="font-size: larger;">Collaborate on Files</div>
        </div>
        <div class="col-md-4" style="text-align: center;">
        <div id="decisionTreeBox" style="font-size: larger;">Collaborate Socially</div>
        </div>
      </div>
      <hr />
      <div class="row">
      <div class="col-md-4" style="text-align: center;">
    <div id="decisionTreeOneDrive"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/onedrive-logo.png" style="width: 65px; height: 65px; padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>OneDrive</h3></div>
    </div>
        <div class="col-md-4" style="text-align: center;">
        <div id="decisionTreeProject"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/Project.png" style="padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>Project</h3></div>
        </div>
        <div class="col-md-4" style="text-align: center;">
        <div id="decisionTreeSharePoint"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/SharePointDecisionTree.png" style="padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>SharePoint</h3></div>
        </div>
        <div class="col-md-4" style="text-align: center;">
        <div id="decisionTreeTeams"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/TeamsDecisionTree.png" style="padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>Teams</h3></div>
        </div>
        <div class="col-md-4" style="text-align: center;">
        <div id="decisionTreePlanner"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/PlannerDecisionTree.png" style="padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>Planner</h3></div>
        </div>
        <div class="col-md-4" style="text-align: center;">
        <div id="decisionTreeYammer"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/YammerDecisionTree.png" style="padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>Yammer</h3></div>
        </div>
      </div>
    <script>
    function projectCollab() {
    var x = document.getElementById("decisionTreeOneDrive");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}
</script>
</div>

Please ignore the JavaScript code provided as it did not seem to work correctly.

Answer №1

Consider using different selectors for your div IDs, such as data attributes.

<html>
    <head>
        <meta charset="UTF-8" />
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-4" style="text-align: center;">
                    <div data-collaborate="projects" style="font-size: larger;">Collaborate on Projects</div>
                </div>
                <div class="col-md-4" style="text-align: center;">
                    <div data-collaborate="files" style="font-size: larger;">Collaborate on Files</div>
                </div>
                <div class="col-md-4" style="text-align: center;">
                    <div data-collaborate="socially" style="font-size: larger;">Collaborate Socially</div>
                </div>
            </div>
            <hr />
            <div class="row">
                <div class="col-md-4" style="text-align: center;">
                    <div data-decision="projects" id="decisionTreeOneDrive"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/onedrive-logo.png" style="width: 65px; height: 65px; padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>OneDrive</h3></div>
                </div>
                <div class="col-md-4" style="text-align: center;">
                    <div data-decision="projects" id="decisionTreeProject"><h3 id="innerBoxHeadings"><img src="/TrainingResourceC...
        </div>
    </body>
</html>

Answer №2

To easily switch between hiding and showing elements, you can utilize the jQuery .toggle() function. This function will automatically adjust the position of adjacent divs.

$(document).ready(function() {
  $('#decisionTreeBox').on('click', function() {
    $('#test').toggle('show');
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">


<div class="container">
   <div class="row">
      <div class="col-md-4" style="text-align: center;">
    <button onclick="projectCollab()"><div id="decisionTreeBox" style="font-size: larger;">Collaborate on Projects</div></button>
    </div>
        <div class="col-md-4" style="text-align: center;">
        <div id="decisionTreeBox" style="font-size: larger;">Collaborate on Files</div>
        </div>
        <div class="col-md-4" style="text-align: center;">
        <div id="decisionTreeBox" style="font-size: larger;">Collaborate Socially</div>
        </div>
      </div>
      <hr />
      <div class="row">
      <div class="col-md-4" style="text-align: center;" id="test">
    <div id="decisionTreeOneDrive"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/onedrive-logo.png" style="width: 65px; height: 65px; padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>OneDrive</h3></div>
    </div>
        <div class="col-md-4" style="text-align: center;">
        <div id="decisionTreeProject"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/Project.png" style="padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>Project</h3></div>
        </div>
        <div class="col-md-4" style="text-align: center;">
        <div id="decisionTreeSharePoint"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/SharePointDecisionTree.png" style="padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>SharePoint</h3></div>
        </div>
        <div class="col-md-4" style="text-align: center;">
        <div id="decisionTreeTeams"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/TeamsDecisionTree.png" style="padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>Teams</h3></div>
        </div>
        <div class="col-md-4" style="text-align: center;">
        <div id="decisionTreePlanner"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/PlannerDecisionTree.png" style="padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>Planner</h3></div>
        </div>
        <div class="col-md-4" style="text-align: center;">
        <div id="decisionTreeYammer"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/YammerDecisionTree.png" style="padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>Yammer</h3></div>
        </div>
      </div>
    


</div>

Answer №3

If you want to hide or show a specific element, you can achieve this by calling a function with an onclick event and passing 'this' as a parameter. Try out the provided example below.

<div class="container">
    <div class="row">
           <div class="col-md-4" style="text-align: center;">
             <button onclick="projectCollab(this)"><div class="container">

Collaborate on Projects Collaborate on Files Collaborate Socially


OneDrive Project SharePoint Teams Planner Yammer function projectCollab() { var x = document.getElementById("decisionTreeOneDrive"); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } }

Answer №4

My version of HTML mirrors yours, but the JS functions below are here to assist in case you prefer utilizing JavaScript over jQuery.

<div class="container">
   <div class="row">
        <div class="col-md-4" style="text-align: center;">
            <button onclick="projectCollab()"><div id="decisionTreeBox" style="font-size: larger;">Collaborate on Projects</div></button>
        </div>
        <div class="col-md-4" style="text-align: center;">
            <div id="decisionTreeBox" style="font-size: larger;">Collaborate on Files</div>
        </div>
        <div class="col-md-4" style="text-align: center;">
            <div id="decisionTreeBox" style="font-size: larger;">Collaborate Socially</div>
        </div>
      </div>
      <hr />
      <div class="row">
        <div class="col-md-4" style="text-align: center;">
            <div id="decisionTreeOneDrive"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/onedrive-logo.png" style="width: 65px; height: 65px; padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>OneDrive</h3></div>
        </div>
        <div class="col-md-4" style="text-align: center;">
            <div id="decisionTreeProject"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/Project.png" style="padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>Project</h3></div>
        </div>
        <div class="col-md-4" style="text-align: center;">
            <div id="decisionTreeSharePoint"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/SharePointDecisionTree.png" style="padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>SharePoint</h3></div>
        </div>
        <div class="col-md-4" style="text-align: center;">
            <div id="decisionTreeTeams"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/TeamsDecisionTree.png" style="padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>Teams</h3></div>
        </div>
        <div class="col-md-4" style="text-align: center;">
            <div id="decisionTreePlanner"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/PlannerDecisionTree.png" style="padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>Planner</h3></div>
        </div>
        <div class="col-md-4" style="text-align: center;">
            <div id="decisionTreeYammer"><h3 id="innerBoxHeadings"><img src="/TrainingResourceCenter/O365Training/PublishingImages/YammerDecisionTree.png" style="padding-bottom: 5px; padding-right: 10px; vertical-align: middle;"/>Yammer</h3></div>
        </div>
      </div>
    <script>
    function projectCollab() {
        var x = document.getElementById("decisionTreeOneDrive").setAttribute("onclick", hide());
    }
    function hide(){
        var sharepoint = document.getElementById("decisionTreeSharePoint");
        var planner = document.getElementById("decisionTreePlanner");
        if (sharepoint.style.display === "none") {
            sharepoint.style.display = "block";
        } else {
            sharepoint.style.display = "none";
        }

        if (planner.style.display === "none") {
            planner.style.display = "block";
        } else {
            planner.style.display = "none";
        }
    }
    </script>
</div>

Answer №5

It appears that you are faced with two challenges.

  1. Your objective is to switch the squares below.
  2. You aim for the containers to collapse in the remaining space.

To address the first challenge - I've implemented a vanilla JavaScript toggle function without relying on any frameworks.

This involves making three modifications to the HTML code:

  • Include the onClick toggle function on each button:
    onclick=toggleSquares('DESTINATION');
  • Add the destination to the CSS column element (solves #2) you want toggled: data-toggle="files"
  • Optional: Add a CSS class hook to the CSS column element.

<button onclick=toggleSquares('projects')>
        <div id="decisionTreeBox">Collaborate on Projects</div>
 </button>

...

<div class="col-md-4 square" data-toggle="projects">
    <div>
          <h3 id="innerBoxHeadings">OneDrive</h3>
    </div>
</div>

`

The JavaScript function would resemble this:

function toggleSquares(type){
   var getSquares = document.querySelectorAll(".square");

  getSquares.forEach(function(element){

    if(element.getAttribute('data-toggle') != type) {
      element.classList.add('display-none');
    }
    else {
      element.classList.remove('display-none');
    }
  })
}

Here's an overview of the process:

  1. Upon click, retrieve all elements with the '.square' class and store them in a local variable within the function.
  2. Iterate through these elements and compare them to the type passed down by the function.
  3. If the element doesn't match the provided type, add a CSS class with 'display: none' property.
  4. If the element does match the type, remove the previously added CSS class from step 3.

Check out this CodePen demonstration of the functionality: https://codepen.io/MathiasaurusRex/pen/aKZbqR

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

Merge nested arrays while eliminating any redundant elements

Is there a way to merge these array sets while ensuring that duplicate values are removed? I am unsure if lodash provides a solution for this specific scenario where the arrays are nested. Most of the solutions I have come across assume flat arrays. Any ...

Cut off the initial characters in the URL's hash component

Hey there, I'm currently working on a task that involves removing a specific part of a URL string. Here's the scenario: if (window.location.hash == '#super-super-product') { change.window.location.hash.to.this: #product // this i ...

Guide to choosing the directory for Visual Studio's compilation of LESS files

I currently use VS 2012 on my Windows 7. It seems that by default, it compiles LESS files to CSS in the same directory as the LESS file when I save. However, I would prefer to have all my CSS files saved in a "css" directory located next to the "less" dir ...

Steps for disabling script debugger within Visual Studio 2013

How do I disable script debugging in Visual Studio 2013? I have already disabled script JIT debugging under Tools>Options>Debugging>JIT, and have turned off script debugging in Internet Explorer as well. Despite setting the error option to 'b ...

Sort the currency column in an HTML table through JavaScript

I have a code snippet below that I'm currently utilizing to arrange columns in an HTML table. The code works perfectly for alphabetical sorting and also for single-digit numbers. However, when attempting to sort a column containing currency values, t ...

Centering navigation using HTML5

I've been struggling a bit trying to build a website, particularly with centering my <nav> tag. Despite reading numerous suggestions like using CSS properties such as margin: 0 auto; or text-align: center, nothing seems to be working for me. Si ...

The screen reader is unable to interpret the text that is visible within the anchor tag

I have an Angular application with a dropdown menu implemented as shown below. When using the NVDA screen reader to navigate, only the content inside the aria-label attribute is being read when tab focused. However, I want it to also read the content (&ap ...

The client end encountered an issue preventing the saving of a jpeg image

I have a situation where I need to retrieve an image stored on the server and send it to the client using sockets. While I am able to display the received image on canvas, I am encountering difficulties in saving the image to the local disk. I have attempt ...

Encountering an error message stating "Unable to read property 'map' of undefined while attempting to create drag and drop cards

I have incorporated the library available at: https://github.com/clauderic/react-sortable-hoc The desired effect that I am aiming for can be seen in this example: https://i.stack.imgur.com/WGQfT.jpg You can view a demo of my implementation here: https:// ...

Guide on submitting a multi-step form using jQuery

Greetings, I am in need of assistance with submitting a jQuery step wizard form. Although I have a plugin that helps, it primarily uses jQuery rather than HTML. So far, I have accomplished the following steps: - Set up the necessary database and table - C ...

Animating a jQuery Knob as you scroll from 0 to a set value

I am new to jQuery and currently working on jQuery Knob. Everything is functioning properly, but I have encountered an issue. When scrolling to the section with the knobs, I would like them to animate from 0 to a specific value. Is there a way to achieve ...

JSON payload with an array that includes nested JSON objects

I am struggling with JSON objects and need to create a JSN structure similar to the following: { name: 'root', children: [ name: 'son1', children: [....] ] } Could someone please guide me on how to construct it using Java ...

Avoiding line breaks when using an :after pseudo element

I am trying to style external links by adding a pseudo :after element right after the link itself, but I'm having trouble getting it to work on the same line. Here is the CSS code I have: a:not([href*="domain"])::after { content: url(data:image/svg+ ...

Learn how to toggle multiple class elements with jQuery, and how to hide the ones that have

This is an example of my HTML code: <h4 class="list-group-item-heading"> @Model.Customer.FirstName @Model.Customer.LastName wrote: <span class="right"><span class="icon-file padding-right link"></span></span> </h4& ...

Enhancing the window.print() Functionality

I recently utilized the window.print() function to print a web page containing a table. The headers of the table were styled with font color, however when printed, they appeared black instead. Below is the code snippet: <thead> <tr style="color:r ...

Getting the start of a day for a specific date in JavaScript while considering the timezone

I'm having trouble determining the start of a day while factoring in timezones using javascript. Consider this example: var raw_time = new Date(this.created_at); var offset_time = new Date(raw_hour.getTime() + time_zone_offset_in_ms); // Th ...

Encountering a problem with the Batarang tool while constructing a MEANJS demo (Uncaught TypeError: Unable to access property 'getToggleElement' of null)

Trying to utilize the AngularJS Batarang while learning to create a MEANJS App. You can find the tutorial here: Noticing that my "Scopes" tab appears differently compared to the tutorial video and an error is displayed. Here is what I see in my Batarang ...

The Google Geo Charts fail to load when initiated by Ajax requests

My goal is to use ajax to load an external HTML page that includes the following code: <script type='text/javascript' src='https://www.google.com/jsapi'></script> <script type='text/javascript'> function ...

Printing from a lengthy React DOM using window.print only generates a single page

My React component is capable of rendering markdown and can span multiple pages. Everything looks great when the component is displayed in the browser - scrolling works perfectly. However, whenever I try to print the page using window.print or ctrl + P, ...

Steps for installing an npm package from a downloaded folder

In the past, I had a method of installing an npm project from Github that involved using git clone followed by npm install. git clone http...my_project npm install my_project Instead of manually copying the contents of my_project to my local node_modules ...