简体   繁体   中英

How to Syncing Content With HTML5 Video using javascript?

I have a form which contains some input fields name, email etc, I have a video (which I can not post it here) which contains a girl saying, eg email is wrong please enter a new email, password is not correct enter a correct password, name is taken please enter a new name etc,

So I want when a user enter a name instead of displayed message eg good name , I want to play a video saying 'ooh that is good name' and vice versa,

here is jsfiddle for reference: validation message using video

here is what I have so far

<!--PEN CODE-->
<div id="contactForm" class="contactForm">
    <div id="formHeader" class="formHeader">
        <h1 id="message">Contact Me</h1>
    </div>
    <div id="formBody" class="formBody">
        <form action="" method="POST" name="contactForm">
            <div class="inputContainer">
                <label for="userName">
                    <i class="fa fa-lg fa-fw fa-user"></i>
                </label>
                <input name="name" id="userName" type="text" placeholder="John Smith">
            </div>
            <div class="inputContainer">
                <label for="userEmail">
                    <i class="fa fa-lg fa-fw fa-envelope"></i>
                </label>
                <input name="email" id="userEmail" type="email" placeholder="jsmith@domain.com">
            </div>
            <div class="inputContainer">
                <textarea name="feedback" id="userMessage" rows="10" placeholder="Enter your message"></textarea>
            </div>
            <input id="submitBtn" class="submitBtn" type="submit" value="Send">
        </form>
    </div>
</div>
<center><p><em>NOTE: This form is for presentation only. Any form data entered is not submitted</em></p></center>
<!--END PEN CODE-->


    <div class="video=wrapper">

      <video id="video1" width="420">
    <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
  </video>


    </div>

Here is js I have so far

(function() {
    "use strict";
    var //GLOBAL VARIABLES
    input,
            container,
            //CSS CLASSES
            classSuccess = "success",
            classError = "error",
            //FORM VALIDATOR
            formValidator = {
                init: function() {
                    this.cacheDom();
                    this.bindEvents();
                },
                cacheDom: function() {
                    //MAIN PARENT ELEMENT
                    this.contactForm = document.getElementById("contactForm");
                    //MAIN FORM ELEMENTS
                    this.formHeader = document.querySelector("#formHeader h1");
                    this.formBody = document.getElementById("formBody");
                    this.inputContainer = document.getElementsByClassName("inputContainer");
                    //USER INPUT ELEMENTS
                    //INPUT FIELDS
                    this.fields = {
                        userName: document.getElementById("userName"),
                        userEmail: document.getElementById("userEmail"),
                        userMessage: document.getElementById("userMessage")
                    };
                    this.submitBtn = document.getElementById("submitBtn");
                },
                bindEvents: function() {
                    var i;
                    //RUN RULES ON SUBMIT BUTTON CLICK
                    this.submitBtn.onclick = this.runRules.bind(this);
                    //BIND EVENTS TO EACH INPUT FIELD
                    for (i in this.fields) {
                        if (this.fields.hasOwnProperty(i)) {
                            //VARIABLES
                            input = this.fields[i];
                            container = input.parentElement;
                            //RUN RULES WHEN INPUT HAS FOCUS
                            input.onfocus = this.runRules.bind(this);
                            //RESET ERRORS WHEN CONTAINER IS CLICKED
                            container.onclick = this.resetErrors.bind(this, input);
                        }
                    }
                },
                runRules: function(evnt) {
                    var target = evnt.target,
                            type = evnt.type;
                    //IF EVENT ON SUBMIT BUTTON
                    if (target === this.submitBtn) {
                        //PREVENT FORM SUBMITTION
                        this.preventDefault(evnt);
                        //IF INPUT HAS FOCUS
                    } else if (type === "focus") {
                        //RESET CLASSLIST
                        this.resetClassList(target.parentElement);
                        //RESET ERRORS
                        this.resetErrors(target);
                        return false;
                    }
                    //RESET CLASSLIST
                    this.resetClassList();
                    //CHECK FIELDS
                    this.checkFields();
                },
                preventDefault: function(evnt) {
                    //PREVENT DEFUALT
                    evnt.preventDefault();
                },
                checkFields: function() {
                    var i,
                            validCount = 0,
                            //EMAIL FILTER
                            filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                    //CYLCE THROUGH INPUTS
                    for (i in this.fields) {
                        if (this.fields.hasOwnProperty(i)) {
                            input = this.fields[i];
                            //CHECK IF FIELD IS EMPTY
                            if (input.value === "") {
                                //ADD ERROR CLASS
                                this.addClass(input, classError);
                                //CHECK IF EMAIL IS VALID
                            } else if (i === "userEmail" && !filter.test(input.value)) {
                                //ADD ERROR CLASS
                                this.addClass(input, classError);
                            } else {
                                //FIELD IS VALID
                                this.addClass(input, classSuccess);
                                validCount += 1;
                            }
                        }
                    }
                    //IF ALL FEILDS ARE VALID
                    if (validCount === 3) {
                        //SUBMIT FORM
                        this.submitForm();
                    }
                },
                addClass: function(input, clss) {
                    container = input.parentElement;
                    //IF INPUT HAS ERROR
                    if (clss === classError) {
                        //SHOW ERROR MESSAGE
                        this.errorMessage(input);
                    }
                    //ADD CLASS
                    input.parentElement.classList.add(clss);
                },
                errorMessage: function(input) {
                    var message;
                    //IF USERNAME HAS ERROR
                    if (input === this.fields.userName) {
                  //grab data from video and interact it with html5 form
                  var videoElement = document.getElementById('video1')[0];
                  videoElement.addEventListener('loadmetadata', function(){
                  this.currentTime =20;
                }, false)

                        //ELSE IF USEREMAIL HAS ERROR
                    } else if (input === this.fields.userEmail) {
            //grab data from video and interact it with html5 form
            var videoElement = document.getElementById('video1')[0];
            videoElement.addEventListener('loadmetadata', function(){
            this.currentTime =70;
          }, false)
                        //ELSE IF USERMESSAGE HAS ERROR
                    } else if (input === this.fields.userMessage) {
            //grab data from video and interact it with html5 form
            var videoElement = document.getElementById('video1')[0];
            videoElement.addEventListener('loadmetadata', function(){
            this.currentTime =50;
          }, false)
                    }
                    this.renderError(input, message);
                },
                renderError: function(input, message) {
                    var html;
                    //GET INPUT CONTAINER
                    container = input.parentElement;
                    //RENDER HTML
                    html = document.createElement("div");
                    html.setAttribute("class", "message");
                    html.innerHTML = message;
                    //IF MESSAGE ELEMENT DOESN'T EXIST
                    if (!container.getElementsByClassName("message")[0]) {
                        //INSERT MESSAGE TO INPUT CONTAINER
                        container.insertBefore(html, container.firstElementChild);
                    }
                },
                resetClassList: function(input) {
                    var i;
                    //IF TARGETING SPECIFIC INPUT
                    if (input) {
                        //GET INPUT CONTAINER
                        container = input.parentElement;
                        //REMOVE CLASSES
                        container.classList.remove(classError, classSuccess);
                        //FOCUS ON INPUT FIELD
                        input.focus();
                    } else {
                        for (i in this.fields) {
                            if (this.fields.hasOwnProperty(i)) {
                                //REMOVE CLASSES FROM ALL FIELDS
                                this.fields[i].parentElement.classList.remove(classError, classSuccess);
                            }
                        }
                    }
                },
                resetErrors: function(input) {
                    //GET INPUT CONTAINER
                    container = input.parentElement;
                    //IF CONTAINER CONTAINS ERROR
                    if (container.classList.contains(classError)) {
                        //RESET CLASSES
                        this.resetClassList(input);
                    }
                },
                submitForm: function() {
                    var waitForAnimation;
                    //ADD SUCCESS CLASS
                    this.contactForm.classList.add(classSuccess);
                    //WAIT FOR ANIMATION TO FINISH
                    this.changeHeader("Sent Succesfully");
                    //WAIT FOR ANIMATION TO FINISH
                    setTimeout(this.changeHeader.bind(this, "Thank you for your feedback"), 1200);
                },
                changeHeader: function(text) {
                    //CHANGE HEADER TEXT
                    this.formHeader.innerHTML = text;
                }
            };


    //INITIATE FORM VALIDATOR
    formValidator.init();


}());

**

NOTE: you can use any video , the important is working solution

**

unfortunatelly this is not working as expected

What am I doing wrong in my code?

First, it looks like you are mixing jQuery code with native JS. you are not selecting the video element with:

document.getElementById("video1")[0];

That requires this:

document.getElementById("video1");

Next, you set an event listener on an element that may or may not ever get fired. Let's make sure our event handler can get fired by forcing a video fetch.

You have a lot going on in your sample, so I broke this down to the smallest bits.

  1. The button emulates a form field being in error.
  2. Next, load the video so the canplay event fires.
  3. Then capture a click of the button and set the video URL to force the video load
  4. Finally, use Async/Await and play the video.
    • Note: the video may not play if the user agent prevents it from doing so

 let vidElement = document.getElementById('video1'); vidElement.addEventListener('canplay', playVideo); document.querySelector('button').addEventListener('click', loadvideo); function loadvideo() { vidElement.src = "https://www.w3schools.com/html/mov_bbb.mp4"; } async function playVideo() { vidElement.currentTime = 70; console.log("Playing video from: ", vidElement.currentTime); await vidElement.play().catch(e => console.log("error: ", e.message)); } 
 <button>Make Form Error</button> <br> <video id="video1" width="420"> <source type="video/mp4"> </video> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM