Document.querySelector failing to execute the if statement properly

Currently, I am working on implementing a hamburger menu functionality. The basic setup involves creating a menu that transforms into a cross icon when clicked, and this part is functioning correctly.

function drop(){
let bars = document.querySelector("div.bar");
let cross = document.querySelector("div.cross");
bars.style.display = "none";
cross.style.display = "flex";
}
div.bar {
    display: flex;
    transition: 1s;
    cursor: pointer;
    justify-content: space-between;
    flex-direction: column;
    height: 30px;
    color: gray;
}

.ibar {
    display: inline-flex;
    width: 40px;
    height: 5px;
    background-color: black;
    border-radius: 31%;
}

.cross{
    display: none;
    justify-content: center;
    align-items: center;
    width: fit-content;
    font-size: 70px;
    color: gray;
}
<div class="bar" id="bar" onclick="drop()">
    <div class="ibar"></div>
    <div class="ibar"></div>
    <div class="ibar"></div>
</div>
<div class="cross" id="hiddenCross">&times;</div>

However, I have encountered a significant issue:

The problem arises when I attempt to add an if statement within my function like so:

if (cross.style.display === "none"){
    bars.style.display = "none";
    cross.style.display = "flex";
}

In this scenario, the two lines of code inside the if block do not execute as intended to change the display properties.

Initially, I suspected it might be due to a limitation of the document.querySelector property causing this unexpected behavior. However, even after using IDs to trigger the same function, the issue persists.

Answer №1

When inspecting elements, only inline styles are considered by the style property. It is advisable to utilize getComputedStyle instead as it captures all CSS rules.

function toggleDisplay(){
let containers = document.querySelectorAll("div.container");
let toggler = document.querySelector("button.toggle");
if (window.getComputedStyle(toggler).display === "none"){
containers.forEach(container => {
  container.style.display = "none";
});
}
}
div.container {
    display: flex;
    transition: 1s;
    cursor: pointer;
    justify-content: space-between;
    flex-direction: column;
    height: 30px;
    color: gray;
}

.item {
    display: inline-flex;
    width: 40px;
    height: 5px;
    background-color: black;
    border-radius: 31%;
}

.toggler{
    display: none;
    justify-content: center;
    align-items: center;
    width: fit-content;
    font-size: 70px;
    color: gray;
}
<div class="container" id="mainContainer" onclick="toggleDisplay()">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>
<button class="toggler" id="hideButton">Hide</button>

Answer №2

Each time the hamburger is clicked, the drop() function is triggered. Within this function, the style.display property of the "cross" element is set to flex. However, the code within the if statement will only run when the style.display property of the "cross" element is set to none, which never occurs. One solution is to use an additional class, such as "hidden," and toggle it each time the menu is clicked: if the bar has the "hidden" class, the cross should also have this class and vice versa. In the CSS file, the "hidden" class should have the display: none property.

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

Encountered an issue during deployment with Vercel: The command "npm run build" terminated with exit code 1 while deploying a Next.js web application

I've been working on a local Next.js app, but encountered an error when deploying it. Vercel Deployment Error: Command "npm run build" exited with 1 Here is the log from the build process: [08:26:17.892] Cloning github.com/Bossman556/TechM ...

Updating CSS class within a div tag utilizing ASP.NET (C#)

How can I dynamically update the properties of a CSS class using C#? I need to change the background image, font size, font style, and font based on user input through an interface. Once the changes are saved, I store them in a database. However, when the ...

Having trouble with conditional statements in jQuery when handling ajax responses?

I am currently working with the following code: $.ajax({ url: 'upload.php', //Server script to process data type: 'POST', xhr: function() { // Custom XMLHttpRequest var myXhr = $.ajaxSettings.xhr(); if(myX ...

Why is the fog in three.js not showing up?

Having trouble getting fog to render in my scene - any suggestions? I've scoured the internet for solutions, but can't seem to find any that work. Check out this screenshot to see the issue: https://i.sstatic.net/ThJRh.png Here is the code sni ...

Implementing a dynamic header image that adjusts its resolution based on the device and pixel density for

After finishing a design in Sketch, I have 3 unique layouts with header images displayed below: https://i.sstatic.net/fG5T3.png To ensure the height is consistent and to crop the image appropriately on different devices, I export the following images fro ...

Understanding the reach of 'this' in a React component written in ES6

I'm struggling to grasp the concept of the scope of this within ES6 classes. Consider this component: export default class App extends React.Component { constructor(props) { super(props); this.state = { credentials: { v: &apo ...

I can't seem to get my code to work more than once

My code seems to be working only once. This is the HTML code snippet I am using: <span id="0" class="add-title">add title</span> And here is my JavaScript code: jQuery(document).ready(function($) { var iTitlesArray = []; $(document ...

Accessing confidential information from a server-side application like Node.js (express) or Asp.net-core to be displayed on the client-side using Angular

My belief is that I will receive an HTML form through a POST method which will contain a token, and I need to catch it on the server side. app.post('/callback', (req, res)=> { var token = req.body.access_token res.cookie('acc ...

Changing the Color of a Table Cell with jQuery

I have designed a table cell in the following way <tr> <td id = 'even'>row 8, cell 1</td> <td id = 'odd'>row 8, cell 2</td> </tr> The colors and font sizes are defined using the CSS below #even { ...

Trouble with jQuery event.keyCode in detecting alphanumeric characters

I recently developed a script that is supposed to detect the key the user clicks and perform an action based on whether it is alphanumeric. However, I am encountering an issue as the script does not seem to be working as expected, and I am not receiving an ...

What is the process for incorporating a unique Mongo expression into a JSON object?

I'm currently trying to figure out how to add a specific Mongo command to my JSON object. Normally, adding regular strings or objects is straightforward, but I'm struggling with this particular command: $set : { "author" : req.body.name } Simpl ...

Error is caused by state variable triggering mutation

In my store module, I am encountering an issue with the following pseudo-code: const state = { users: [] } const actions = { addUsers: async ({commit, state}, payload) => { let users = state.users // <-- problem // fetching new users fo ...

The Ajax request encountered a syntax error due to an unexpected token '<'

I have searched the forum extensively for similar questions, but unfortunately haven't found a suitable answer for my specific problem. In my jQuery code, I am attempting to make an AJAX call using the following snippet: function submitForm(formData) ...

Ways to apply jquery.validate rules that have already been defined to form fields that are added dynamically

I need to duplicate a specific section of a form and apply the same validation rules that were set up before. After researching this issue, I found that most recommendations suggest adding new rules to the newly generated elements. Therefore, I attempted ...

Client sites are not displaying any data through sockets

My goal is to transmit data using socket.io from my nodejs server to the client. The data I am receiving originates from pusher. I have an express backend and set up my server like this: #!/usr/bin/env node var debug = require('debug')('t ...

Making a Django template recognize the load tag when inheriting from a base template involves ensuring proper syntax and file

My current setup involves a file called base.html. {% load static from staticfiles %} <html> <title>COOL| {% block title %} Sometitle {% endblock %}</title> <body> <!--- BEGIN INSERT CONTENT FOR OTHER PAGE HERE--> ...

Divide the full width into three divisions, each taking up 33% of the total width

I have been experimenting with using 3 divs to create a table-like layout with 3 columns. I set each div to occupy 33% of the width of the page, and it worked well until I tried to add padding to move the text away from the border. This caused the third di ...

What is the best way to understand and decipher this CSS code?

As I delve into customizing the CSS of an Internet theme, I am faced with a syntax that is unfamiliar and puzzling to me. One example from the theme is as follows: @media screen and(max-width: 768 px) { .wy-tray-container { bottom: auto;top: 0; ...

Retrieve the link's "href" attribute and its text if they match the specified text

Is there a way to extract the href link and text from a specific type of link? <a href="google.com">boom</a> I am looking to retrieve only the 'google.com' part and the text 'boom' Furthermore, how can I filter out other ...

Looking to incorporate HTML5 videos into a responsive Bootstrap carousel?

I've been working on creating a carousel that includes videos. When it comes to images, everything works smoothly as they are responsive even in mobile view. However, I'm encountering an issue with videos where the width is responsive but the hei ...