Suraj Gautam
Suraj Gautam

Reputation: 13

How to display an element on hover over other element

I want to display a button element on hovering another button element but my code doesn't work.

HTML Code

<div class="right-account">
  <button class="btn_login">MY ACCOUNT</button>
    <a href="../products/user_cart.php"><button class="btn_signup">MY CART</button></a><br>
    <button class="pwd_button">Change Password</button>
</div>

CSS Code

.pwd_button{
display: none;
border: 1px solid #13619f;
background: #2371b7;
padding: 5px;
color: white;
font-size: 15px;
}

.btn_login:hover + .pwd_button{
display: block;
}

But this code is not working.

Upvotes: 1

Views: 75

Answers (3)

MarioG8
MarioG8

Reputation: 5961

Or we could do in this alternative way :-D :-P =>

.pwd_button{
display: none;
border: 1px solid #13619f;
background: #2371b7;
padding: 5px;
color: white;
font-size: 15px;

}

.btn_login:hover + .pwd_button{
/*display: inline-block;*/
display: block;
}
<div class="right-account">
        <button class="btn_login">MY ACCOUNT</button>
        <button class="pwd_button">Change Password</button>
        <a href="../products/user_cart.php"><button class="btn_signup">MY CART</button></a><br>
</div>

Upvotes: 0

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23510

Try ti use ~:

const btn = document.querySelector('.btn_login')
const pwd = document.querySelector('.pwd_button')
btn.addEventListener('mouseover', () => {
  pwd.classList.add('showpwd')
})
pwd.addEventListener('mouseleave', () => {
  pwd.classList.remove('showpwd')
})
.pwd_button{
  display: none;
  border: 1px solid #13619f;
  background: #2371b7;
  padding: 5px;
  color: white;
  font-size: 15px;
}

.btn_login:hover ~ .pwd_button{
  display: block;
}
.showpwd {
  display: block;
}
<div class="right-account">
  <button class="btn_login">MY ACCOUNT</button>
  <a href="../products/user_cart.php">
    <button class="btn_signup">MY CART</button>
  </a>
  <br>
  <button class="pwd_button">Change Password</button>
</div>

Upvotes: 2

A Haworth
A Haworth

Reputation: 36664

The problem is that the + combinator selects the immediate sibling and the password button is not the immediate sibling. But it is a sibling so you can do what you want by selecting with the tilda ~

See MDN:

General sibling combinator If you want to select siblings of an element even if they are not directly adjacent, then you can use the general sibling combinator (~).

So use:

.btn_login:hover ~ .pwd_button{
  display: block;
}

.pwd_button {
  display: none;
  border: 1px solid #13619f;
  background: #2371b7;
  padding: 5px;
  color: white;
  font-size: 15px;
}

.btn_login:hover~.pwd_button {
  display: block;
}
<div class="right-account">
  <button class="btn_login">MY ACCOUNT</button>

  <a href="../products/user_cart.php"><button class="btn_signup">MY CART</button></a><br>

  <button class="pwd_button">Change Password</button>

</div>

Upvotes: 0

Related Questions