<div class="boxes">
<div class="box">1</div>
<div id="targetBox" class="box">2</div>
</div>
<div class="controls">
<button id="btn">Toggle Box 2 Position</button>
</div>
:root {
--spacer: 1.5rem;
}
body {
align-items: center;
background: #333;
display: flex;
flex-direction: column;
justify-content: center;
height: 100vh;
padding: var(--spacer);
}
.boxes {
background: rgba(255, 255, 255, 1);
display: flex;
padding: var(--spacer);
}
.box {
align-items: center;
display: flex;
height: 200px;
justify-content: center;
width: 200px;
}
.box:first-child {
background: #ff8a00;
}
.box:nth-child(2) {
background: #e52e71;
}
.absolute {
position: absolute;
}
.controls {
margin-top: var(--spacer);
}
let box = document.getElementById("targetBox").classList;
let button = document.getElementById("btn");
function positionBox() {
if (box.contains("absolute")) {
box.remove("absolute");
} else {
box.add("absolute");
}
}
button.addEventListener("click", positionBox);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.