HTML5 Video Capture Snapshots / Images

I was recently developing a fully resposive and customised HTML5 player and I wanted to be able to switch between bitrate sources smoothly. Instead of using two seperate videos, I thought it might be easier to capture a snapshot at the video’s currentTime, display it while the video shows a  glitch during switching of the source and remove this snapshot once switched. In order to do so, I needed to create a simple jquery method to do so using canvas. I thought it was pretty cool so I decided to upload a mini version to display the capturing of the images under the video while playing. For a live demo click here.

Instructions:

CSS:

#player-container { position: relative; width: 620px; }
#player-container .camera {

width: 32px; height: 32px; position: absolute; top: 10px; right: 10px; z-index: 99999999;
background-color: rgba(0,0,0,0.7); border-radius: 4px;
background-image: url(‘camera.png’);

}

#gallery-snapshots { width: 100%; height: 87px; background-color: rgba(0,0,0,0.7); margin-top:10px; width: 620px; }
#gallery-snapshots:empty { background-color: transparent; }
#gallery-snapshots canvas{ float: left; margin: 10px; }

.clearfix:after {
visibility: hidden;
display: block;
font-size: 0;
content: ” “;
clear: both;
height: 0;
}
.clearfix { display: inline-block; }
* html .clearfix { height: 1%; }
.clearfix { display: block; }

 

Jquery:

<script src=”http://code.jquery.com/jquery-1.11.0.min.js”></script&gt;

<script>

function takeSnapshot() {

var video = $(“#player-container”).find(“video”);
var wrapper = $(“#gallery-snapshots”);

var canvases = $(‘canvas’);

//Remove if it has no limit of how many snapshots
if (canvases.length == 4)
canvases.eq(0).remove();

var spacing = 20;
var height = (video.height() / 4) – spacing;
var width = (video.width() / 4) – spacing;

var canvas = $(‘<canvas />’).attr({ width: width, height: height })[0];
canvas.getContext(‘2d’).drawImage(video[0], 0, 0, width, height);

wrapper.append(canvas);

}
</script>

And finally, the HTML:

 <div id=”player-container”>

<div id=”captureSnapshot” class=”camera” onclick=”takeSnapshot()”></div>

<video width=”620″ autoplay autobuffer controls preload=”auto”>

<source src=”movie.mp4″ type=”video/mp4″>
<p>Your browser does not support HTML5 video.</p>

</video>

</div>

<div id=”gallery-snapshots” class=”clearfix”></div>

Have fun !!

Simple Javascript Countdown

countdown

 

I recently needed a simple javascript countdown and thought would be easier to create one rather than using a complicated existing one. In the following demo, I’m getting date now and add only 1 minute to it for the count down. As soon as the countdown reaches zero seconds, the countdown will be hidden and another element would show.

View DEMO HERE

Continue reading

Error: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

I was trying to make an AJAX Post to another domain http://freegeoip.net/ to get Geo Location and therefore the browser would not allow me to proceed due to cross-domains. Cross domain means that if you are on domain A.com and would like to make a request to domain B.com, it does not allow the request to be made since the boundaries are set on the domain A.com by your browser. Script tags allow us to overcome this boundary however we still cannot read or do anything with the data returned.

Ajax Post:

$.ajax({

url: 'http://freegeoip.net/json/',
type: 'POST',
dataType: 'json',
success: function (data) {

var ip = data["ip"];
var country_name = data["country_name"];
var city_name = data["city"];

}

});

Error:

XMLHttpRequest cannot load http://freegeoip.net/json/. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:4868‘ is therefore not allowed access.

Solution ( Very Easy!) :

JSONP is just like the normal JSON we are used to but it also passes an extra parameters with more of your pages details. When sending a request to another domain B.com with JSON, if the domain B.com has JSONP enabled, it will change the response in a way to be readable for us to handle. Therefore, all we need to do is change the dataType from “json” to “jsonp” as follows:

$.ajax({

url: 'http://freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function (data) {

var ip = data["ip"];
var country_name = data["country_name"];
var city_name = data["city"];

}

});

This worked perfectly for me, and I could successfully get the Client IP, Country and City.

PS: the above requires jQuery to function since we are using a jQuery Ajax Request.

Goodluck 🙂

Preview Image from File Upload using JavaScript

Try it out now:

Demo

Steps:

Step 1: Add a input type=”file”, give it an id and add the attribute multiple to allow for multiple file upload

<input type="file" id="files" name="files" multiple >

Step 2: On Page load, add an event listener for your input file upload change event


<script>

window.onload = function() {

var inputLocalFont = document.getElementById("files");

inputLocalFont.addEventListener("change", previewImages, false);

}

</script>

Step 3: Create a previewImages() function to be called when the change event is fired


<script>

//Preview new images to upload

function previewImages() {

var fileList = this.files;

var previewImages = document.getElementById("previewImages");

var anyWindow = window.URL || window.webkitURL;

previewImages.innerHTML = “”;

for (var i = 0; i < fileList.length; i++) {

var objectUrl = anyWindow.createObjectURL(fileList[i]);

var filenameExt = fileList[i].name.split(‘.png’);

var filename = filenameExt[0];

var holder = ‘<div style=”float:left;”>’ +

‘ <img alt=”” src=”‘ + objectUrl + ‘” width=”100px” height=”100px” style=”margin: 15px;” />’ +

‘</div>’;

previewImages.innerHTML += holder;

window.URL.revokeObjectURL(fileList[i]);

}

//This will be used to set the hight of the parent div

previewImages.innerHTML += “<div style=’width: 100%; clear: both; float: none’></div>”;

}
</script>

Enjoy 🙂

MVC Redirect from View with Parameters

I needed to redirect to another view using JavaScript for which I encountered quite some issues to do so.

1. First of all, windows.location.href = “http://&#8230;.” would not work.

2. Then I discovered that what needed to be done to redirect to another view was:

window.location.href = ‘@(Url.Action(“Index”, “Home”))’;

3. However, I needed to pass a search query and so I added the normal new parameter:

var mySearchQuery = $(“#mySearch”).val();

window.location.href = ‘@(Url.Action(“Index”, “Home”, new { search = mySearchQuery }))’;

The above kept on giving me error, no matter what I tried to put instead of mySearchQuery.

4.Finally, I found the solution for this. Which was:

var mySearchQuery = $(“#mySearch”).val();
var tempUrl = ‘@(Url.Action(“Index”, “Home”, new { search = 0, }))’;
var actualUrl= tempUrl .replace(“0”, mySearchQuery );
window.location.href = actualUrl;

Hope that helped 🙂

Detecting IE10 and IE11Browsers

Since IE10, browser detection tags such as (.ie or .ie9 etc) are no longer support to identify the version of the IE browser. As a matter of fact, IE is no longer even recognized as an IE browser. Instead, if you search for the User-Agent in your request header, you will see that IE10 and IE11 have a User-Agent of a Mozilla Browser: “User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko”

ie11

I thought that this means, all rendering should look like any other Mozilla rendering (Firefox). However, it was not the case. I needed to specify a certain css styling only for IE10+ browsers and could not seem to find a way of doing so without using JavaScript.

Paste the following code between script tags at the end of your page before the body closing tag:

if (document.body.style["msScrollLimit"] == undefined){
//NOT IE10+ Browser
alert("You are not using IE10 or IE11");
}
else if (document.body.style["msScrollLimit"] != undefined){
//IE10+ Browser

    //msTextCombineHorizontal is a css property only accepted using IE10+
if (document.body.style["msTextCombineHorizontal"] == undefined){
//IE10 Browser
alert("You are using IE10");
}
if (document.body.style["msTextCombineHorizontal"] != undefined){
//IE11 Browser
alert("You are using IE11");
}
}

View Live Demo Here.

Goodluck 🙂

Manage Cookies in JavaScript

function setCookie(cookie_name, cookie_value, cookie_days) {

var expiry_date = new Date();

expiry_date.setDate(expiry_date.getDate() + cookie_days);

var cookie_value = escape(cookie_value) + ((expiry_date == null) ? “” : “; expires=” + expiry_date.toUTCString());

document.cookie = cookie_name + “=” + cookie_value;

}

function getCookie(cookie_name) {

var cookie_value = document.cookie;

var cookie_value_start = cookie_value.indexOf(” ” + cookie_name + “=”);

if (cookie_value_start == -1)

cookie_value_start = cookie_value.indexOf(cookie_name + “=”);

if (cookie_value_start == -1)

cookie_value = null;

else {

cookie_value_start = cookie_value.indexOf(“=”, cookie_value_start) + 1;

var cookie_value_end = cookie_value.indexOf(“;”, cookie_value_start);

if (cookie_value_end == -1)

cookie_value_end = cookie_value.length;

cookie_value = unescape(cookie_value.substring(cookie_value_start, cookie_value_end));

}
return cookie_value;

}

function deleteCookie(cookie_name) {

document.cookie = cookie_name + ‘=;expires=Mon, 01 Jan 1990 00:00:01 GMT;’;

};

 

function checkCookieExists(cookie_name) {

if(getCookie(cookie_name) == null)

return false;

else

return true;

};

JavaScript Date Format dd/mm/yyyy

JavaScript String Date format dd/mm/yyyy hh:m:s  using a 24 hour clock:

<script>

function formatDate() {
var d = new Date();
var dd = d.getDate();
var mm = Number(d.getMonth() + 1);
var yyyy = d.getFullYear();

if (mm.toString().length == 1)
mm = “0” + mm;

var hh = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();

if (hh.toString().length == 1)
hh = “0” + hh;

return mm + “/” + dd + “/” + yyyy + ” ” + hh + “:” + m + “:” + s;
}

</script>

for meridian timing / 12 hour clocks ……

Continue reading

Get Query String using only JavaScript

Sending Query String URLs

lets assume we will have a link with a user’s id as a query string using ? to indicate the query string, id as a parameter name and =5842 to assign the value to the parameter:

<a href=”mypage.com/index.htm?id=5842“> Username </a>

Note: you can send multiple parameters using & as a seperator, example:

?id=5842&username=user1&password=psd

Loading Query String Values:

<script>

var urlParameters;

var UserID

//retrieving query string parameters
(window.onpopstate = function () {

var queryStringMatch,
regexReplaceSymbols = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decodeURI = function (s) { return decodeURIComponent(s.replace(regexReplaceSymbols , ” “)); },
queryString = window.location.search.substring(1);

urlParameters = {};
while (queryStringMatch= search.exec(queryString))
urlParameters[decodeURI(queryStringMatch[1])] = decodeURI(queryStringMatch[2]);

})();

//checking if parameter id exists and if it contains any value

if (urlParameters[“id”] != null && (urlParameters[“id”] != “”)){

UserID = urlParameters[“id”]; //assigning the parameters value to UserID

doSomething();

}

function doSomething()

{

//You can use UserID here now which contains the user’s id read from the query string

}

</script>

document.ready vs window.load

document.ready is fired once the html has loaded while windows.load is fired once everything has loaded including images, jquery, html, text from db etc.

Therefore the document.ready would fire before the window.load

examples:

<script>

$(document).ready(function() {

//your code here – fired when html loads

});

$(window).load(function() {

//your code here – fired when all page elemenets are loaded

});

</script>