Search code examples
hoverhidden

Added hidden element, but now my hover effect doesn't work anymore


I have a problem with my javascript code, I made a hover effect for a text to play a video. but now I want to hide the video when you not hover the text. when I'm adding a hidden element, the hover effect does not work anymore...

Do you guys know the solution?

<script type="text/javascript">

var Htext=document.getElementById("Htext");
var Hvideo=document.getElementById("Hvideo");

function PauseH(){
    Hvideo.pause();
}

function PlayH(){
if(Hvideo.paused)
    Hvideo.play();
    
}

if(Hvideo.pause){
    Hvideo.hidden = true;
}else{
    Hvideo.hidden = false;
}
</script>

<div>
<video id="Hvideo" width="320" height="240" preload="auto">
    <source src="URL will be added" type="video/mp4">
</video>
<button id="Htext" onmouseover="PlayH()" onmouseout="PauseH()">HVAC</button>

</div>

Solution

  • your code appears to be essentially working:

    https://www.w3schools.com/code/tryit.asp?filename=GMLBBYWJV4I2

    <div>
    
    <button id="Htext" onmouseover="PlayH()" onmouseout="PauseH()">HVAC</button>
    
    </div>
    
    <video id="Hvideo" width="320" height="240" controls>
      <source src="https://www.w3schools.com/jsref/movie.mp4" type="video/mp4">
      <source src="https://www.w3schools.com/jsref/movie.ogg" type="video/ogg">
      Your browser does not support the video tag.
    </video>
    
    <script>
    var Htext=document.getElementById("Htext");
    var Hvideo=document.getElementById("Hvideo");
    
    function PauseH(){
        Hvideo.pause();
        Hvideo.hidden = true;
    }
    
    function PlayH(){
      if(Hvideo.paused) {
        Hvideo.play();
        Hvideo.hidden = false;
      }    
    }
    
    </script>
    

    I do wonder if the issue is down to the fact that you need the HTML elements to exist before you run your JavaScript, and it will fail if the JavaScript runs before the elements appear on the page.