What are some effective strategies for keeping content from shrinking in a drawer menu?

I am currently using a tutorial from https://www.w3schools.com/howto/howto_js_sidenav.asp to create a drawer sidebar menu.

However, in my scenario, I need to include a wall of text instead of <a> links. The issue I am facing is that the text expands and contracts when the drawer is opened and closed. https://jsfiddle.net/52qukbow/

function openNav() {
  document.getElementById("mySidenav").style.width = "500px";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
}
body {
  font-family: "Lato", sans-serif;
}

.sidenav {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.content {
  color: white;
}

.sidenav .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

@media screen and (max-height: 450px) {
  .sidenav {
    padding-top: 15px;
  }
}
<div id="mySidenav" class="sidenav">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
  <div class="content">
    Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
    sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora
    incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate
    velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
  </div>
</div>

<h2>Animated Sidenav Example</h2>
<p>Click on the element below to open the side navigation menu.</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span>

How can I prevent the content inside the drawer menu from expanding and contracting when the drawer is opened and closed?

Answer №1

If you're looking to learn things correctly, I suggest staying away from using w3schools. There are numerous tutorials out there that are much better. For references, I would recommend using MDN instead.

  1. Instead of using <a> for non-links, opt for <button> for actions you want to perform.

  2. Utilize classes and toggle them for states rather than manipulating them with JavaScript for things that can be accomplished using CSS.

  3. Avoid changing properties that trigger re-paints for better performance. For example, using translate instead of width will just move the element without causing a re-paint.

I prefer using class querySelector over onClick. While there are some CSS adjustments I would make, I have only made changes relevant to the question.

const toggleNavigationActions = document.querySelectorAll('.js-toggle-navigation')

toggleNavigationActions.forEach(function(action) {
  action.addEventListener('click', function() {
    const slideOutNavigation = document.querySelector('#slide-out-navigation')
    slideOutNavigation.classList.toggle('sidenav--is-open')
  })
})
body {
  font-family: "Lato", sans-serif;
}

.sidenav {
  height: 100%;
  width: 500px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: transform 240ms ease-out;
  padding-top: 60px;
  transform: translateX(-500px);
}

.sidenav--is-open {
transition: transform 240ms ease-in;
  transform: translateX(0);
}

.content {
  color: white;
}

.sidenav .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

@media screen and (max-height: 450px) {
  .sidenav {
    padding-top: 15px;
  }
}
<div id="slide-out-navigation" class="sidenav">
  <button class="closebtn js-toggle-navigation">&times;</button>
  <div class="content">
    Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae...
  </div>
</div>

<h2>Animated Sidenav Example</h2>
<p>Click on the element below to open the side navigation menu.</p>
<button style="font-size:30px;cursor:pointer" class="js-toggle-navigation">&#9776; open</button>

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

Using Javascript to Treat an HTML Document as a String

Check out the complete project on GitHub: https://github.com/sosophia10/TimeCapsule (refer to js/experience.js) I'm utilizing JQuery to develop "applications" for my website. I'm encountering a problem where I can't locate the correct synta ...

Issues with Implementing Custom CSS Styles in ag-grid

It seems like a simple customization, but the documentation on it is quite limited. I'm trying to change the line-height of one of my tables so that text doesn't double-space when wrapping. Here's the CSS code from Test.module.css: .ag-them ...

Can someone show me the JavaScript code to split a string at every instance of ' '?

Hey there! I have a question about manipulating strings. Take a look at this example: var string = '"In Another World" "Magic Books"' I want to create an array that contains every name within the [""]. How can I ach ...

Using jQuery to pass UI positions as percentages instead of screen positions

Currently, I have implemented the following code to send $_GET values to a PHP page: $.get('/includes/sticky_notes/update_position.php',{ x : ui.position.left, y : ui.position.top, z : zIndex, id : parseInt(ui. ...

What is the best way to extract the value from a JSON URL?

Using AngularJS, I am looking to dynamically retrieve the price value from a URL's JSON data. Is this feasible? Here is the URL JSON: link Below is my controller: angular.module("myApp",['zingchart-angularjs']).controller('MainContro ...

Unable to access property within JSON object sent via POST request

I encountered an issue TypeError: Cannot read property &#39;tasks&#39; of undefined While attempting a new POST request on my API, here is the request body I am using: { "name": "example1", "description": "teaching example1", "rules" ...

Developing a fresh Outlook email using a combination of javascript and vbscript

I have created a custom HTML page with fields and a button to fill out in order to generate a new Outlook mail item. To format the body of the email using HTML, I am utilizing VBScript to create the new mail item. <script> function generateEmail() { ...

Unable to delete the margin of Material-ui TextField

Having trouble removing the padding around material-ui's TextField component when using styled-components and inline styling. Any solutions to this issue? Interestingly, the inline width property is functioning correctly, unlike the styled-component w ...

Is it possible to maintain child divs in a single line?

Despite trying numerous recommendations (many involving white-space:nowrap and display:inline-block), I have been unsuccessful in keeping these child divs on a single line with horizontal scrolling. This is my code: <div id="list"> < ...

Guide on incorporating one element into another with jquery

I am facing a challenge with the following code snippet: <p>Nuno</p> <p>Eimes</p> My goal is to transform it into this format: <p><a href="name/Nuno">Nuno</a></p> <p><a href="name/Eimes">Eimes& ...

5% of the time, Ajax fails and the response is "error"

When utilizing jQuery for Ajax calls, I have encountered a situation where the call fails approximately 5% of the time. To troubleshoot and understand the issue better, I implement this code: $.ajax({ type:'POST', url:'somepage.php ...

Other Components take turns submitting the form in one Component

Two components, CreateCandidate and Technologies are being used. CreateCandidate requires technologies from the Technologies Component. When passing the technologies to CreateCandidate, the form within CreateCandidate is submitted. Below is the code: Crea ...

I wonder where the file from the HTML form download has originated

Recently, I've been experimenting with the developer tools in Chrome to observe the behavior of websites at different moments. It has proven useful in automating certain tasks that I regularly perform. Currently, my focus is on automating the process ...

Having trouble locating the nivoslider IE8 jQuery bug, can't seem to track it

I am encountering an issue with the nivoslider script in IE8 and I am having trouble identifying what is causing it. The nivoslider works perfectly fine in all other browsers except for IE8. Any help or guidance on this matter would be greatly appreciated ...

Could the issue lie with PHP or the caching system?

I'm encountering a frustrating issue with my simple test that I just can't seem to resolve. It seems like there's some sort of glitch involving images and PHP, as I can only display one image at a time. The script looks correct to me, so I&a ...

The link that has been clicked on should remain in an active state

Is there a way to make the link that is clicked on active? I have attempted various scripts but have had no luck in getting the desired effect. Can anyone identify what might be causing the issue? $("a").click(function () { if ($(this).hasClass("acti ...

Dygraphs.js failing to display the second data point

My website features a graph for currency comparison using Dygraphs. Everything was working fine until I encountered this strange issue. https://i.stack.imgur.com/OGcCA.png The graph only displays the first and third values, consistently skipping the seco ...

Angular 2 is not recognizing the element 'router-outlet'

I am currently utilizing universal-cli... This is how my app.node.module.ts appears: /** * This file and `main.browser.ts` are quite similar, for now! * By separating these, you can create logic, imports, etc that are "Platform" specific. * If you wis ...

Executing a function a specific number of times in Jquery

I have a query regarding JQuery related to randomly placing divs on a webpage. The issue I'm facing is that it currently does this indefinitely. Is there a way to make it run for a specific duration and then stop? $(document).ready(function () { ...

The dropdown login form is malfunctioning on my Wordpress website

After reading various tutorials and guides online, I managed to set up a login screen. You can view the code in my jsfiddle: Jsfiddle. Unfortunately, I am facing issues with making the code function correctly. Being new to Jquery, I might have made a begin ...