or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdcore-media-element.mdfeature-system.mdindex.mdmedia-player.mdrenderer-system.mdutility-functions.md

utility-functions.mddocs/

0

# Utility Functions

1

2

MediaElement.js provides a comprehensive set of utility functions for DOM manipulation, media type detection, time formatting, and browser feature detection, accessible through the `mejs.Utils` namespace.

3

4

## Capabilities

5

6

### DOM Utilities

7

8

Helper functions for DOM manipulation and element interaction.

9

10

```javascript { .api }

11

/**

12

* Check if element has a CSS class

13

* @param el - HTML element to check

14

* @param className - CSS class name to look for

15

* @returns Whether element has the class

16

*/

17

function hasClass(el: HTMLElement, className: string): boolean;

18

19

/**

20

* Add CSS class to element

21

* @param el - HTML element to modify

22

* @param className - CSS class name to add

23

*/

24

function addClass(el: HTMLElement, className: string): void;

25

26

/**

27

* Remove CSS class from element

28

* @param el - HTML element to modify

29

* @param className - CSS class name to remove

30

*/

31

function removeClass(el: HTMLElement, className: string): void;

32

33

/**

34

* Toggle CSS class on element

35

* @param el - HTML element to modify

36

* @param className - CSS class name to toggle

37

*/

38

function toggleClass(el: HTMLElement, className: string): void;

39

40

/**

41

* Get element's offset position relative to document

42

* @param el - HTML element to measure

43

* @returns Object with top and left offset values

44

*/

45

function offset(el: HTMLElement): { top: number; left: number };

46

47

/**

48

* Get sibling elements of a given element

49

* @param el - Reference element

50

* @param filter - Optional filter function

51

* @returns Array of sibling elements

52

*/

53

function siblings(el: HTMLElement, filter?: (element: HTMLElement) => boolean): HTMLElement[];

54

55

/**

56

* Check if element is visible

57

* @param elem - HTML element to check

58

* @returns Whether element is visible

59

*/

60

function visible(elem: HTMLElement): boolean;

61

```

62

63

**Usage Examples:**

64

65

```javascript

66

import { mejs } from 'mediaelement';

67

68

const playerElement = document.getElementById('player');

69

70

// CSS class manipulation

71

if (!mejs.Utils.hasClass(playerElement, 'active')) {

72

mejs.Utils.addClass(playerElement, 'active');

73

}

74

75

mejs.Utils.removeClass(playerElement, 'loading');

76

mejs.Utils.toggleClass(playerElement, 'playing');

77

78

// Element positioning

79

const position = mejs.Utils.offset(playerElement);

80

console.log(`Player position: ${position.left}, ${position.top}`);

81

82

// Check visibility

83

if (mejs.Utils.visible(playerElement)) {

84

console.log('Player is visible');

85

}

86

87

// Get siblings

88

const siblingElements = mejs.Utils.siblings(playerElement);

89

console.log(`Found ${siblingElements.length} siblings`);

90

```

91

92

### Animation Utilities

93

94

Functions for smooth element animations.

95

96

```javascript { .api }

97

/**

98

* Fade element in with animation

99

* @param el - HTML element to fade in

100

* @param duration - Animation duration in milliseconds

101

* @param callback - Optional callback when animation completes

102

*/

103

function fadeIn(el: HTMLElement, duration?: number, callback?: () => void): void;

104

105

/**

106

* Fade element out with animation

107

* @param el - HTML element to fade out

108

* @param duration - Animation duration in milliseconds

109

* @param callback - Optional callback when animation completes

110

*/

111

function fadeOut(el: HTMLElement, duration?: number, callback?: () => void): void;

112

```

113

114

**Usage Examples:**

115

116

```javascript

117

import { mejs } from 'mediaelement';

118

119

const controlsElement = document.querySelector('.mejs__controls');

120

121

// Fade controls in over 300ms

122

mejs.Utils.fadeIn(controlsElement, 300, () => {

123

console.log('Controls faded in');

124

});

125

126

// Fade controls out over 500ms

127

mejs.Utils.fadeOut(controlsElement, 500, () => {

128

console.log('Controls faded out');

129

});

130

```

131

132

### Script Loading Utilities

133

134

Dynamic script loading with Promise support.

135

136

```javascript { .api }

137

/**

138

* Dynamically load JavaScript file

139

* @param url - URL of script to load

140

* @returns Promise that resolves when script loads

141

*/

142

function loadScript(url: string): Promise<void>;

143

```

144

145

**Usage Examples:**

146

147

```javascript

148

import { mejs } from 'mediaelement';

149

150

// Load HLS.js library dynamically

151

mejs.Utils.loadScript('https://cdn.jsdelivr.net/npm/hls.js@latest/dist/hls.min.js')

152

.then(() => {

153

console.log('HLS.js loaded successfully');

154

// Initialize HLS player

155

})

156

.catch((error) => {

157

console.error('Failed to load HLS.js:', error);

158

});

159

160

// Load multiple scripts sequentially

161

async function loadDependencies() {

162

try {

163

await mejs.Utils.loadScript('/js/hls.min.js');

164

await mejs.Utils.loadScript('/js/dash.min.js');

165

console.log('All dependencies loaded');

166

} catch (error) {

167

console.error('Failed to load dependencies:', error);

168

}

169

}

170

```

171

172

### AJAX Utilities

173

174

Simple AJAX request functionality.

175

176

```javascript { .api }

177

/**

178

* Make AJAX request

179

* @param url - Request URL

180

* @param dataType - Expected response type ('json', 'text', 'xml')

181

* @param success - Success callback function

182

* @param error - Error callback function

183

*/

184

function ajax(

185

url: string,

186

dataType: 'json' | 'text' | 'xml',

187

success: (data: any) => void,

188

error: (xhr: XMLHttpRequest) => void

189

): void;

190

```

191

192

**Usage Examples:**

193

194

```javascript

195

import { mejs } from 'mediaelement';

196

197

// Load player configuration from server

198

mejs.Utils.ajax(

199

'/api/player-config.json',

200

'json',

201

(config) => {

202

console.log('Config loaded:', config);

203

// Initialize player with server config

204

const player = new MediaElementPlayer('video', config);

205

},

206

(xhr) => {

207

console.error('Failed to load config:', xhr.status);

208

}

209

);

210

211

// Load subtitle tracks

212

mejs.Utils.ajax(

213

'/api/subtitles.vtt',

214

'text',

215

(vttData) => {

216

console.log('Subtitles loaded');

217

// Add track to player

218

},

219

(xhr) => {

220

console.error('Failed to load subtitles');

221

}

222

);

223

```

224

225

### Media Type Detection

226

227

Functions for detecting and working with media types and file extensions.

228

229

```javascript { .api }

230

/**

231

* Convert relative URL to absolute URL

232

* @param url - Relative or absolute URL

233

* @returns Absolute URL

234

*/

235

function absolutizeUrl(url: string): string;

236

237

/**

238

* Format media type string

239

* @param url - Media file URL

240

* @param type - Optional explicit type

241

* @returns Formatted MIME type

242

*/

243

function formatType(url: string, type?: string): string;

244

245

/**

246

* Extract MIME type from type string

247

* @param type - Type string that may include codecs

248

* @returns Clean MIME type

249

*/

250

function getMimeFromType(type: string): string;

251

252

/**

253

* Detect media type from file URL

254

* @param url - Media file URL

255

* @returns Detected MIME type

256

*/

257

function getTypeFromFile(url: string): string;

258

259

/**

260

* Get file extension from URL

261

* @param url - File URL

262

* @returns File extension (without dot)

263

*/

264

function getExtension(url: string): string;

265

266

/**

267

* Normalize file extension

268

* @param extension - File extension

269

* @returns Normalized extension

270

*/

271

function normalizeExtension(extension: string): string;

272

```

273

274

**Usage Examples:**

275

276

```javascript

277

import { mejs } from 'mediaelement';

278

279

// URL handling

280

const relativeUrl = '../videos/sample.mp4';

281

const absoluteUrl = mejs.Utils.absolutizeUrl(relativeUrl);

282

console.log('Absolute URL:', absoluteUrl);

283

284

// Media type detection

285

const videoUrl = 'https://example.com/video.mp4';

286

const detectedType = mejs.Utils.getTypeFromFile(videoUrl);

287

console.log('Detected type:', detectedType); // 'video/mp4'

288

289

const extension = mejs.Utils.getExtension(videoUrl);

290

console.log('Extension:', extension); // 'mp4'

291

292

// Type formatting

293

const formattedType = mejs.Utils.formatType(videoUrl);

294

console.log('Formatted type:', formattedType);

295

296

// MIME type extraction

297

const complexType = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';

298

const mimeType = mejs.Utils.getMimeFromType(complexType);

299

console.log('MIME type:', mimeType); // 'video/mp4'

300

```

301

302

### Time Formatting Utilities

303

304

Functions for converting and formatting time values and timecodes.

305

306

```javascript { .api }

307

/**

308

* Convert seconds to formatted timecode string

309

* @param time - Time in seconds

310

* @param forceHours - Force hour display even for short durations

311

* @param showFrameCount - Include frame count in display

312

* @param fps - Frames per second for frame calculation

313

* @param secondsDecimalLength - Decimal places for seconds

314

* @param timeFormat - Custom time format string

315

* @returns Formatted time string

316

*/

317

function secondsToTimeCode(

318

time: number,

319

forceHours?: boolean,

320

showFrameCount?: boolean,

321

fps?: number,

322

secondsDecimalLength?: number,

323

timeFormat?: string

324

): string;

325

326

/**

327

* Convert SMPTE timecode to seconds

328

* @param smpte - SMPTE timecode string (HH:MM:SS:FF)

329

* @returns Time in seconds

330

*/

331

function convertSMPTEtoSeconds(smpte: string): number;

332

333

/**

334

* Convert time string to seconds

335

* @param time - Time string in various formats

336

* @returns Time in seconds

337

*/

338

function timeStringToSeconds(time: string): number;

339

340

/**

341

* Calculate appropriate time format for duration

342

* @param time - Duration in seconds

343

* @param options - Formatting options

344

* @param fps - Frames per second

345

*/

346

function calculateTimeFormat(time: number, options: TimeFormatOptions, fps?: number): void;

347

348

interface TimeFormatOptions {

349

alwaysShowHours?: boolean;

350

showTimecodeFrameCount?: boolean;

351

framesPerSecond?: number;

352

timeFormat?: string;

353

}

354

```

355

356

**Usage Examples:**

357

358

```javascript

359

import { mejs } from 'mediaelement';

360

361

// Basic time formatting

362

const duration = 3661; // 1 hour, 1 minute, 1 second

363

const timeString = mejs.Utils.secondsToTimeCode(duration);

364

console.log('Duration:', timeString); // '1:01:01'

365

366

// Force hour display for short durations

367

const shortTime = 90; // 1.5 minutes

368

const withHours = mejs.Utils.secondsToTimeCode(shortTime, true);

369

console.log('With hours:', withHours); // '0:01:30'

370

371

// Frame count display for video editing

372

const timeWithFrames = mejs.Utils.secondsToTimeCode(10.5, false, true, 30);

373

console.log('With frames:', timeWithFrames); // '0:10:15' (15 frames at 30fps)

374

375

// Convert time strings to seconds

376

const timeInSeconds = mejs.Utils.timeStringToSeconds('1:30:45');

377

console.log('Seconds:', timeInSeconds); // 5445

378

379

// Convert SMPTE timecode

380

const smpteSeconds = mejs.Utils.convertSMPTEtoSeconds('01:30:45:15');

381

console.log('SMPTE seconds:', smpteSeconds);

382

383

// Format calculation

384

const formatOptions = {

385

alwaysShowHours: false,

386

showTimecodeFrameCount: false,

387

framesPerSecond: 25

388

};

389

mejs.Utils.calculateTimeFormat(3661, formatOptions);

390

```

391

392

### General Utilities

393

394

Miscellaneous utility functions for common tasks.

395

396

```javascript { .api }

397

/**

398

* Escape HTML entities in string

399

* @param input - String to escape

400

* @returns HTML-safe string

401

*/

402

function escapeHTML(input: string): string;

403

404

/**

405

* Debounce function calls

406

* @param func - Function to debounce

407

* @param wait - Wait time in milliseconds

408

* @param immediate - Execute immediately on first call

409

* @returns Debounced function

410

*/

411

function debounce(func: Function, wait: number, immediate?: boolean): Function;

412

413

/**

414

* Check if object is empty

415

* @param instance - Object to check

416

* @returns Whether object has no properties

417

*/

418

function isObjectEmpty(instance: object): boolean;

419

420

/**

421

* Check if value is a string

422

* @param value - Value to check

423

* @returns Whether value is string type

424

*/

425

function isString(value: any): boolean;

426

427

/**

428

* Create custom event

429

* @param eventName - Name of event to create

430

* @param target - Target element for event

431

* @param isIframe - Whether event is for iframe

432

* @returns Custom event object

433

*/

434

function createEvent(eventName: string, target?: HTMLElement, isIframe?: boolean): Event;

435

436

/**

437

* Check if one DOM node comes after another

438

* @param sourceNode - First node

439

* @param targetNode - Second node

440

* @returns Whether sourceNode comes after targetNode

441

*/

442

function isNodeAfter(sourceNode: Node, targetNode: Node): boolean;

443

444

/**

445

* Split events into document and window events

446

* @param events - Event string with space-separated event names

447

* @param id - Element ID for namespacing

448

* @returns Object with document and window event arrays

449

*/

450

function splitEvents(events: string, id: string): { d: string[]; w: string[] };

451

```

452

453

**Usage Examples:**

454

455

```javascript

456

import { mejs } from 'mediaelement';

457

458

// HTML escaping for safe display

459

const userInput = '<script>alert("xss")</script>';

460

const safeText = mejs.Utils.escapeHTML(userInput);

461

console.log('Safe text:', safeText); // '&lt;script&gt;alert("xss")&lt;/script&gt;'

462

463

// Debounce resize handler

464

const handleResize = mejs.Utils.debounce(() => {

465

console.log('Window resized');

466

// Expensive resize logic here

467

}, 250);

468

469

window.addEventListener('resize', handleResize);

470

471

// Type checking

472

const config = { autoplay: true };

473

if (!mejs.Utils.isObjectEmpty(config)) {

474

console.log('Config has options');

475

}

476

477

const title = "My Video";

478

if (mejs.Utils.isString(title)) {

479

console.log('Title is valid string');

480

}

481

482

// Custom events

483

const customEvent = mejs.Utils.createEvent('playerReady', playerElement);

484

playerElement.dispatchEvent(customEvent);

485

486

// DOM position checking

487

const button1 = document.getElementById('play-btn');

488

const button2 = document.getElementById('pause-btn');

489

if (mejs.Utils.isNodeAfter(button2, button1)) {

490

console.log('Pause button comes after play button');

491

}

492

493

// Event splitting for different contexts

494

const eventString = 'click touchstart mouseover';

495

const events = mejs.Utils.splitEvents(eventString, 'player1');

496

console.log('Document events:', events.d);

497

console.log('Window events:', events.w);

498

```

499

500

### Browser Feature Detection

501

502

Access to browser capability detection through the utility system.

503

504

```javascript { .api }

505

// Access feature detection through mejs.Features

506

interface FeatureDetection {

507

isiOS: boolean;

508

isAndroid: boolean;

509

isiPad: boolean;

510

isiPhone: boolean;

511

isIE: boolean;

512

isChrome: boolean;

513

isFirefox: boolean;

514

isSafari: boolean;

515

hasNativeFullscreen: boolean;

516

supportsNativeHLS: boolean;

517

hasMSE: boolean; // Media Source Extensions

518

}

519

520

// Available as mejs.Features

521

const features: FeatureDetection = window.mejs.Features;

522

```

523

524

**Usage Examples:**

525

526

```javascript

527

import { mejs } from 'mediaelement';

528

529

// Platform-specific behavior

530

if (mejs.Features.isiOS) {

531

console.log('Running on iOS device');

532

// Use iOS-specific optimizations

533

}

534

535

if (mejs.Features.isAndroid) {

536

console.log('Running on Android device');

537

// Handle Android-specific quirks

538

}

539

540

// Browser capability checks

541

if (mejs.Features.hasNativeFullscreen) {

542

console.log('Native fullscreen API available');

543

} else {

544

console.log('Fallback fullscreen implementation needed');

545

}

546

547

if (mejs.Features.supportsNativeHLS) {

548

console.log('Browser supports HLS natively');

549

// Don't need hls.js library

550

} else {

551

console.log('Need HLS.js for HLS support');

552

}

553

554

if (mejs.Features.hasMSE) {

555

console.log('Media Source Extensions supported');

556

// Can use adaptive streaming

557

}

558

```