how to add custom button inside html player using mediaelement,js script - javascript

I wanted to add a extra button "HD" near caption inside html5 player.
Added this piece of code inside mediaelementplayer.js file.
//HD button display starts
(function ($) {
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function (player, controls, layers, media) {
// create HD button
$('<div class="mejs-button mejs-hd-button"><span>HD<span/></div>')
.appendTo(controls);
}
});
})(mejs.$);
//HD button display stops
can anyone help to solve this issue?
As of now mediaelementplayer.js by johndyer doesnot support HD on/off button.
Reference http://mediaelementjs.com/ by johndyer

You need to do it as follows (this is an example for a Loop button):
MediaElementPlayer.prototype.buildloop = function(player, controls, layers, media) {
var
// create the loop button
loop =
$('<div class="mejs-button mejs-loop-button ' + ((player.options.loop) ? 'mejs-loop-on' : 'mejs-loop-off') + '">' +
'<span></span>' +
'</div>')
// append it to the toolbar
.appendTo(controls)
// add a click toggle event
.click(function() {
player.options.loop = !player.options.loop;
if (player.options.loop) {
loop.removeClass('mejs-loop-off').addClass('mejs-loop-on');
} else {
loop.removeClass('mejs-loop-on').addClass('mejs-loop-off');
}
});
}
Then, when creating your video player you can just add your variable to the features list for example:
$('video,audio').mediaelementplayer({
features: ['loop','playpause','current','progress','duration','fullscreen'],
alwaysShowControls: true,
});

Thank you #Sam, i used your code and wrote a vanilla version of your solution. This one adds two buttons to adjust the volume, a plus and a minus button, to make 10 steps for adjustment. (mediaelementjs 4.2.8)
Javascript:
var audio_player = document.getElementById('audio-player').children[0];
MediaElementPlayer.prototype.buildvolume_plus = function(player, controls) {
var
volume = document.createElement('div'),
volume_button = document.createElement('button');
volume.className = 'mejs__button mejs__volumeplus-button';
volume_button.type = 'button';
volume.appendChild(volume_button);
controls.appendChild(volume);
volume_button.addEventListener('click', function() {
player.setVolume( player.volume < 1 ? Math.round( (player.volume + .1 ) * 10) / 10 : 1 );
})
};
MediaElementPlayer.prototype.buildvolume_minus = function(player, controls) {
var
volume = document.createElement('div'),
volume_button = document.createElement('button');
volume.className = 'mejs__button mejs__volumeminus-button';
volume_button.type = 'button';
volume.appendChild(volume_button);
controls.appendChild(volume);
volume_button.addEventListener('click', function() {
player.setVolume( player.volume > 0 ? Math.round( (player.volume - .1 ) * 10) / 10 : 0 );
})
};
new MediaElementPlayer(audio_player);
HTML:
<div id="audio-player">
<audio src="http://example.com" width="220" height="60" controls data-mejsoptions=\'{"features": ["playpause", "volume_plus", "volume_minus"]}\'></audio>
</div>

Related

Loading/Buffering text while loading audio in html5 custom player with JavaScript

I found a custom html5 audio player and successfully redesigned it, now I want to add a "loading/buffering" text while player is loading audio (otherwise users may freak out because nothing happening after they hit play).
Here is the code to explain:
function calculateTotalValue(length) {
var minutes = Math.floor(length / 60),
seconds_int = length - minutes * 60,
seconds_str = seconds_int.toString(),
seconds = seconds_str.substr(0, 2),
time = minutes + ':' + seconds
return time;
}
function calculateCurrentValue(currentTime) {
var current_hour = parseInt(currentTime / 3600) % 24,
current_minute = parseInt(currentTime / 60) % 60,
current_seconds_long = currentTime % 60,
current_seconds = current_seconds_long.toFixed(),
current_time = (current_minute < 10 ? "0" + current_minute : current_minute) + ":" + (current_seconds < 10 ? "0" + current_seconds : current_seconds);
return current_time;
}
function initProgressBar() {
var player = document.getElementById('player');
var length = player.duration
var current_time = player.currentTime;
// calculate total length of value
var totalLength = calculateTotalValue(length)
jQuery(".end-time").html(totalLength);
// calculate current value time
var currentTime = calculateCurrentValue(current_time);
jQuery(".start-time").html(currentTime);
var progressbar = document.getElementById('seekObj');
progressbar.value = (player.currentTime / player.duration);
progressbar.addEventListener("click", seek);
if (player.currentTime == player.duration) {
$('#play-btn').removeClass('pause');
}
function seek(evt) {
var percent = evt.offsetX / this.offsetWidth;
player.currentTime = percent * player.duration;
progressbar.value = percent / 100;
}
};
function initPlayers(num) {
// pass num in if there are multiple audio players e.g 'player' + i
for (var i = 0; i < num; i++) {
(function() {
// Variables
// ----------------------------------------------------------
// audio embed object
var playerContainer = document.getElementById('player-container'),
player = document.getElementById('player'),
isPlaying = false,
playBtn = document.getElementById('play-btn');
// Controls Listeners
// ----------------------------------------------------------
if (playBtn != null) {
playBtn.addEventListener('click', function() {
togglePlay()
});
}
// Controls & Sounds Methods
// ----------------------------------------------------------
function togglePlay() {
if (player.paused === false) {
player.pause();
isPlaying = false;
$('#play-btn').removeClass('pause');
} else {
player.play();
$('#play-btn').addClass('pause');
isPlaying = true;
}
}
}());
}
}
initPlayers(jQuery('#player-container').length);
Player code (source) on CodePen
I want some text will be shown in the same "span" that shows
"start time" (please see CodePen) while media is loading;
The text " 'loading.' 'loading..' 'loading...' " must changing on
loop while media is loading;
When it is loaded the "loading" text must be changing on "start
time" as it is now.
So basically I wat to put some text in start time while it is not shows anything but zeroes
I'm new to JS
Thats why I need some help or point to right direction
You can use the "readyState" event of the audio player to show hide loading.
There is already a "SetInterval" even which is getting fired so in that we can add this code to show/hide the "Loading"
1st add the loading element(You can put it where ever you want"
<h3 id="loading" style="display:none;">Loading</h3>
Now let's add the code to check "readystate" inside "SetInterval"
if(player.readyState>0&&player.readyState<4){
$("#loading").show();
}
else{
$("#loading").hide();
}
You can read more about "readystate" here
/As per the request I have changed the code to use the start time as loading, to make it work we don't have to add anything inside html but need to do some changes in JS
First, add this inside "togglePlay" functions pay condition in the "else" block.
$(".start-time").html("Loading...");
After this inside "initProgressBar()" function replace the "jQuery(".start-time").html(currentTime);" with the below code
if (player.readyState === 4) {
jQuery(".start-time").html(currentTime);
}
so how it will work, When you click play button the start time text will show as "Loading" but once the file is loaded and the player is ready to play the text will be changed to "start time", Hope it works. Also updated the CodePen for better understanding
You can find the full code in the CodePen
You could use setInterval to cycle through the different 'loading' text and clearInterval when the player's play promise is done.
Here's a basic example:
var dots = 1;
var loading = setInterval(function(){
dots = (dots % 3) + 1;
$(".start-time").text("Loading" + Array(dots + 1).join("."));
console.log($(".start-time").text());
}, 250);
player.play().then(function() {
clearInterval(loading);
}).catch((error) => {
$(".start-time").text("Error loading");
});

Fading out in Javascript

Hey I'm new to javascript and I'm working on a small chat program right now.
I've got all the chatlogs (global& private and stuff..) but i want to add a button which can make (most of) the elements of these little 'clients' fade out and in, so that you dont have to see ALL of them at one time, just the ones you want.
The (relevant) code with the example element mess1:
h=0;
newroom = function (roomname) {
//create new container
var div = document.createElement('div');
div.className = 'container';
//new text input
var mess = document.createElement('input');
mess.type = 'text';
mess.id = 'mess1' + i;
div.appendChild(mess);
//minimizer button
var min = document.createElement('input');
min.type = 'button';
min.value = 'Minimize chat';
min.id = 'min' + i;
div.appendChild(min);
document.body.appendChild(div);
document.getElementById("min" + h).addEventListener("click", function (){
//this is where the magic happens
}
h++;
};
I've tried document.getElementById("mess1" + h).style.visibility = 'hidden';, but that just makes the element disappear, leaving a big ugly blank space behind.
I thought document.getElementById("mess1" + h).fadeOut('slow'); would fix that, but it just doesn't do anything...
Thanks in advance for your answers
function fadeout(element) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
first of all I will recommend to use jQuery, it will make your life much more easy. In jQuery, you can fade the element and then remove it like this
$("#mess1" + h).fadeOut('slow',function(){
$("#mess1" + h).remove();
});
It will first fade the element and will then remove it from node if required
You can use
document.getElementById("mess1" + h).style.display= 'none';
it will hide element without empty space. But if you whant to hide element with animation you can use eq. this jquery:
$("#mess1" + h).hide('slow')
or eq. 'fast' - as parameter

Javascript slider function - How to objectify the selectors?

I'm currently working on a project where a custom slider was needed and i quickly grabbed a neat looking tutorial of the web and went away and staticly it all works great.
Now i want to be able to put several sliders on my page and therefore need to add the controls dynamicly rather than just selecting a certain slider with jquery like I've done below.
This is my code with comments added to explain what im trying to achieve:
var Slider = function() { this.initialize.apply(this, arguments) };
Slider.prototype = {
initialize: function(slider) {
this.ul = slider.children[2];
this.li = this.ul.children;
this.nav = slider.children[3]; //Why cant i use .append on this element?
// make <ul> as large as all <li>’s
this.ul.style.width = (100 * this.li.length) + '%';
// set width of the li's
for(i = 0; i < this.li.length; i++) {
this.li[i].style.width = (100 / this.li.length) + '%';
$(".slider-nav").append( '<div class="slider-dot"></div>'); //Want to make it a this.nav or something similar instead of an external selector
//console.log(this.nav);
}
this.currentIndex = 0;
},
goTo: function(index) {
if (index < 0 || index > this.li.length - 1)
return;
// move <ul> left
this.ul.style.left = '-' + (100 * index) + '%';
this.currentIndex = index
},
goToPrev: function() {
this.goTo(this.currentIndex - 1)
},
goToNext: function() {
this.goTo(this.currentIndex + 1)
}}
var sliders = [];
$('.slider').each(function() {
sliders.push(new Slider(this));
});
//Find a way to implement theese 2 within the slider function, how to find out what position in the array a slider has?
$(".prev-btn").click(function() {
sliders[0].goToPrev();
});
$(".next-btn").click(function() {
sliders[0].goToNext();});
The marks up for the slider looks like this: http://puu.sh/hAUH1/a865792137.png
I managed to get it done by defining this as another var
var sliderEle = this;
I could then call it like this:
$(this.prev).click(function(e) {
e.preventDefault();
sliderEle.goToPrev();
});
with prev and next defined like this:
this.prev = slider.children[0];
this.next = slider.children[1];

Changing image to another on click

We are currently creating an image inside a holder (ch-item) as shown below:
<div class="ch-item ch-img-1" style="background: url(<?php echo get_template_directory_uri(); ?>/images/image1.jpg);">
If possible we would like to make this image change to another when clicked, and repeat this process six times in all, so each time it is clicked it changes to another image.
We would greatly appreciate any help. Thank you!
This is one way to do it using solely Javascript:
// Counter to keep track of which the current image is
var counter = 0;
// List of images
var images = [
'http://cdn.cutestpaw.com/wp-content/uploads/2011/11/Seemly-l.jpg',
'http://cdn.cutestpaw.com/wp-content/uploads/2011/11/Handsome-l.jpg',
// Add more images here
];
window.onload = function () {
// Get the container div
var gallery = document.getElementById('gallery');
// Run updateImage function on click
gallery.addEventListener('click', updateImage);
// Run updateImage on start
updateImage();
}
function updateImage() {
// Get the container div
var gallery = document.getElementById('gallery');
// Set background image
gallery.style.backgroundImage = 'url(' + images[counter] + ')';
// Update counter
counter++;
// Remove old class name
if (counter == 1) { // Remove last
gallery.className = gallery.className.replace(
' ch-img-' + images.length,
''
);
} else { // Remove previous
gallery.className = gallery.className.replace(
' ch-img-' + (counter - 1),
''
);
}
// Add new class name
gallery.className = gallery.className + ' ch-img-' + (counter);
// Reset counter when at the end of the images list
if (counter == images.length) {
counter = 0;
}
}
And here is a JSFiddle to try it out:
https://jsfiddle.net/0tg6up0o/14/

Previewing form using javascript in lightbox popup

please I need some help in previewing a form in popup. I have a form, quite big, so I added the option of preview to show as popup. The lightbox form popup works well, but the problem I now have is function passform() passing the inputs(textfield, select, checkbox, radio) into the popup page for preview on Click().
Below are my javascript and html codes. I left the css and some html out, because I think they're not necessary. I will appreciate your help. Thank you
The Javascript
function gradient(id, level)
{
var box = document.getElementById(id);
box.style.opacity = level;
box.style.MozOpacity = level;
box.style.KhtmlOpacity = level;
box.style.filter = "alpha(opacity=" + level * 100 + ")";
box.style.display="block";
return;
}
function fadein(id)
{
var level = 0;
while(level <= 1)
{
setTimeout( "gradient('" + id + "'," + level + ")", (level* 1000) + 10);
level += 0.01;
}
}
// Open the lightbox
function openbox(formtitle, fadin)
{
var box = document.getElementById('box');
document.getElementById('shadowing').style.display='block';
var btitle = document.getElementById('boxtitle');
btitle.innerHTML = formtitle;
if(fadin)
{
gradient("box", 0);
fadein("box");
}
else
{
box.style.display='block';
}
}
// Close the lightbox
function closebox()
{
document.getElementById('box').style.display='none';
document.getElementById('shadowing').style.display='none';
}
//pass form fields into variables
var divexugsotherugsexams1 = document.getElementById('divexugsotherugsexams1');
var exugsotherugsexams1 = document.form4.exugsotherugsexams1.value;
function passform()
{
divexugsotherugsexams1.innerHTML = document.form4.exugsotherugsexams1.value;
}
The HTML(with just one text field try):
<p><input name="submit4" type="submit" class="button2" id="submit4" value="Preview Note" onClick="openbox('Preview Note', 1)"/>
</p>
<div id="shadowing"></div>
<div id="box">
<span id="boxtitle"></span>
<div id="divexugsotherugsexams1"></div>
<script>document.write('<PARAM name="SRC" VALUE="'+exugsotherugsexams1+'">')</script>
Close
</div>

Categories