0

I have input element and paragraph element, I want the p element to be displayed only on hovering over the input element.

Here is what I tried

<html>
 <body>
 <div class="overlay">
   <input id="inputCustomer" value="sometext">
 </div>
 <div class="content">
  <p id="spandiv">This the p element</p>
 </div>
 </body>
 <style>
    #spandiv {
        background-color: #232F34;
        color:#FFFFFF;
        opacity:0;
    }

    #inputCustomer:hover + #spandiv {
    display: block;
    opacity:1;
    }

 </style>
</html>
Tân
  • 1
  • 15
  • 56
  • 102
karansys
  • 2,449
  • 7
  • 40
  • 78

2 Answers2

2

To use plus sign, you must put all of the selectors in the same level:

#spandiv {
    background-color: #232F34;
    color:#FFFFFF;
    opacity:0;
}

#inputCustomer:hover + #spandiv {
    display: block;
    opacity:1;
}
<div class="overlay">
   <input id="inputCustomer" value="sometext">
   <p id="spandiv">This the p element</p>
 </div>

JavaScript version (to use them in different levels):

document.getElementById('inputCustomer').addEventListener('mouseover', function () {
  document.getElementById('spandiv').style.opacity = 1;
});

document.getElementById('inputCustomer').addEventListener('mouseout', function () {
  document.getElementById('spandiv').style.opacity = 0;
});
#spandiv {
    background-color: #232F34;
    color:#FFFFFF;
    opacity: 0;
}
 <div class="overlay">
   <input id="inputCustomer" value="sometext">
 </div>
 <div class="content">
  <p id="spandiv">This the p element</p>
 </div>
Tân
  • 1
  • 15
  • 56
  • 102
1

By using mouseenter (add class .show to the paragraph) and mouseleave (remove class .show from the paragraph). In the style you can define class .show

<style>
#spandiv {
  display: block;
  background-color: #232f34;
  color: #ffffff;
  opacity: 0;
}
#spandiv.show {
  opacity: 1;
}
</style>

<div class="overlay">
  <input id="inputCustomer" value="sometext">
</div>
<div class="content">
  <p id="spandiv">This the p element</p>
</div>

<script>
var input = document.getElementById("inputCustomer");
var paragraph = document.getElementById("spandiv");
input.addEventListener("mouseenter", function(e) {
  paragraph.classList.add('show');
});
input.addEventListener("mouseleave", function(e) {
  paragraph.classList.remove('show');
});
</script>
bron
  • 1,457
  • 1
  • 9
  • 18