javascripthtmlonmouseoveronmouseout

Autoplay on MouseOver


OBJECTIVE: Trying to autoplay when mouse is over the video itself.

HTML:

<video id = "litVideo" src="lt.mp4" onmouseover="over(this)" onmouseout="out(this)" controls>

JAVASCRIPT:

function over(element) {
    alert("mouseover");
    element.append(autoplay)
   **also tried element.add(autoplay)**
}
    
function out(element) {
    alert("mouseout");
    element.remove(autoplay);  
}

Problem: Mouseover is alerting. However, autoplay is not working. Please help.


Solution

  • use play() and pause() function

        const video = document.getElementById("video")
        video.onmouseover = function(){
            video.play()
        }
        video.onmouseout = function(){
            video.pause()
        }
    <video src="https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4" controls id="video"></video>

    However if you want to use your approach then use

    element.setAttribute("autoplay")