The button designed to execute JavaScript and modify CSS is malfunctioning

I am trying to use a button to expand my sidenav by toggling the class with JQuery.

Although I am more familiar with JavaScript, I attempted to solve it with JS before moving to JQuery.

function toggleMenu() {
        var sideEle = document.getElementById("sidebar-wrapper");
        var mainEle = document.getElementById("page-content-wrapper");
        sideEle.classList.toggle("sideMenuDisplayed");
        mainEle.classList.toggle("bodyMenuDisplayed");
    };

I added onclick="toggleMenu()" to the button html, but it did not work. I also added borders to both the before and after to check for class changes while debugging.

Here is my current code using JQuery

$(document).ready(function() {
      $('#menu-toggle').on('click', function() {
        $('#sidebar-wrapper').toggleClass('sideMenuDisplayed');
      });
#sidebar-wrapper {
  z-index: 1;
  position: absolute;
  width: 0;
  height: 100%;
  overflow-y: hidden;
  background: #f07878;
  border: 2px solid red;
  opacity: 0.9;
}

.sideMenuDisplayed {
  width: 250px;
  border: 2px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<div class="wrapper">
  <!-- Sidenav -->
  <div id="sidebar-wrapper">
    <ul class="sadebar-nav">
      <li><a href="/account">Account</a></li>
      <li><a href="/blog">blog</a></li>
      <li><a href="/contact">Contact me!</a></li>
    </ul>
  </div>
  <!-- Page Content -->
  <div id="page-content-wrapper">
    <div class="col-1">
      <button class="btn" id="menu-toggle"><i class="fas fa-bars fa-2x" id="homeIcon"></i></button>
    </div>

    <div class="container" id="homeContainer">
      <p>my content</p>
    </div>
  </div>

When I press the button, there are no errors in the console, and the page does not change. The button should toggle the class of #sidebar-wrapper and change its properties to width: 250px; and border color to blue

Answer №1

Your code already has the class toggling functionality implemented.

You can confirm this by checking the class of the element in the developer tools.

Remember, CSS ID selectors take precedence over class selectors. This concept is known as Specificity.

The specificity of selectors increases in the following order:

  • Type selectors (e.g., h1) and pseudo-elements (e.g., ::before).
  • Class selectors (e.g., .example), attribute selectors (e.g.,[type="radio"]), and pseudo-classes (e.g., :hover).
  • ID selectors (e.g.,#example).
  • Universal selector (*), combinators (+, >, ~, ' ', ||), and negation pseudo-class (:not()) do not affect specificity. However, selectors within :not() do have an impact.

For instance, in your code, the #sidebar-wrapper has a specificity score of 1000, while .sideMenuDisplayed scores only 100. You can utilize class selectors as you have done or enhance the specificity to achieve the desired style toggle.

Below is the same code implemented using only class selectors:

document.getElementById('menu-toggle').addEventListener('click', toggleMenu);

function toggleMenu() {
        var sideEle = document.getElementById("sidebar-wrapper");
        var mainEle = document.getElementById("page-content-wrapper");
        sideEle.classList.toggle("sideMenuDisplayed");
        mainEle.classList.toggle("bodyMenuDisplayed");
    }
.sidebar-wrapper{
 z-index: 1;
    position: absolute;
    width: 0;
    height: 100%;
    overflow-y: hidden;
    background: #f07878;
    border: 2px solid red;
    opacity: 0.9;
    top: 100px; /* add this because the content is masking the button here*/
}
.sideMenuDisplayed {
    width: 250px;
    border: 2px solid blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id="homeBody">

<div class="wrapper">
<!-- Sidenav -->
    <div id="sidebar-wrapper" class="sidebar-wrapper">
        <ul class="sadebar-nav">
            <li><a href="/account">Account</a></li>
            <li><a href="/blog">blog</a></li>
            <li><a href="/contact">Contact me!</a></li>
        </ul>
    </div>
<!-- Page Content -->
<div id="page-content-wrapper">
        <div class="col-1">
            <button class="btn" id="menu-toggle"><i class="fas fa-bars fa-2x" id="homeIcon"></i></button>
        </div>

    <div class="container" id="homeContainer">
           <p>my content</p>
        </div>
</div>

Answer №2

Kindly make adjustments to the codes provided below :

styling

#sidebar-wrapper.sideMenuDisplayed {
    width: 250px;
    border: 2px solid blue;
}
#menu-toggle {
    position: relative;
    z-index: 9;
}

jQuery

<script>
    $(document).ready(function () {
        $('#menu-toggle').on('click', function () {
          $('#sidebar-wrapper').toggleClass('sideMenuDisplayed');
        });
    });
</script>

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

Layer several divs inside a main div

I'm grappling with a simple issue and could use some help to resolve it. Utilizing bootstrap, below is my CSS and div structure. How can I achieve an overlap of DIV 1, DIV 2, and DIV 3? Essentially, I want to position them on the same level, one behi ...

angular 2 text box clearing functionality appears to be malfunctioning

I am currently working on implementing a reusable search box in Angular 2. Although the code is relatively basic, I am new to Angular 2 but have some experience with Angular 1. I am facing an issue where the value is not clearing when the text box is foc ...

Determining where to implement the API display logic - on the server side or

Currently, I am in the process of restructuring an API that deals with user profiles stored in one table and profile images in another. The current setup involves querying the profiles table first and then looping through the images table to gather the ass ...

Struggling to send formData to AJAX for uploading files

My current code involves sending a file from a form to a PHP script and then taking action based on the script's response: <script> function upload_img() { var formData = new FormData($('img_form')[0]); console.log(formData); alert("H ...

JSON Date Format

I'm facing an issue where I am unable to retrieve the current date using new Date() because it is in JSON format. This particular code was written using MVC C#. The date appears as \/Date(1531364413000)\/. The dates stored in the database ...

What is the best method for transforming an HTML file into an ICS (iCal) file?

Hello there! I am interested in converting an HTML file (website) to an iCalendar file (iCal). Is this even possible? If so, how can it be achieved? Does anyone have any ideas or recommendations on how to proceed? Thank you in advance! ...

Tips for achieving consistent text and image alignment through CSS styling

My table currently contains a default profile image. Initially, there might not be any text content and I have set up the CSS styling to allow text to wrap around the default image. I am facing an issue when trying to position the image statically in a wa ...

The size of the Tweet button iframe is set at 107 pixels

Has anyone been able to successfully adjust the size of the tweet button generated by Twitter's iframe code? My attempts have resulted in a default width of 107px, but I need it to match the actual button size. I've tried adjusting the CSS proper ...

Error -1 with JSON key

I've been tirelessly seeking the solution to this issue, but it eludes me. My goal is to retrieve the value by index of a JSON string. Despite the matching key, I'm getting -1 for the index. All I want is the value "Ethan" for the key username. ...

Leveraging the power of moment to properly display time in relation to the present

Is there a way to format dates like "a few seconds ago", "10 minutes ago", "a day ago" using momentjs in the browser? var date = moment('2017-01-10T13:53:00'); date = moment(date).fromNow(); When I use date, it shows "in 14 minutes" instead of ...

A Promise is automatically returned by async functions

async saveUserToDatabase(userData: IUser): Promise<User | null> { const { username, role, password, email } = userData; const newUser = new User(); newUser.username = username; newUser.role = role; newUser.pass ...

tips for aligning bootstrap flex items horizontally in multiple div containers

Is there a more efficient method to align flex items in different div flex containers so that the flex items have the same width, as shown below? <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" ...

Utilize JSON parsing with AngularJS

My current code processes json-formatted text within the javascript code, but I would like to read it from a json file instead. How can I modify my code to achieve this? Specifically, how can I assign the parsed data to the variable $scope.Items? app.co ...

Nested Promise.all within another Promise.all appears to terminate prematurely, triggering a warning indicating failure to return from a promise

I am utilizing this function to be invoked within another Promise.all. However, I consistently encounter a warning message: Caution: a promise was generated in a handler but was not returned from it. Additionally, the function deleteFutureAppointments() ap ...

What is the best way to set a background image that covers the entire screen while eliminating any borders on the sides using React and Material UI?

Working with Material-UI in React, I am attempting to set a background image behind a Paper component on the login page. Despite setting the image's backgroundSize to cover, there is still a white edge on the left and right sides of the screen. Below ...

Adding a class to an element can be easily achieved when both input fields have values

Is it possible to apply the "active" class to the element go_back_right only when both inputs with classes search_box_name and search_box_id have content in them? I've tried looking for solutions on this platform, but being new to JavaScript, I couldn ...

Is there a way to divide my time during work hours using Javascript?

This is just a simple example. 9.00 - 18.00 I am looking to modify the schedule as follows: 9.00 - 10.00 10.00 - 11.00 11.00 - 12.00 12.00 - 13.00 13.00 - 14.00 14.00 - 15.00 15.00 - 16.00 16.00 - 17.00 17.00 - 18.00 The current code implementation see ...

Is there a way to verify if an AJAX request calls HTML content?

Here is the HTML code for a mosaic of images. <div id="container"> <img id="1" /> ... <img id="20" /> </div> This script creates a mosaic layout from the images on the page after it has loaded or been resized. <script& ...

Embed PHP PDO using AJAX

I've been stuck for days now, unable to solve what should be a simple problem. My goal is to perform a basic insert operation using ajax. Even though I am new to PHP, I have gone through numerous examples, studied POST requests in HTTP and PHP, revie ...

Should buttons be wrapped based on the text of the link?

I'm struggling to include buttons in my design but I can't seem to achieve the desired outcome. The image below illustrates what I am attempting to create but have been unsuccessful in replicating: https://i.sstatic.net/CnYLV.png However, the ...