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

Javascript encounters an unforeseen < token

I encountered an unexpected token < error in my JavaScript file. Despite checking the code using JSHint, I couldn't find any issues that could resolve the problem. I attempted to place the JavaScript code in a separate file and also tried embeddin ...

Solution to trigger CSS :hover to refresh following a transition (such as expanding a menu)

While there are existing discussions on this topic, I am presenting my query for two specific reasons: It introduces a potential alternative solution The demo code could be helpful to individuals looking to emulate a menu Following a CSS transition, the ...

Implementing a restriction clause while executing a load additional data feature

I'm currently working on implementing a basic load more function for my web page. Right now, the page displays 8 results from the database. When the user scrolls, a load more button appears. Clicking this button triggers an ajax request to another PH ...

Enabling or disabling a button dynamically in Ionic based on a conditional statement

I am looking to dynamically enable or disable buttons based on specific conditions. The data is retrieved from Firebase, and depending on the data, I will either enable or disable the button. For example, if a user passes the First Quiz, I want to enable ...

Using Ruby on Rails to incorporate AJAX for posting and commenting functionality

Could use some assistance with implementing AJAX into my project. It seems like it should be a simple task, but I've been struggling with it for days. My goal is to have new comments appear without the need to reload the page. Below are references to ...

Struggling to store information in a MongoDB database within my MEAN Stack project

After successfully creating a collection for user LOGIN/LOGOUT and managing to store and retrieve data using Express app and mongoose, I encountered an issue when trying to create another collection. Despite successfully creating the collection, the data w ...

Can anyone provide a method for obtaining a date that is x days earlier through date arithmetic?

Is there a method to obtain the date from 63 days ago with only day, month, and year information needed, excluding hours, minutes, and seconds? I am aware that one can calculate Date object - Date object, but I am curious if it is feasible to derive a dat ...

Discover the process of incorporating secondary links into your dabeng organizational chart!

I need to incorporate dotted lines on this chart, such as connecting leaf level nodes with middle level nodes. import OrgChart from '../js/orgchart.min.js'; document.addEventListener('DOMContentLoaded', function () { Mock.mock(&apo ...

Runtime.UnhandledPromiseRejection - Oops! Looks like we're trying to read properties of something that doesn't exist (specifically 'headers')

I'm facing an unexpected error that has left me puzzled. Let me walk you through what I am trying to accomplish: The task at hand involves fetching data from one API and then transmitting it to another. This process is executed as a background-funct ...

Using Single Quotes as Parameters in JavaScript

I'm currently facing an issue with a function that is designed to populate a field in the parent window when clicked. Specifically, it is meant to fill in a text field with a name. The challenge I am encountering arises when the field contains a sing ...

There are critical vulnerabilities in preact-cli, and trying to run npm audit fix leads to a never-ending loop between versions 3.0.5 and 2.2.1

Currently in the process of setting up a preact project using preact-cli: npx --version # 7.4.0 npx preact-cli create typescript frontend Upon completion, the following information is provided: ... added 1947 packages, and audited 1948 packages in 31s 12 ...

Updating the state of a nested array using React Hooks

After spending some time working with React Hooks, my main struggle has been dealing with arrays. Currently, I am developing a registration form for teams. Each team consists of a list of players (an array of strings). The goal is to allow users to add t ...

Pass multiple variables as input to a function, then query a JSON array to retrieve multiple array values as the output

My JavaScript function contains a JSON array, where it takes an input and searches for the corresponding key/value pair to return the desired value. I am attempting to input a string of variables like this: 1,2,3,4,5 Into this function: function getF(f ...

The efficiency of React Context API's setters is remarkably sluggish

I have a goal to implement a functionality where the background gradient of a page changes depending on whether the child's sublinks are expanded or collapsed. To achieve this, I am using the useContext hook. However, I've noticed that although e ...

Creating a New Section in your HTML Table

Can a page break be implemented in an HTML table? I've attempted to add page breaks to the following HTML: <html> <title>testfile</title> <meta http-equiv="expires" content="0" /> <meta http-equiv="cache-contr ...

Using selenium for testing JavaScript elements through RSpec results in failures in other segments of the RSpec test

Trying to implement Stripe into my web application has brought me to a frustrating roadblock. Every attempt to test the "Pay with Card" button seems to be thwarted by an ElementNotFound error thrown by rspec. Research revealed that the root cause of this ...

How to change the image source using jQuery when hovering over a div and set its class to active?

I am working with a div structure that looks like this: <div class="row margin-bottom-20"> <div class="col-md-3 service-box-v1" id="div1"> <div><a href="#"><img src="path" id="img1" /></a></div> ...

NodeJS - issues with nodemon auto-reload feature causing my server to not

After successfully installing NodeJS version 4.4.5, I proceeded to install nodemon version 1.9.2 by following all the installation instructions using npm (npm install -g nodemon). In a newly created folder, I have my server.js file with some basic code: ...

Angular 2 ngIf displaying briefly before disappearing

Encountering a strange issue with an Angular 2 ngIf statement where it appears on the page for a brief moment and then disappears. The content is visible, but it doesn't remain on the page. I suspect it might be related to some asynchronous behavior. ...

Using the data from two input fields, an ajax request is triggered to dynamically populate the jQuery autocomplete feature

I've been struggling with this issue for quite some time now. My goal is to pass 2 arguments (the values of 2 input fields in a form) in my ajax call so I can use them for a jQuery autocomplete feature (the search is based on a MySQL query using the v ...