JavaScript CSS HTML - Click event functioning on a single div

How can I shrink the right side div when the left navigation menu is open? Here are the code examples,

HTML :

<div id="home" class="full"><p>Home</p></div>
<div id="about" class="full"><p>About</p></div>
<div id="portfolio" class="full"><p>Portfolio</p></div>
<div id="skills" class="full"><p>Skills</p></div>
<div id="contact" class="full"><p>Contact</p></div>

Css :

.full{height: 100vh;color: #fff;}
.PageShrink{margin-left: 30vh;}

JS:

const fullPage = document.querySelector('.full');
let menuOpen = false;
menuBtn.addEventListener('click', () => {
  if(!menuOpen) {
    fullPage.classList.add('PageShrink');
    menuOpen = true;
  } else {
    fullPage.classList.remove('PageShrink');
    menuOpen = false;
  }
});

When clicking on the menuBtn to slide in from the left, the Home section shrinks by 30vh as expected. However, it seems that subsequent clicks on About, Portfolio, etc., do not trigger the shrinking effect even though they have the same class applied. The issue only works on the first div i.e., home. Any assistance would be greatly appreciated.

Thank you for your help!

Answer №1

It appears that the issue lies in your JavaScript code. The use of querySelector only targets the first element with that class, so you should consider using querySelectorAll instead. However, keep in mind that this method returns an array of all elements, and any changes made will still only affect the first element. To apply changes to all elements with that class, you need to loop through each one using the following code:

fullPage.forEach(el => el.classList.add('PageShrink'));

const fullPage = document.querySelectorAll('.full');
let menuOpen = false;
menuBtn.addEventListener('click', () => {
  if(!menuOpen) {
    fullPage.forEach(el => el.classList.add('PageShrink'));
    menuOpen = true;
  } else {
    fullPage.forEach(el => el.classList.remove('PageShrink'));
    menuOpen = false;
  }
});

To demonstrate and test:

function caseA() {
  document.querySelector(".test").style.color = "red";
}

function caseB() {
  document.querySelectorAll(".test").style.color = "green";
}

function caseC() {
  document.querySelectorAll(".test").forEach(el => el.style.color = "blue");
}
<ul>
  <li class="test">Test</li>
  <li class="test">Test</li>
  <li class="test">Test</li>
  <li class="test">Test</li>
  <li class="test">Test</li>
</ul>

<button onclick="caseA()">querySelector</button>
<button onclick="caseB()">querySelectorAll</button>
<button onclick="caseC()">querySelectorAll + forEach</button>

You'll notice that "Case A" only targets the first element, while "Case B" will result in an error as querySelectorAll returns an array of elements, not a single element. By using forEach, you can apply your JavaScript command to all elements in the array, ensuring it is executed on every individual element.

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 change the padding that is being inherited from "@ .MuiAlert-icon"?

Is there a method to override the padding inherited from "@ .MuiAlert-icon"? The Chrome inspector indicates that the current padding is set to 7px. .MuiAlert-icon { display: flex; opacity: 0.9; padding: 7px 0; font-size: 22px; ...

Tips for transforming a navigation link pill into a hyperlink:

I am using a Bootstrap Nav-pills with 2 tabs: <ul class="nav nav-pills nav-fill kt-portlet__space-x" role="tablist"> <li class="nav-item"> <a class="nav-link active" data-toggle="pill" href="#menu11"><span> TAB1</span> ...

What is the best way to eliminate specified users from the list of command arguments?

I am looking for a way to remove user mentions from a command's arguments array. Although I tried to follow the instructions in the official Discord JS guide here, the example provided only works if the mention is in a specific argument position. Th ...

What is the best way to utilize v-model to set values within a 2D array?

I would like to populate a 2D array with values using v-model. Here is an example of my array containing objects: [ { first_attribute_value: 'red', second_attribute_value: 'medium', third_attribute_value: 'cotton&apo ...

Creating a central navigation menu for a website

Currently, I am working on incorporating a menu in the center of a webpage (please note that this is not a top navigation menu). Here is the initial setup: https://i.sstatic.net/3arql.png Users are able to click on various menu items to access different ...

Save the values of the first and second characters in two separate variables

Can someone help me with storing the first and second characters of a value in separate variables, id and ccMain, using either jQuery or JavaScript? Below is the HTML code needed to set up the environment: <span id="ccMain">GM</span> ...

HashId plugin for Angular

Currently, I'm attempting to integrate into my Angular project built on the latest version. After discovering this definition file: // Type definitions for Hashids.js 1.x // Project: https://github.com/ivanakimov/hashids.node.js // Definitions by: ...

A JQuery function linked to the click event of the body element triggers another click event right away

$().ready(function(){ $("#move-to").click(function(){ $("body").bind("click",function(){ alert("foo"); }); }); }); Why do I receive an alert message of "foo" immediately after clicking on "move-to"? When I bind the " ...

What is the best way to show a specific page using router-view?

Is it possible to restrict router-view to display content from only one specific page? App.vue <div id="app"> <div class="out-page" v-if="$route.path === '/login'"> <router-view name="login"></router-view> </d ...

Tips for effectively submitting a form to Flask using AJAX

As someone who is new to Python and AJAX, I have encountered an issue with my app.py and app.html files. Instead of displaying the desired result, a whole form is replacing it. Can anyone help me with this problem? Below is the code snippet: from flask i ...

Blender Mesh Not Visible in Three.js

After creating a mesh in Blender, I attempted to use it in three.js. Although the file is being loaded according to the event log, all I see is a black screen. How can I ensure that the mesh actually appears on the screen? import * as THREE from 'thre ...

I am looking for a way to retrieve the ids of all div elements that have the same x coordinate using document.elementFromPoint in JavaScript. Can someone help me with

Currently, I am facing an issue where I have two divs positioned at the same x coordinate. I am attempting to retrieve the IDs of both divs using document.elementFromPoint(). However, I am only able to receive the ID of one div. var elem = document.elem ...

SwipeJS is not compatible with a JQuery-Mobile web application

I am currently attempting to integrate SwipeJS (www.swipejs.com) into my JQuery-Mobile website. <script src="bin/js/swipe.js"></script> <style> /* Swipe 2 required styles */ .swipe { overflow: hidden; ...

Create a roster of numbers that are multiples using a systematic approach

Is the following code a functional way to return multiples of 5? function Mul(start,array,Arr) { Arr[start]=array[start]*5; if(start>array.length-2){ return Arr; } return Mul(start+1,array,Arr); } var numbers =[1,2,3,4,5,6 ...

Performing an action once all AJAX requests have finished

I'm dealing with a situation where I have a click event triggering 3 ajax calls: $("#button").click(function(e) { e.preventDefault(); $.ajax(call1); $.ajax(call2); $.ajax(call3); some_function() //needs to be executed only afte ...

Updating the database table using javascript

I am looking to dynamically update my database based on a condition in JavaScript. Currently, I have been using the following approach: <a href="#" onclick="hello()">Update me</a> <script> function hello(smthing) { if(smthing == true) ...

encountering plupload issue during file upload

While utilizing the Plupload solution to upload multiple files simultaneously, an error message appears in the browser console: NS_ERROR_DOM_BAD_URI: Access to restricted URI denied The code halts at this point: new n.DOMException(n.DOMException.INVALID_S ...

What is the best way to activate ui-sref in an AngularJS unit test?

Currently I am conducting a test on an AngularJS view. The code sample contains some non-standard helpers, but they should not affect the specific functionality being tested. Below is the view (written in Jade): #authentication-options button#sign-up(u ...

Is a Circular Logo Aligned in the Middle of the Navigation Bar?

Just starting out with bootstrap and looking to design a unique navbar with a round logo in the center: https://i.sstatic.net/whLUr.png Finding it a bit tricky, I searched for similar solutions and came across this one. However, implementing that navbar d ...

What specific CSS attribute changes when an element is faded out using jQuery's FadeOut method?

When we make an element fade in or out, which specific CSS property is being altered? Is it the visibility attribute, or the display property? I am hoping to create a code snippet with an if statement condition that reads (in pseudo code): if the div is ...