Is it possible to create A simple yii2 helper html5/vanala js video player
Assistant
Yes, it is definitely possible to create a simple Yii2 helper that renders an HTML5 video player using vanilla JavaScript. Yii2 helpers are usually PHP classes with static methods that generate commonly used UI components, and since an HTML5 video player is basically an HTML <video> element (plus optional JS for control), you can wrap it nicely in a helper.
Here’s a step-by-step example of how to create a simple Yii2 helper for an HTML5 video player:
1. Create the Helper class
Create a new helper class under components folder in your Yii2 project (or wherever you store helpers):
File: components/VideoPlayerHelper.php
php
<?php
namespace app\components;
use yii\helpers\Html;
class VideoPlayerHelper
{
/**
* Generates a simple HTML5 video player
*
* @param string $src The video source URL
* @param array $options HTML attributes for the video tag, e.g. ['width' => 640, 'height' => 360, 'controls' => true]
* @param array $jsOptions Additional JavaScript options (optional)
* @return string The generated HTML + JS code
*/
public static function video($src, $options = [], $jsOptions = [])
{
// Ensure 'controls' attribute is present
if (!isset($options['controls'])) {
$options['controls'] = true;
}
// Set src attribute
$options['src'] = $src;
// Generate the video tag (self-closing is not valid for video, so close with </video>)
$html = Html::beginTag('video', $options);
$html .= "Your browser does not support the video tag.";
$html .= Html::endTag('video');
// Example: basic vanilla JS to play/pause on click (optional)
if (!empty($jsOptions['clickTogglePlay']) && $jsOptions['clickTogglePlay'] === true) {
$id = $options['id'] ?? uniqid('video_');
if (!isset($options['id'])) {
// Add id if not set so we can target it in js
$html = Html::beginTag('video', array_merge($options, ['id' => $id]));
$html .= "Your browser does not support the video tag.";
$html .= Html::endTag('video');
}
$js = <<<JS
document.getElementById('{$id}').addEventListener('click', function () {
if (this.paused) {
this.play();
} else {
this.pause();
}
});
JS;
$html .= Html::script($js);
}
return $html;
}
}
Renders <video> tag with provided source URL and HTML attributes.
Adds default controls if not explicitly provided.
Optionally adds vanilla JS to toggle play/pause when clicking on the video.
Graceful fallback message if the browser does not support <video>.
You can extend this by:
Adding support for multiple <source> tags for different formats.
Adding custom controls with more JS.
Handling events like ended, time updates, volume changes with vanilla JS.
Adding captions or subtitles.
But the above is a minimal starting point for a Yii2 helper to embed an HTML5 video player with optional simple JS.
If you want me to help extend it or add features, just ask!
User
Ok
Assistant
Great! If you want, you can try the helper in your Yii2 project and let me know if you need help customizing it further or adding more features like playlists, custom controls, or events handling.
Just ask anytime!
User
You said you could make it better
Assistant
Absolutely! Let me enhance the Yii2 video player helper by adding a few useful features that improve flexibility and usability:
Improvements we can make:
Support for multiple video sources for better browser compatibility (e.g., MP4, WebM).
Support for captions (subtitles).
Customizable controls option (choose between default controls or no controls).
Configurable container with a CSS class for easier styling.
Cleaner handling of IDs and JavaScript initialization.
Here's an improved version of the helper class:
php
User
I was hoping for html5 or js video player fullback: this is ok tho
Assistant
Thanks for clarifying! If you want a simple vanilla HTML5 video player with a basic JavaScript fallback for older browsers or if the video tag isn't supported, here’s how you can extend the helper to provide a fallback (like a download link or a Flash fallback) and more usable JS controls.
What does fullback mean here in video player context?
HTML5 <video> tag is the modern way.
For browsers that don't support it, a fallback message or alternative method is required (e.g., Flash player, or just a download link).
Also, simple vanilla JS can provide basic controls or events on the video.
You want the helper to automatically embed the fallback element/message.
Here is a refined helper method that:
Generates an HTML5 <video> element with multiple sources.
Includes a friendly fallback UI message with a download link.
Adds a simple vanilla JS toggle play/pause on click as an example custom control.
Clean, no dependencies except Yii2 Html helper.
php
User
So it's not possible to create vanilla js video player? As the fallback or use html5 with js enhancement
Assistant
It absolutely is possible to create a vanilla JavaScript (no dependencies) HTML5 video player with custom controls and JS enhancements, including fallback UI for unsupported browsers — and enhance UX beyond native controls!
The trick is you start with the native <video> tag for playback, then build your own UI controls with HTML+CSS, wiring up all the video APIs with vanilla JavaScript.
What you want roughly boils down to:
Base:<video> element (HTML5 standard, universal playback support)
Fallback: A message, or download link, if <video> isn't supported
JS enhancement: Implement custom controls (play/pause, progress bar, volume, fullscreen) with vanilla JS that:
Control the native video
Update UI on video events
No Flash or third-party dependencies involved.
Why build custom controls?
Native controls differ across browsers/platforms and you have limited styling control
Custom UI lets you create a consistent cross-browser experience
You can add exactly the controls and styles you want
Basic example of a vanilla JS custom video player with fallback
1. HTML + PHP helper to output player container and video tag
php
User
Want it as a widget
Assistant
Got it! I’ll provide you with a Yii2 widget that renders a fully functional HTML5 video player with vanilla JS custom controls and fallback — all self-contained, reusable, and easy to drop into any Yii2 view.
Yii2 Video Player Widget with Vanilla JS Custom Controls
1. Create the widget file
Create a new PHP widget file in your Yii2 project, e.g.,
components/VideoPlayerWidget.php
php
User
Can you make it look clean and elegant
Assistant
Certainly! Let me update the widget to include clean and elegant styles with modern minimal design, smooth controls, and subtle hover effects — all CSS handcrafted and integrated in the widget.
Here’s the enhanced VideoPlayerWidget with:
Stylish, flat buttons with icons
Horizontal progress bar with buffer and hover effects
Responsive layout with consistent spacing and subtle shadows
Better font and colors
Smooth transitions on hover/focus
Updated VideoPlayerWidget.php
php
Dataset releases
Not yet included in a published release.
<?php
namespace app\components;
use yii\helpers\Html;
use yii\helpers\Json;
class VideoPlayerHelper
{
/**
* Render an HTML5 video player with multiple sources and captions.
*
* @param array|string $sources Single URL string or array of sources.
* Each source can be a string URL or an associative array:
* E.g. 'video.mp4' or ['src' => 'video.webm', 'type' => 'video/webm']
* @param array $options Video tag options e.g. 'width', 'height', 'controls', 'autoplay', 'loop', 'muted', 'id' etc.
* 'controls' defaults to true if not set.
* @param array $captions Array of captions, each an array with keys:
* 'src' => path to VTT file,
* 'srclang' => e.g. 'en',
* 'label' => e.g. 'English',
* 'default' => (bool) default track.
* @param array $jsOptions Optional, to add vanilla JS behaviors:
* - 'clickTogglePlay' => bool (default false) - toggle play/pause on click,
* - other behaviors can be added as needed.
*
* @return string
*/
public static function video($sources, $options = [], $captions = [], $jsOptions = [])
{
if (!isset($options['id'])) {
$options['id'] = uniqid('video_');
}
$id = $options['id'];
// Make sure controls is true by default
if (!isset($options['controls'])) {
$options['controls'] = true;
}
// Start building video tag
$videoOptions = $options;
// Remove src from videoOptions if set to avoid duplicate attribute
unset($videoOptions['src']);
$html = Html::beginTag('video', $videoOptions);
// Handle multiple sources
if (is_string($sources)) {
// single source
$type = self::getMimeTypeByExtension($sources);
$html .= Html::tag('source', '', [
'src' => $sources,
'type' => $type,
]);
} elseif (is_array($sources)) {
// multiple sources
foreach ($sources as $source) {
if (is_string($source)) {
$type = self::getMimeTypeByExtension($source);
$html .= Html::tag('source', '', [
'src' => $source,
'type' => $type,
]);
} elseif (is_array($source) && isset($source['src'])) {
$type = $source['type'] ?? self::getMimeTypeByExtension($source['src']);
$html .= Html::tag('source', '', [
'src' => $source['src'],
'type' => $type,
]);
}
}
}
// Add captions if any
foreach ($captions as $caption) {
if (!isset($caption['src'], $caption['srclang'], $caption['label'])) {
continue;
}
$captionOptions = [
'src' => $caption['src'],
'srclang' => $caption['srclang'],
'label' => $caption['label'],
];
if (!empty($caption['default'])) {
$captionOptions['default'] = 'default';
}
$html .= Html::tag('track', '', $captionOptions);
}
$html .= "Your browser does not support the video tag.";
$html .= Html::endTag('video');
$js = '';
if (!empty($jsOptions['clickTogglePlay'])) {
$js .= <<<JS
document.getElementById('{$id}').addEventListener('click', function () {
if (this.paused) {
this.play();
} else {
this.pause();
}
});
JS;
}
// You can add other jsOptions handlers here for more customization
if (!empty($js)) {
$html .= Html::script($js);
}
return $html;
}
/**
* Get the MIME type based on file extension (based on common video formats)
*
* @param string $file
* @return string|null
*/
protected static function getMimeTypeByExtension($file)
{
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
$map = [
'mp4' => 'video/mp4',
'webm' => 'video/webm',
'ogv' => 'video/ogg',
'ogg' => 'video/ogg',
'mov' => 'video/quicktime',
'mkv' => 'video/x-matroska',
];
return $map[$ext] ?? null;
}
}
If the browser supports HTML5 <video>, it plays the first viable source.
If not, the fallback message inside the video tag is displayed.
By default, fallback is a download link pointing to the first source URL.
You can override the fallback message with custom HTML or text if you want.
Additional ideas for pure JS fallback:
If you want to support really old browsers without <video>, you'd traditionally use a Flash fallback player script — but Flash is deprecated and not recommended.
Another option is to provide a custom made player with <canvas> or <div>s and JS but that's non-trivial and out of scope for a simple helper; usually a third-party library is used.
The standard fallback approach is enough for gently handling unsupported browsers.
If you want me to help with anything more advanced — such as adding custom controls (play, pause, seek bar, volume) built with pure JS — just let me know!
<?php
namespace app\components;
use yii\helpers\Html;
class VideoPlayerHelper
{
public static function videoWithControls($src, $options = [])
{
$id = $options['id'] ?? uniqid('video_');
$width = $options['width'] ?? 640;
$height = $options['height'] ?? 360;
$poster = $options['poster'] ?? null;
$html = <<<HTML
<div class="custom-video-player" style="max-width: {$width}px;">
<video id="{$id}" width="{$width}" height="{$height}" poster="{$poster}" preload="metadata">
<source src="{$src}" type="video/mp4" />
Your browser does not support the video tag. <a href="{$src}">Download video</a>
</video>
<div class="controls" id="{$id}_controls" style="background: #333; color: #fff; padding: 10px; display: flex; align-items: center;">
<button type="button" id="{$id}_play">Play</button>
<input type="range" id="{$id}_seek" value="0" step="0.01" min="0" max="1" style="flex-grow:1; margin: 0 10px;">
<span id="{$id}_time">0:00 / 0:00</span>
<button type="button" id="{$id}_mute">Mute</button>
<button type="button" id="{$id}_fullscreen">FullScreen</button>
</div>
</div>
HTML;
// Include JS to wire controls — simple and vanilla
$js = <<<JS
(function(){
var video = document.getElementById('{$id}');
var playBtn = document.getElementById('{$id}_play');
var seekBar = document.getElementById('{$id}_seek');
var timeDisplay = document.getElementById('{$id}_time');
var muteBtn = document.getElementById('{$id}_mute');
var fullscreenBtn = document.getElementById('{$id}_fullscreen');
// Play/Pause toggle
playBtn.addEventListener('click', function(){
if(video.paused){
video.play();
playBtn.textContent = 'Pause';
} else{
video.pause();
playBtn.textContent = 'Play';
}
});
// Update seekBar as video plays
video.addEventListener('timeupdate', function(){
var value = 0;
if(video.duration){
value = video.currentTime / video.duration;
}
seekBar.value = value;
// Show current time / duration
var curM = Math.floor(video.currentTime / 60);
var curS = Math.floor(video.currentTime % 60);
var durM = Math.floor(video.duration / 60);
var durS = Math.floor(video.duration % 60);
if (isNaN(durM)) { durM = 0; durS = 0; }
timeDisplay.textContent = curM + ':' + (curS < 10 ? '0' + curS : curS) + ' / ' + durM + ':' + (durS < 10 ? '0' + durS : durS);
});
// Seek video when seekBar changes
seekBar.addEventListener('input', function(){
if(video.duration){
video.currentTime = seekBar.value * video.duration;
}
});
// Mute/unmute toggle
muteBtn.addEventListener('click', function(){
video.muted = !video.muted;
muteBtn.textContent = video.muted ? 'Unmute' : 'Mute';
});
// Fullscreen toggle
fullscreenBtn.addEventListener('click', function(){
if(document.fullscreenElement){
document.exitFullscreen();
} else {
video.parentElement.requestFullscreen();
}
});
// When video ends, reset play button text
video.addEventListener('ended', function(){
playBtn.textContent = 'Play';
});
})();
JS;
return $html . Html::script($js);
}
}
Custom controls are below the video — play/pause button, seek slider, time display, mute button, fullscreen button.
All controls are wired in vanilla JS and synced with the native video.
If the user’s browser doesn’t support <video>, fallback text with download link is shown.
You can style .custom-video-player and .controls as you want.
Benefits of this approach
Full control over styling the controls (CSS).
No dependencies (no jQuery, no third-party libs).
Works in all modern browsers (video support is good these days).
Graceful fallback if no video support.
Easy to extend with your own buttons (volume slider, playback speed, captions).
Summary
Yes — you can absolutely make a fully functional HTML5 video player with vanilla JS for custom controls and built-in fallback.
If you want, I can help you build more features like:
Volume slider
Playback speed controls
Subtitle toggle
Keyboard shortcuts
Better styling or responsive layout
Would you like me to prepare a more complete vanilla JS player example with these features, or help integrating it into Yii2 as a reusable widget/helper?
<?php
namespace app\components;
use yii\base\Widget;
use yii\helpers\Html;
class VideoPlayerWidget extends Widget
{
/**
* @var string The video source (mp4 recommended)
*/
public $src;
/**
* @var int Width in pixels
*/
public $width = 640;
/**
* @var int Height in pixels
*/
public $height = 360;
/**
* @var string Poster image URL
*/
public $poster;
/**
* @var bool Whether autoplay is enabled
*/
public $autoplay = false;
/**
* @var bool Whether to start muted
*/
public $muted = false;
/**
* @var bool Whether video should loop
*/
public $loop = false;
/**
* @var array Additional HTML attributes for the container div
*/
public $containerOptions = [];
public function run()
{
$id = $this->getId();
$posterAttr = $this->poster ? ['poster' => $this->poster] : [];
$autoplayAttr = $this->autoplay ? ['autoplay' => 'autoplay'] : [];
$mutedAttr = $this->muted ? ['muted' => 'muted'] : [];
$loopAttr = $this->loop ? ['loop' => 'loop'] : [];
$videoOptions = array_merge([
'id' => $id . '-video',
'width' => $this->width,
'height' => $this->height,
'preload' => 'metadata',
// Don't use native controls; we build custom controls
//'controls' => true,
'tabindex' => 0, // for keyboard focus
'style' => 'background-color: black;',
], $posterAttr, $autoplayAttr, $mutedAttr, $loopAttr);
$videoTag = Html::tag('video',
Html::tag('source', '', [
'src' => $this->src,
'type' => 'video/mp4',
]) .
"Your browser does not support the video tag. <a href=\"{$this->src}\">Download Video</a>",
$videoOptions
);
$controlsId = $id . '-controls';
$controlsHtml = <<<HTML
<div id="{$controlsId}" class="custom-video-controls" style="background:#222; color:#fff;
display:flex; align-items:center; padding:6px 10px; font-family:sans-serif; line-height:1;">
<button type="button" id="{$id}-play" aria-label="Play/Pause"
style="background:none; border:none; color:#fff; font-size:16px; cursor:pointer; margin-right:10px;">►</button>
<input type="range" id="{$id}-seek" min="0" max="100" value="0" step="0.1"
aria-label="Seek"
style="flex-grow:1; margin-right:10px;">
<span id="{$id}-time" style="font-size:14px; min-width:80px; text-align:right; margin-right:10px;">0:00 / 0:00</span>
<button type="button" id="{$id}-mute" aria-label="Mute/Unmute"
style="background:none; border:none; color:#fff; font-size:16px; cursor:pointer; margin-right:10px;">🔈</button>
<button type="button" id="{$id}-fullscreen" aria-label="Fullscreen"
style="background:none; border:none; color:#fff; font-size:16px; cursor:pointer;">⛶</button>
</div>
HTML;
$containerOptions = array_merge([
'id' => $id,
'class' => 'yii2-custom-video-player',
'style' => 'max-width:' . ($this->width) . 'px; user-select:none;'
], $this->containerOptions);
$container = Html::beginTag('div', $containerOptions) .
$videoTag .
$controlsHtml .
Html::endTag('div');
// Register the vanilla JS for controls here (inline script; you can move to separate file if needed)
$js = <<<JS
(function(){
var video = document.getElementById('{$id}-video');
var playBtn = document.getElementById('{$id}-play');
var seekBar = document.getElementById('{$id}-seek');
var timeDisplay = document.getElementById('{$id}-time');
var muteBtn = document.getElementById('{$id}-mute');
var fullscreenBtn = document.getElementById('{$id}-fullscreen');
// Utility: format time in seconds => mm:ss
function formatTime(seconds) {
var m = Math.floor(seconds / 60);
var s = Math.floor(seconds % 60);
return m + ':' + (s < 10 ? '0' + s : s);
}
// Play/pause toggle
playBtn.addEventListener('click', function(){
if(video.paused || video.ended){
video.play();
} else {
video.pause();
}
});
// Update play button icon & tooltip
function updatePlayButton(){
if(video.paused || video.ended){
playBtn.textContent = '►';
playBtn.title = 'Play';
} else {
playBtn.textContent = '❚❚';
playBtn.title = 'Pause';
}
}
video.addEventListener('play', updatePlayButton);
video.addEventListener('pause', updatePlayButton);
video.addEventListener('ended', updatePlayButton);
updatePlayButton();
// Update seek bar as video plays
video.addEventListener('timeupdate', function(){
if(video.duration){
var value = (video.currentTime / video.duration) * 100;
seekBar.value = value;
timeDisplay.textContent = formatTime(video.currentTime) + ' / ' + formatTime(video.duration);
}
});
// Seeking video when user changes seek bar
var seeking = false;
seekBar.addEventListener('input', function(){
seeking = true;
if(video.duration){
var newTime = (seekBar.value / 100) * video.duration;
timeDisplay.textContent = formatTime(newTime) + ' / ' + formatTime(video.duration);
}
});
seekBar.addEventListener('change', function(){
if(video.duration){
var newTime = (seekBar.value / 100) * video.duration;
video.currentTime = newTime;
seeking = false;
}
});
// Mute toggle with icon update
muteBtn.addEventListener('click', function(){
video.muted = !video.muted;
updateMuteButton();
});
function updateMuteButton(){
if(video.muted){
muteBtn.textContent = '🔇';
muteBtn.title = 'Unmute';
} else {
muteBtn.textContent = '🔈';
muteBtn.title = 'Mute';
}
}
video.addEventListener('volumechange', updateMuteButton);
updateMuteButton();
// Fullscreen toggle
fullscreenBtn.addEventListener('click', function(){
var container = document.getElementById('{$id}');
if(!document.fullscreenElement){
if(container.requestFullscreen) {
container.requestFullscreen();
} else if (container.mozRequestFullScreen) { /* Firefox */
container.mozRequestFullScreen();
} else if (container.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
container.webkitRequestFullscreen();
} else if (container.msRequestFullscreen) { /* IE/Edge */
container.msRequestFullscreen();
}
} else {
if(document.exitFullscreen) {
document.exitFullscreen();
}
}
});
})();
JS;
// register the JS inline
$this->view->registerJs($js);
return $container;
}
}
If you want, I can also help package the CSS & JS into separate asset bundles, or add more controls like volume slider, subtitles, etc. Just let me know!