Tips on playing HTML video only when it is in the user's view

Currently, I am working on a TikTok-inspired UI project. However, I am facing an issue where videos do not autoplay when they come into view after scrolling, similar to how it works on TikTok. Here is a demo for reference.

Below is a snippet of my code:


    <div class="parent">
        <div class="vi"> 
            <video class="video-player" id="vid1" controls> <source src="https://writesonic.com/static/landingpage/dist/images/willscheren.mp4" type="video/mp4"> </video>
        </div>
        <div class="vi"> 
            <video class="video-player" id="vid2" controls> <source src="https://writesonic.com/static/landingpage/dist/images/willscheren.mp4" type="video/mp4"> </video>
        </div>
        <div class="vi"> 
            <video class="video-player" id="vid3" controls> <source src="https://writesonic.com/static/landingpage/dist/images/willscheren.mp4" type="video/mp4"> </video>
        </div>
        <div class="vi"> 
            <video class="video-player" id="vid4" controls> <source src="https://writesonic.com/static/landingpage/dist/images/willscheren.mp4" type="video/mp4"> </video>
        </div>
        <div class="vi"> 
            <video class="video-player" id="vid5" controls> <source src="https://writesonic.com/static/landingpage/dist/images/willscheren.mp4" type="video/mp4"> </video>
        </div>
    </div>

    <script>
        function isOnScreen(element)
        {
            var curPos = element.offset();
            var curTop = curPos.top;
            var screenHeight = $(window).height();
            return (curTop > screenHeight) ? false : true;
        }

        if(isOnScreen($('video'))) {
             console.log("")
        };
    </script>

I am looking for a solution to this problem using JavaScript or jQuery. Any help would be greatly appreciated!

Answer №1

Here is one way to do it

let newVideo = document.createElement("video"); /*creating a new video element */
newVideo.id = `unique_ID`;
newVideo.autoplay = true;
newVideo.playsInline = true; /* To ensure proper playback on Safari */

Alternatively, you can use

newVideo.play();

Answer №2

Make sure to include the attribute "autoplay" in every video tag as shown below.

 <video class="video-player" controls **autoplay**> <source src="https://uniquewebsite.com/static/videos/sample.mp4" type="video/mp4" > </video>

Answer №3

In my opinion, it would be more effective to dynamically insert video elements instead of hardcoding links in the HTML code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Scope Data Using a Custom AngularJS Directive

We are completely new to the world of AngularJS and are currently facing a challenge in displaying HTML tooltips from a custom directive within Angular. As beginners in this technology, we are struggling to find the right solution for this issue. Initiall ...

Tips for sending multiple identical POST parameters

Currently, I'm in the process of developing a new user interface for a website that I frequently use. My approach involves utilizing Node.js along with request and cheerio to scrape data from various web pages. However, I've encountered an issue ...

Tips for setting up a scheduled event on your Discord server using Node.js

Hello fellow programmers! Recently, I've been working on a Discord bot using discordjs sdk. I'm trying to implement a feature where the bot creates an event every week. I went through the discordjs guide and checked the discord api documentati ...

My Node/Express service seems to be generating a span in the logs, but I am unable to locate my service in the Ja

Currently, I am in the process of setting up Jaeger tracing for my Node.js microservice using Express.js. After adding a basic GET request handler in my Express app and hitting the endpoint via curl, I notice that a span is created in the logs. However, w ...

Using Jasmine and ReSharper to test TypeScript modules

In my VS2017 project, I have a Jasmine test written in TypeScript: describe("A simple test", () => { it("Should succeed", () => { expect(true).toBeTruthy(); }); }); Everything runs smoothly using the ReSharper test runner. However, when I ...

Despite my efforts to include the necessary key, I am still encountering an error with the item list in

Below is an example of a list container: import { List, ListItemText, ListItem } from '@mui/material'; import FooterItem from './FooterItem'; const FooterList = ({ title, items }) => { return ( <List> ...

Encountered difficulty accessing the controller ActionResult from JavaScript代码

Resolution: After thorough investigation, I successfully identified and resolved the issue. Surprisingly, it was not related to the Javascript or Controller code as initially anticipated. The root cause stemmed from a .dll file that was causing discrepanci ...

Issue with bidirectional binding on angular material slide toggle not functioning as anticipated (Angular 4)

My angular material slide-toggle implementation seems to be working, but I'm facing an issue where it doesn't bind the value to the relevant variable as expected. // other irrelevant imports above.. import {MatDialog, MatDialogRef, MAT_DIALOG_DA ...

Having trouble getting @vercel/ncc to work, keeps throwing a "Module not found" error

Recently, I have been attempting to follow a tutorial on creating custom GitHub actions using JavaScript from here. The tutorial suggests using the @vercel/ncc package to compile code into a single file if you prefer not to check in your node_modules folde ...

TinyMCE file multimedia upload feature allows users to easily add audio, video

I am looking to enhance the functionality of my TinyMCE Editor by enabling file uploads for audio/video and images. Although image uploading is functioning properly, I am encountering issues with other types of files. Despite setting up pickers throughout, ...

Outlook creates unnecessary spacing within tables in emails

Despite all my efforts, I am facing an issue with Outlook adding an unwanted gap after one of my tables in my responsive email design. I have tried various solutions such as adding border-collapse:collapse, dividing tables, and using block styling for imag ...

Changing the background color of tabs in Angular

Being a beginner in HTML and CSS, I recently utilized the angular-tabs-component to create tabs. Now, I am looking to change the background color of the tab. Can someone guide me on how to achieve this? Below is the code snippet: HTML: <tabs (currentT ...

Increase the size of the grid system column upon clicking on a Bootstrap icon

I am using Google Maps in a tab with Bootstrap, but the map is too small. I would like to change the Bootstrap grid system when I click on a FontAwesome icon: the first column should turn into col-md-8, and the second column should become col-md-4. Here i ...

Guidelines for aligning a form in the middle of the screen (positioned between the navigation bar and footer

Before asking this question, I made sure it's not a duplicate by researching previous similar issues with no success. I'm currently utilizing Bootstrap 4. You can view my app at (I'm unable to post the CSS and HTML of my React app due to S ...

JavaScript - Issue with For Loop when Finding Symmetric Difference

Here is my solution to a coding challenge on FreeCodeCamp called "Symmetric Difference." I'm puzzled as to why my code is returning 2, 3, 4, 6 instead of the expected 2, 3, 4, 6, 7. function sym(args) { args = Array.from(arguments); var new ...

What is the manual way to initiate the onclicksubmit event in jqgrid?

Is there a way to manually trigger the onclicksubmit event in jqgrid? If a certain condition is met, I need to programmatically call the submit event. See the code snippet below for reference. afterShowForm: function (formid) { if (condition) { ...

How can I solve the issue of connecting to a database with mysql_connect() in PHP?

While using PHP and AJAX to query a database, I encountered the following error messages: Warning: mysql_query() [function.mysql-query]: A link to the server could not be established... and Warning: mysql_query() [function.mysql-query]: Can't connect ...

Display all items on page load using ng-repeat checkboxes in AngularJS filter

I have encountered a problem with filtering checkboxes in my code. I want all products to load on the page initially, and then when I check multiple checkboxes within technologyArray and/or technologyArray2, the products that match the checkbox name should ...

Learn how to style inline HTML elements, such as headings, labels, input fields, and buttons, which are typically displayed as block elements

Title. For my dictionary chrome extension, I am looking to inline a label, input field, and button all in one line. This is what I want to achieve: Define:[ INPUT ] DEFINE The brackets represent the input field and "DEFINE" is the ...

What is the method for accessing the value of variable "a" in the following code?

request(target, function (err, resp, body) { $ = cheerio.load(body); links = $('a'); $(links).each(function (i, link) { if ($(link).text().match('worker')) { var a = $(link).attr('href').toStri ...