I want to resize multiple boxes together using javascript or jquery.
For this purpose, I wrote a code that changes the size of the desired box by adding or removing the class.
The code I wrote works correctly but the only problem is that it only affects the first box and the other boxes don’t react at all.
The codes I wrote are as follows:
let Box = document.querySelector(".box");
let btn_one = document.querySelector(".btn_one");
btn_one.addEventListener("click", function () {
$(Box).removeClass("box_two");
$(Box).removeClass("box_three");
})
let btn_two = document.querySelector(".btn_two");
btn_two.addEventListener("click", function () {
$(Box).addClass("box_two");
$(Box).removeClass("box_three");
})
let btn_three = document.querySelector(".btn_three");
btn_three.addEventListener("click", function () {
$(Box).addClass("box_three");
$(Box).removeClass("box_two");
})
.main-BOX {
box-shadow: 0 0 4px #000;
width: 500px;
height: auto;
margin: 3rem auto 5rem;
padding: 10px;
}
.btn_one,
.btn_two,
.btn_three {
font-size: 35px;
background: #93ff8a;
color: #f87070;
border: none;
padding: 10px;
margin: 15px;
border-radius: 50%;
cursor: pointer;
}
.box {
width: 90%;
height: 190px;
box-shadow: 0 0 5px #000;
background: #61cc8b;
margin: 25px;
border-radius: 5px;
}
.box_two {
width: 30%;
height: 240px;
box-shadow: 0 0 5px #3add89;
background: #2572e9;
}
.box_three {
width: 90%;
height: 70px;
box-shadow: 0 0 5px #a2dd3a;
background: #e925dd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="main-BOX">
<button class="btn_one">1</button>
<button class="btn_two">2</button>
<button class="btn_three">3</button>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</section>
2
Answers
You might want to stick to JQuery for this. In vanilla JS,
let Box = document.querySelector(".box")
only selects the first element with the class.box
it finds. You’re better off doinglet Box = $('.box');
JQuery will select all of them.The
let btn_xxx = document.querySelector(".btn_xxx");
are fine, because there are only one of each class in your code.EDIT
Here’s a version that simplifies the
click
event listener, uses no JQuery, and usesdata
attributes instead of classes to assign the styles.I’m hoping this will help give you a starting point.
Here’s a React Hook I use that reacts to the Window Size:
P.S. The imported type is simply this:
I know that you didn’t mention React but hopefully the code will still be helpful.