Error in HTML5 video: Unable to access property '0' as it is undefined

I am trying to create a simple block displaying an HTML5 video tag. I want the ability to play different videos along with their titles from a JSON file by using previous and next buttons. Clicking the next button should play the next video, and the same goes for the previous button.

For reference, here is a JSFiddle link: HTML5 video previous - next btns demo

This is what I have implemented so far:

HTML

        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<div id="video-container">

<h1 class="movie-title">Movie title</h1>

   <video class="videoplayer" id="video-player_transformed"
                            playsinline autoplay muted>
 <source src="https://app.coverr.co/s3/mp4/Sand-Slow-Walk.mp4"
                                type="video/mp4">

   </video>

</div>

<div class="btns">
    <div class="prev">
           Prev
   </div>

   <div class="next">
           next
   </div>
 </div>

CSS

body{
  background: gray;
}
#video-container{
position: relative;
  height: 314px;
  width: 800px;
  display: flex;
  justify-content: center;
   align-self: center;
   overflow: hidden;
}
.movie-title{
position: absolute;
top: 0px;
}

.btns{
  display: flex;
  justify-content: center;
}
.prev, .next{
  display: flex;
  width: 100px;
  height: 50px;
  background: red;
  margin: 20px;
    justify-content: center;
    align-items: center;
    color: white;
    cursor: pointer;
}
video{
height: 400px;
width: 400px;
}

JS

$(document).ready(function () {

            var data
            $.ajax({
              dataType: 'json',
              url: 'https://videomill-bot.audiencevideo.com/videoexplainer/videoexplainer/data/video.json',
              data: data,
              success: function(data) {
                console.log($('.videoplayer').append(data));

              },
            })


var player = document.querySelector('#videoplayer');
var i = 0;
var prev = document.querySelector('.prev');
var next = document.querySelector('.next');

prev.addEventListener('click',function(){
    player.src = data[i == 0 ? data.length-- : i--];
    video.play();
},false);

next.addEventListener('click',function(){
    player.src = data[i ==data.length-- ? 0 : i++];
    video.play();
},false);

player.src = data[i];
player.play(); //init the video player


});

However, I encountered the following error:

 Uncaught TypeError: Cannot read property '0' of undefined

If you have any suggestions on how to fix this issue and achieve my desired functionality, please feel free to share. Your help is greatly appreciated. Thank you!

Answer №1

Make sure to assign a value to the variable data from your AJAX call. To avoid scoping errors, consider changing some names and assigning it in this way:

var myData;
//...
success: function(data) {
  console.log($('.videoplayer').append(data));
  myData = data;
}

As highlighted by @Louys Patrice Bessette in the comments, remember to replace occurrences of myData with data in the rest of your 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

What steps can I take to make sure the JavaScript runs and updates the images correctly?

Trying to adjust image sizes with JavaScript. Followed a jsfiddle example, but it's not working on the page. Seems like the script is misplaced. How can I fix this? <!DOCTYPE html> <html> <head> <meta http-equiv="cont ...

Modify background image upon hovering using AngularJS

I cannot seem to make the background images of my divs change. Despite trying various options, none of them have been successful. Here's an example of my code: <div ng-controller="mainController" class="main"> <div ng-repeat="land in lan ...

The MUI date picker does not display dates earlier than 1900

I am in need of a datepicker that allows users to select dates from the 1850s, however, the mui datepicker only starts from the 1900s. To demonstrate this issue, I have provided a sample code in this codesandbox I am utilizing mui in the remainder of my ...

Encountering the error "Cannot GET /login" while attempting to send a file through a post request in Express.js

I'm having trouble sending a new HTML file to the user after a successful login. Every time I attempt to send the file, I keep getting an error message saying "Cannot GET /login" on the page. Below is the section of code that's causing me diffic ...

What is the best way to transfer static assets from an npm package to a nuxt project?

Has anyone successfully sent assets from an npm package to a nuxt application before? I have a vue component within an npm package with the following structure: -src/ -assets/ -noun-filter.svg In this npm package, the vector image is included in the v ...

How jQuery Autocomplete handles lowercase conversions in queries

Currently, I am utilizing the jQuery Autocomplete plugin 1.1 for a project. Below is my calling code: $("#txtCombo").autocomplete("http://www.example.com/autocomplete.php", { autoFill: false, width: 550, minChars: 3, ...

Organize JSON data based on the timestamp

What is the most effective method for sorting them by timestamp using jquery or plain JavaScript? [{"userName":"sdfs","conversation":"jlkdsjflsf","timestamp":"2013-10-29T15:30:14.840Z"},{"userName":"sdfs","conversation":"\ndslfkjdslkfds","timestamp" ...

IBM Watson Conversation and Angular Integration

After recently diving into Angular, I am eager to incorporate a Watson conversation bot into my angular module. Unfortunately, I'm facing an issue with including a library in Angular. To retrieve the Watson answer, I am utilizing botkit-middleware-wat ...

Unveiling the secrets to integrating real-time graphical representations of sensor

I have successfully connected a temperature sensor to the BeagleBone Black [BBB] board. Every 1 second, the sensor senses the temperature and passes it to the BBB. The BeagleBone then dumps this data into a MySQL database on another computer. Now, I want t ...

Accessing content from a text file and showcasing a designated line

Apologies if my wording was unclear... In this scenario, we will refer to the text file as example.txt. The value in question will be labeled as "Apple" My goal is to retrieve example.txt, search for Apple within it, and display the entire line where thi ...

What is the best way to create a gradual color change in each individual cell instead of changing all at once?

Looking for some help with a grid I'm working on. I've got the cells changing colors like I want them to, but they're all changing at once. What I really need is for them to light up in a specific order - Yellow, Green, Blue, White, Orange. ...

Fluid pictures in Mozilla Firefox not fluid

My images are shrinking in Chrome, as expected, but they don't adjust their size in Firefox and IE9. I'm using the CSS below: .pics img { max-width: 100%; height: auto; width: auto\9; /* ie8 */ border: 1px solid #CCC; }​ ...

No content appearing instead of AngularJS code displayed

My goal is to retrieve data from a MySQL database using PHP and then pass that data in JSON format to AngularJS for display in a table. The HTML code looks like this: <body ng-app="myModule"> <div class="row"> <div class="col-lg-12 ...

Utilizing a refreshed array of elements within a component directive

When working within a view, I am utilizing ng-repeat inside a directive to iterate over an array of objects from my controller. However, as the objects in the array undergo value changes, I encounter a dilemma when transitioning to a new instance of the sa ...

What could be causing the malfunction of this JavaScript dropdown select feature in Internet Explorer?

I created a website that requires users to input their location, including the city and state. The process involves two dropdown menus: - The first dropdown menu, labeled "state," loads all USA states as selectable options when the website is loaded. This ...

Using jQuery Ajax and PHP for Secure User Authentication

Hello everyone, I could really use some assistance right now. The issue I'm facing is that the error div is not showing the content I expect in the success function of my AJAX request. I've tried alerting the response, which returns true if the ...

What causes the values to constantly change whenever I insert an element into the array?

When I add an element, it automatically replaces all the others. This issue only occurs when I insert the entire object; if I insert a typical element such as an integer or a string, it works without any problems. <body> <div id="app&quo ...

Reset the AJAX object using jQuery

Currently, my code looks like this: object1 = $.ajax({ .. .. }); If an error occurs, I would like to have the ability to restart the ajax request. For instance, if the user's connection is lost, I want to be able to easily call the same ajax again w ...

Guide to sending DevExtreme data grids to ASP.NET MVC controllers

Currently, I am utilizing a datagrid with DevExtreme. I am wondering how I can pass the datagrid to my controller in ASP.NET MVC. In my view, I have attempted the following: @using (Html.BeginForm("action-name", "controller-name", FormMethod.Post)) { ...

Switch Focus and Collapse Submenus upon Menu Click in Recursive React Menu

I've created a dynamic menu system in React using Material-UI that supports recursion for submenus. I'm aiming to implement the following features: 1. When a menu item is clicked, all other open submenus should close and focus on the clicked men ...