It seems that this code is normally working but on this situation, there's a lot of code of JavaScript in 3 boxes only. However, I want more boxes but I want to make the code shorter, it is possible?
function showBTN_A() {
var a = document.getElementsByClassName("Btn");
a[0].style.display = "block";
a[1].style.display = "none";
a[2].style.display = "none";
}
function showBTN_B() {
var a = document.getElementsByClassName("Btn");
a[0].style.display = "none";
a[1].style.display = "block";
a[2].style.display = "none";
}
function showBTN_C() {
var a = document.getElementsByClassName("Btn");
a[0].style.display = "none";
a[1].style.display = "none";
a[2].style.display = "block";
}
function hideBTN() {
var a = document.getElementsByClassName("Btn");
a[0].style.display = "none";
a[1].style.display = "none";
a[2].style.display = "none";
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
width: 100%;
height: 100vh;
align-items: center;
}
.wrapper {
display: flex;
width: 90%;
flex-direction: column;
}
.Box {
width: 90%;
margin: auto;
height: 180px;
background: blue;
margin-top: 10px;
display: flex;
justify-content: center;
align-items: center;
}
.Btn {
background: white;
border: none;
color: blue;
font-weight: bold;
font-size: 20px;
padding: 8px;
display: none;
}
<div class="wrapper">
<div onmouseover="showBTN_A()" onmouseout="hideBTN()" class="Box">
<button class="Btn">Click Here</button>
</div>
<div onmouseover="showBTN_B()" onmouseout="hideBTN()" class="Box">
<button class="Btn">Click Here</button>
</div>
<div onmouseover="showBTN_C()" onmouseout="hideBTN()" class="Box">
<button class="Btn">Click Here</button>
</div>
</div>
I used onmouseover to make button display on their respective Boxes, then if the mouse move out from boxes, the button will gone.
Again, the only problem for this is how to make the code shorter so that I apply it on no matter how many boxes do I have.
You don't need any JS for this. To show the button when the box is hovered you can use the CSS
:hoverpseudo-selector:Here's a working example: