Search code examples
htmljqueryhtml5-video

jQuery isn't working even though everything seems good to go, what's wrong with my code?


I am trying to write simple jQuery play/pause buttons for a video in html5, but when I go and click the buttons, nothing happens. If you have any code for the play/pause functionality, I'd appreciate that very much.

Here's my code at the moment:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js">
        
        $(document).ready(function() {

            $('#play').click(function(){
                $('#myvid').get(0).play();
            });
        });
    </script>
    <title>Drive</title>
</head>
<body>
   
    <video id="myvid" width="800" height="600">
        <source src="video.mp4" type="video/mp4">
        <track  src="leg.vtt" kind="captions" srclang="en-us" label="english" default>
    </video>

    <br>
    <br>

    <input type="button" value="Play" id="play" />
    <input type="button" value="Pause" id="pause" />
    
</body>
</html>

I've tried multiple different codes but none of them caused nothing on the page, not even errors


Solution

  • Here is my working example of JQuery code to play/pause a video:
    https://codepen.io/sethuramancbe/pen/gOBRjmK

    (1) Define a <script> tag for loading external JS files/libraries (ie: JQuery in this case):

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"> 
    </script>
    

    (2) Then define a separate <script> tag for code that handles Elements on the page:

    <script>
    
    $(document).ready(function() 
    {
        $("#play").click( function() { $("#myvid").trigger("play"); } );
    
        $("#pause").click( function() { $("#myvid").trigger("pause"); } );
    });
    
    </script>