I have an array like so:
var data = [
{
"title" : "Title 1",
"slideText" : "",
"startTime" : 0
},
{
"title" : "Title 2",
"slideText" : "",
"startTime" : 60
},
{
"title" : "Title 3",
"slideText" : "",
"startTime" : 120
}
];
I have a seeked event listener on an HTML5 video. When a user seeks, I need to check where they are at and determine which index in the array they're on. For example, they seek to 72 seconds, they would be on array[1]
Right now I have this:
player.addEventListener("seeked", function(event)
{
currentTime = player.currentTime;
angular.forEach($scope.data, function(value, key)
{
if (currentTime >= $scope.data[key].startTime && currentTime <= $scope.data[key + 1].startTime)
{
$scope.$apply(function()
{
$scope.setActive(key);
});
}
});
});
That all works until the seeked time reaches the end of the array and $scope.data[key + 1].time is undefined. How should I approach this? My mind isn't on track right now and I still haven't had my coffee :|
edit
new function working
player.addEventListener("seeked", function(event)
{
currentTime = player.currentTime;
for (var i = 0; i <= $scope.data.length; i++)
{
if ($scope.data[i + 1] != undefined)
{
if (currentTime < $scope.data[i + 1].startTime)
{
$scope.$apply(function()
{
$scope.setActive(i);
});
break;
}
}
else
{
$scope.$apply(function()
{
$scope.setActive($scope.data.length - 1);
});
}
}
});
Test for the array element's existence first. If it fails, the other tests will be ignored:
if ($scope.data[key+1] && currentTime>=$scope.data[key].startTime && currentTime<=$scope.data[key+1].startTime)
You will need a check for [key + 1] to ensure you don't try to access an element beyond the length of the array.
player.addEventListener("seeked", function(event)
{
currentTime = player.currentTime;
angular.forEach($scope.data, function(value, key)
{
if ( ($scope.data[key+1] != undefined) && currentTime < $scope.data[key+1].startTime)
{
// this is the one we are after
return false; // exit foreach
} else {
// we are on the last one.
}
});
});
Here was the final solution that worked
player.addEventListener("seeked", function(event)
{
currentTime = player.currentTime;
for (var i = 0; i <= $scope.data.length; i++)
{
if ($scope.data[i + 1] != undefined)
{
if (currentTime < $scope.data[i + 1].startTime)
{
$scope.$apply(function()
{
$scope.setActive(i);
});
break;
}
}
else
{
$scope.$apply(function()
{
$scope.setActive(i - 1);
});
}
}
});