Is there a way to collapse an element by clicking either the content inside the div or the button within the div?

Is there a way to make a button within a newly activated div close it? The existing code seems to have issues with this functionality, and adding new rules or functions has not solved the problem. Any assistance with fixing this issue using vanilla JavaScript would be greatly appreciated.

var infoBtn = document.getElementsByClassName("more-info");
var i;

for (i = 0; i < infoBtn.length; i++) {
  infoBtn[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.maxHeight) {
      content.style.maxHeight = null;
    } else {
      content.style.maxHeight = content.scrollHeight + "px";
    }
  })
}
.work-projects {
  margin: 40px 0;
}

.work-boxes {
  display: flex;
  position: relative;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 90%;
  height: 40vh;
  min-height: 300px;
  margin: 20px auto;
  background-color: white;
  border-radius: 5px;
}

.work-box-content {
  opacity: 1;
  z-index: 1;
  background-color: rgb(32, 32, 32);
  padding: 20px;
  width: 50%;
  border: 5px solid rgba(253, 225, 78);
  border-radius: 5px;
  position: relative;
}

.work-projects h2 {
  color: turquoise;
  text-align: center;
  font-weight: 400;
  font-size: 1.2em;
}

.work-box-content .code-logo {
  flex-direction: row;
  align-self: center;
  justify-content: space-around;
  max-width: 100%;
}

#PHP-pic {
  height: auto;
  margin: auto 0;
}

.project-links {
  display: flex;
  justify-content: space-between;
}

.project-links img {
  height: 30px;
  width: auto;
  transition: all .2s ease-in-out;
}

.project-links a {
  padding: 20px;
  text-decoration: none;
  margin: 5px 0;
}

.project-links a:hover img {
  filter: opacity(60%);
  transform: scale(1.1);
}

.sidenav {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 0 5px;
  z-index: 200;
  margin: 0;
  background-color: turquoise;
  text-align: center;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.25s ease-out;
}

.more-info {
  height: 30px;
  width: auto;
  display: block;
  padding: 5px;
  margin: 0 auto;
}

.sidenav p {
  font-size: 0.7em;
}
<main class="main-page">
  <div class="work-projects" id="work-bookmark">
    <div class="work-boxes" id="sectionone">
      <div class="work-box-content">
        <h2>TITLE</h2>
        <div class="code-logo">
          <figure>
            <img id="HTML-pic" src="./images/HTML5.png" alt="HTML">
          </figure>
          <figure>
            <img id="CSS-pic" src="./images/CSS3.png" alt="CSS">
          </figure>
          <figure>
            <img id="JS-pic" src="./images/JS.png" alt="JS">
          </figure>
          <figure>
            <img id="PHP-pic" src="./images/php.png" alt="PHP">
          </figure>
        </div>
        <section class="project-links">
          <a class="github-project" href="https://github.com/adraf/Dan-Batchelor">
            <img src="./images/iconmonstr-github-2.png" alt="github logo">
          </a>
          <a class="linktoproject" href="http://danbatch.com/">
            <img src="./images/iconmonstr-share-11.png" alt="website link">
          </a>
        </section>
        <img class="more-info" src="./images/iconmonstr-info-1-240.png" alt="more information">
        <div id="mySidenav" class="sidenav">
          <p>
            Text tetxt text Text tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt text
            text
            <br> Text tetxt text Text tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt textText tetxt text</p>
        </div>
      </div>
    </div>
  </div>
</main>

Answer №1

To implement this functionality, you can add a secondary event listener for the click action on the specified div element (identified by the id mySidenav).

Here's a demonstration of how it works:

var infoBtn = document.getElementsByClassName("more-info");
var index;

for (index = 0; index < infoBtn.length; index++) {
  infoBtn[index].addEventListener("click", function() {
    this.classList.toggle("active");
    var data = this.nextElementSibling;
    if (data.style.maxHeight) {
      data.style.maxHeight = null;
    } else {
      data.style.maxHeight = data.scrollHeight + "px";
    }
  })
  
  document.querySelector("#mySidenav").addEventListener('click', function() {
    this.style.maxHeight = null;
  });
}
.work-projects {
  margin: 40px 0;
}

.work-boxes {
  display: flex;
  position: relative;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 90%;
  height: 40vh;
  min-height: 300px;
  margin: 20px auto;
  background-color: white;
  border-radius: 5px;
}

/* Remaining CSS code here */
<main class="main-page">
  <div class="work-projects" id="work-bookmark">
    <div class="work-boxes" id="sectionone">
      <div class="work-box-content">
        <h2>TITLE</h2>
        <div class="code-logo">
          <figure>
            <img id="HTML-pic" src="./images/HTML5.png" alt="HTML">
          </figure>
          <figure>
            <img id="CSS-pic" src="./images/CSS3.png" alt="CSS">
          </figure>
          <figure>
            <img id="JS-pic" src="./images/JS.png" alt="JS">
          </figure>
          <figure>
            <img id="PHP-pic" src="./images/php.png" alt="PHP">
          </figure>
        </div>
        <section class="project-links">
          <a class="github-project" href="https://github.com/adraf/Dan-Batchelor">
            <img src="./images/iconmonstr-github-2.png" alt="github logo">
          </a>
          <a class="linktoproject" href="http://danbatch.com/">
            <img src="./images/iconmonstr-share-11.png" alt="website link">
          </a>
        </section>
        <img class="more-info" src="./images/iconmonstr-info-1-240.png" alt="more information">
        <div id="mySidenav" class="sidenav">
          <p>
            New text here. New text here. New text here. New text here. New text here. New text here. New text here. New text here. New text here. New text here. New text here. New text here. New text here. New text here. New text here. New text here. </p>
        </div>
      </div>
    </div>
  </div>
</main>

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

How can I pass standard HTML as a component in React?

I need help creating a Higher Order Component (HOC) that accepts a wrapper component, but allows me to pass standard HTML elements as inner content. Here is an example of what I want to achieve: type TextLike = string | {type,content} const TextLikeRender ...

Tips for checking the type radio button input with Angular.js

I want to implement validation for a radio button field using Angular.js. Below is the code snippet I am working with: <form name="myForm" enctype="multipart/form-data" novalidate> <div> <input type="radio" ng-model="new" value="true" ng- ...

Error message 'Module not found' occurring while utilizing dynamic import

After removing CRA and setting up webpack/babel manually, I've encountered issues with dynamic imports. https://i.sstatic.net/CRAWr.png The following code snippet works: import("./" + "CloudIcon" + ".svg") .then(file => { console.log( ...

Delving into the concept of the last-child element

Looking for assistance with selecting the final EC_MyICHP_Item from an HTML structure: <div class="decorator"> <div class="EC_MyICHP_Item"> <div class="text"> <h3><a target="_blank" title="" href="#">& ...

Is it possible to modify a variable within the readline function?

Can anyone help me figure out how to update the variable x within this function? const readline = require('readline'); const r1 = readline.createInterface({ input: process.stdin, terminal: false }); let x = 1; r1.on('line', fu ...

Exploring the process of dynamically setting up Passportjs strategies

Currently experimenting with passport and setting up my Twitter login like this: passport.use(new TwitterStrategy({ consumerKey: '*****', consumerSecret: '*****', callbackURL: "http://blabla/callback" }, functi ...

Unlocking the secrets of extracting dimensions from imported SVG components in nextJS

I am facing an issue with importing an SVG file as a component and trying to obtain its dimensions, but it keeps returning null. Can someone provide me with advice on how to resolve this? PS. When I try using getBBox(), it throws an error. Here is the co ...

Ways to prevent my website from being accessed through the Uc Browser

Is there a way to prevent my website from functioning on UC Browser using HTML or JavaScript? ...

In my React JS class component, I am looking to have the image display switch each time the button is clicked

How can I change the image when clicking a button in a class component? I am familiar with function components, but unsure how to achieve this. class CoffeeImages extends React.Component{ constructor(props){ super(props) ...

Execute an HTTP POST request to the Node server, sending an empty object

For my project, I am attempting to send an HTTP Post request to my Node server from an html form. Despite using Body Parser and setting it up correctly, I am facing an issue where the req.body on my server is returning as an empty object. Can anyone prov ...

The Bootstrap Grid System Column is Experiencing Issues

Check out my code snippet: I've attempted changing the container class to container-fluid and resizing the page, but no luck. <div class="container"> <div class="row"> <!--Product: banana split--> ...

Creating a custom theme for a tree panel in Ext JS 4

I'm looking to start customizing a Sencha 4 Tree panel, adjusting elements like text size and background colors. So far, I haven't been able to figure out the right approach, whether it's through viewConfig or some other method. Here's ...

AngularJS directive: handling child elements

Is there a way to structure the directive below in order to have access to all the ul elements within the link function? In the code snippet provided, when examining the elm (logged in console), it appears as a comment type and ul are displayed as sibling ...

Having trouble with vendor CSS not being recognized during brunch compilation

I am currently exploring the use of Pure.css in my application. After installing it via npm, I have configured my brunch-config.js as follows: stylesheets: { joinTo: { 'app.css': /^app/, 'vendor.css': /^(?!app)/ } } At thi ...

What is the best way to enhance an object using a class in ES6?

In an effort to improve the clarity of my ES6 class definition, my current code looks like this: class SomeClass { constructor({a, b, c, d, e}) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; // additional code here ...

Nuxt: The meta title for dynamic head is not defined during server-side rendering

In my nuxt project, I am encountering an issue with the meta title and description. These values are coming from nuxt/content. The data is fetched asynchronously in the index and passed to a sub component using a getter. When generating the page, the met ...

Parsing JSON data using PHP and AJAX decoding

I have been searching for a way to pass parameters between the server and client, but I am struggling to find a solution that works. Despite reading extensively online, I have not been able to come up with a functioning solution. Client Side function sen ...

Invoking a class method in Javascriptcore on iOS

I'm currently trying to comprehend the inner workings of JavascriptCore. Initially, I attempted calling a single function. Now, my focus has shifted to invoking a function within a class. This is what my javascript code looks like: var sayHelloAlf ...

Change the information displayed on buttons when clicked and provide options for users to navigate between different

In order to change the content when a button or number is clicked, you can utilize the buttons "1,2,3,4" or the Next and Prev buttons shown in the snippet. Both methods allow access to the same article. If you want to switch between articles using the Next ...

Storing data efficiently with Angular 2's local storage service

I am attempting to create a ToDoList using localstorage within a service. add.component.ts export class AddComponent implements OnInit { item: Item[]; constructor( private router: Router, private itemService: ItemService) { } ...