Autoplaying HTML5 Video In Chrome

Whilst working on the new look for my website, I wanted to replace areas where I previously used low-grade animated GIF's for the more modern HTML5 video. Currently, the only place I use HTML5 video is on my 404 page as a light-hearted reference to one of the many memorable quotes that only fans of the early Star Trek films will understand. These are the films I still hold in very high regard, something the recent "kelvin timeline" films are missing. Anyway, back to the post in hand...

Based on Chrome's new policies introduced in April 2018 I was always under the impression that as long as the video is muted, this won't hinder in any way the autoplay functionality. But for the life of me, mt HTML5 video did not autoplay, even though all worked as intended in other browsers such as Firefox.

You can work around Chrome's restrictions through JavaScript.

Code

The HTML is as simple as adding your HTML5 video.

<video id="my-video" autoplay muted loop playsinline>
     <source src="/enterprise-destruction.mp4" type="video/mp4" />
</video>

All we need to do is target our video and tell it to play automatically. I have added a timeout to the script just to ensure the video has enough time to render on the page before our script can do its thing.

var myVideo = $("#my-video");

setTimeout(function () {
    myVideo.muted = true;
    myVideo.play();
}, 100);

It's worth noting that I don't generally write much about front-end approaches (excluding JavaScript) as I am first and foremost a backend developer. So this might not be the most ideal solution and appreciate any feedback.

My Top JavaScript ES6 Features

I've been doing some personal research into improving my own JavaScript development. I decided to get more familiar with the new version of JavaScript - ES6. ES6 is filled to the brim with some really nice improvements that make JavaScript development much more concise and efficient. After having the opportunity to work on React and React Native projects, I had a chance in putting my new found ES6 knowledge to good use!

If I had to describe ES6 in a sentence:

JavaScript has gone on a diet and cut the fat. Write less, do more!

I have only scratched the surface to what ES6 has to offer and will continue to add more to the list as I learn. If you are familiar with server-side development, you might notice some similarities from a syntax perspective. That in itself shows how far ES6 has pushed the boundaries.

Arrow Functions

Arrow functions are beautiful and so easy on the eye when scrolling through vast amounts of code. You'll see with arrow functions, you'll have the option to condense a function that consists of many lines all the way down to single line.

The traditional way we are all familiar with:

// The "old school" way..
function addSomeNumbers(a, b) {
    return a + b;
}

console.log(addSomeNumbers(1, 2));
// Output: 3

ES6:

// ES6.
const addSomeNumbers = (a, b) => {
    return a + b;
}

console.log(addSomeNumbers(1, 2));
// Output: 3

The traditional and ES6 way can still be used in the same way to achieve our desired output. But we can condense out arrow function further:

// Condensed ES6 arrow function.
const addSomeNumbers = (a, b) => a + b;

console.log(addSomeNumbers(1, 2));
// Output: 3

Default Function Parameters

When developing using server-side languages, such as C# you have the ability to set default values on the parameters used for your functions. This is great, since you have more flexibilty in using a function over a wider variety of circumstances without the worry of compiler errors if you haven't satisfied all function parameters.

Lets expand our "addSomeNumbers()" function from our last section to use default parameters.

// Condensed ES6 arrow function with default parameters.
const addSomeNumbers = (a=0, b=0) => a + b;

console.log(addSomeNumbers());
// Output: 0

This is an interesting (but somewhat useless) example where I am using "addSomeNumbers()" function without passing any parameters. As a result the value 0 is returned and even better - no compiler error.

Destructuring

Destructuring sounds scary and complex. In its simple terms, destructuring is the process of adding values to an object or array to an existing variable more straightforward. Lets start of with a simple object and how we can output these values:

// Some info on my favourite Star Trek starship...
const starship = {
  registry: "NCC-1701-E",
    captain: "Jean Luc Picard",
    launch_date: "October 30, 2372",
    spec: {
      max_warp: 9.995,
      mass: "3,205,000 metric tons",
      length: "685.7 meters",
      width: "250.6 meters",
      height: "88.2 meters"
  }
};

We would normally output the these values in the following way:

var registry = starship.registry; // Output: NCC-1701-E
var captain = starship.captain; // Output: Jean Luc Picard
var launchDate = starship.launch_date; // Output: October 30, 2372

This works well, but the process of returning those values is a little repetitive and spread over many lines. Lets get a bit more focus and go down the ES6 route:

const { registry, captain, launch_date } = starship;

console.log(registry); // Output: NCC-1701-E 

How amazing is that? We've managed to select a handful of these fields on one line to do something with. 

My final example in the use of destructuring will evolve around an array of items - in this case names of starship captains:

const captains = ["James T Kirk", "Jean Luc Picard", "Katherine Janeway", "Benjamin Sisko"]

Here is how I would return the first two captains in ES5 and ES6:

// ES5
var tos = captains[0];
var tng = captains[1];

// ES6
const [tos, tng ] = captains;

You'll see similarities to our ES6 approach for getting the values out of an array as we did when using an object. The only thing I need to look into is how to get the first and last captain from my array? Maybe that's for a later post.

Before I end the destructuring topic, I'll add this tweet - a visual feast on the basis of what destructuring is...

Spread Operator

The spread operator has to be my favourite ES6 feature, purely because in my JavaScript applications I do a lot of data manipulation. If you can get your head around destructuring and the spread operator, you'll find working with data a lot easier. A spread operator is "...". Yes three dots - ellipsis if you prefer. This allows you to copy the values of an object to be used as a basis of a new object.

In its basic form:

const para1 = ["to", "boldly", "go"];
const para2 = [...para1, "where", "no", "one"];
const para3 = [...para2, "has", "gone", "before"];

console.log(para1); // Output: ["to", "boldly", "go"]
console.log(para2); // Output: ["to", "boldly", "go", "where", "no", "one"]
console.log(para3); // Output: ["to", "boldly", "go", "where", "no", "one", "has", "gone", "before"]

As you can see from my example above, the spread operator used on variables "para1" and "para2" creates a shallow copy of the array values into our new array. Gone are the days of having to use a for loop to get the values.

Is ReactJS A Worthwhile Addition To An ASP.NET MVC Application?

ReactJSI've been meddling around with ReactJS over the last week or so, seeing if this is something viable to use for future client projects. I am always constantly on the lookout to whether there are better alternatives on how my fellow developers and I develop our sites.

Throughout the sample applications I've been building, I constantly asked myself one question: Why Would I Use ReactJS In My Day To Day Development? I am ASP.NET developer who build websites either using Web Forms or MVC Razor. So I am finding it difficult to comprehend whether using ReactJS is viable in these frameworks, especially MVC.

ReactJS is primarily a view framework where you have the ability to write component-based web applications directly into your JavaScript that then gets output to the DOM virtually - making for a very fast and responsive webpage. It's a different approach to developing websites that I quite like. But for the moment, I just don't see how it can benefit me when the full MVC framework does a pretty good job with all the bells and whistles.

For example, I segregate all my key HTML markup into partial views in order to increase re-use throughout my web application, which works really well when making AJAX calls where the markup needs to be displayed on the page asynchronously as well as server-side. I can just see by implementing ReactJS, I will be duplicating this process at JavaScript and CSHTML level if a markup change ever needed to be made. If partial views does the job effectively, I'm not too sure the need for ReactJS in my future ASP.NET MVC creations.

Don't get me wrong - I really like ReactJS. It makes writing JavaScript an even more enjoyable experience purely due to the JSX syntax. Long gone are the days where you have to concatenate strings to form HTML. More importantly, it's readable and truly scalable.

Unfortunately, it doesn't look like ReactJS is a viable option for me at this moment in time. I can see how it would be a very useful framework for building web applications where there is a requirement for the view to be created strictly client-side along with heavy use of AJAX calls from an API layer to serve data to your application. But in situations where you have two frameworks that provide the ability to create views, in this case ReactJS and ASP.NET MVC, it doesn't make sense.

I could be talking absolute nonsense and missing the whole point. If this is the case (most likely!), please leave a comment.

Change Colour of Address Bar In Chrome For Android

My Nexus 5 upgraded to Android version 5.0 a few months back and it's by far the best update yet (apart from the minor bugs). An OS that is as beautiful to look at as well as use.

One of the most intriguing things I noticed was that the colour of my Chrome browser address bar would occasionally change if I went certain websites. Being a developer who works in the web industry, this peaked my interest. So I had to find out how to do this.

After doing some online research, I found adding the this feature couldn't be simpler. Just add the following META tag to your page:

<meta name="theme-color" content="#4c7a9f">

I carried out this change on my site and it looks kinda cool!

Before

Android Chrome Browser Colour (Before)

After

Android Chrome Browser Colour (After)

It’s all about Website Hotkeys!

During the latter-end of 2010, Twitter overhauled their somewhat simplistic website to compete with client-side offerings (e.g. TweetDeck, Seesmic). What I found really impressive was a hidden bit of functionality that allowed the user to navigate around the site using keyboard shortcuts (or hot keys). If you haven't tried it, take a look at the list of shortcuts below and try them out.

Twitter Keyboard Shortcuts

Some people I know in the industry think it's a pointless feature. But I believe something so simple automatically enhances the users experience when accessing a site. In fact, you could think of hotkeys as an additional web accessibility requirement for those who don’t have a mouse or just prefer the more direct approach in navigating through a site. Many sites have been utilising hotkeys to get their sites to act like locally installed software programmes, for example Google Docs.

I was very keen on replicating hotkey functionality on my next project. Not surprising, there are a lot of custom jQuery plugins that allowed you to implement some basic keyboard shortcut functionality. The best one I found through trial and error is Mousetrap. I found Mousetrap to be the most flexible plugin to fire your own custom JavaScript events by binding a single, sequence or combination key press.

Using Mousetrap, I could replicate a simple Twitter-style shortcut to take a user back to the homepage by pressing the following keys in sequence: “G H”:

Mousetrap.bind("g h",
    function () { 
        window.location = "/Home.aspx"; 
    }
);

Minimise and Obfuscate Your JavaScript Code

Obfuscated Code (Google)

We all know minimising our JavaScript files prior to moving a site into a production environment is best practise. The main reason why we do it is because compressed JavaScript files allow sites run faster at a lower bandwidth cost and (to some extent) make the code harder to understand.

But what if we wanted to have the ability to render a JavaScript file completely unintelligible to prying eyes? This is the very question I asked myself prior to deploying a site I worked on to a live environment.

Even though standard JavaScript minimisers remove comments, white space and use shorter variable names, we can take things a step further.

I found a great site that manages to render your code into complete jibberish. You can give it a go by going to: http://javascriptobfuscator.com/.

NOTE: Just as JavaScript code can be easily minimised, it can just as easily be “beautified” by going to: http://jsbeautifier.org/. Nevertheless, using the link above is a better deterrent when compared to other minimisers in my opinion.

Solving Flash Issues in Isotope jQuery Plugin

I’m using a jQuery plugin called “Isotope” to nicely output a mixture of news articles and advertising banners to a page.

I came across a small issue when using advertising banner’s in Flash format. For some reason, Flash content displayed randomly and mouse-clicks were not registered. This issue only seemed to only occur in Firefox. I couldn’t replicate this issue on other browsers.

Thankfully, only one additional line of code  needed to be added when when initially setting the Isotope plugin options:

$('#wall').isotope({
    itemSelector: '.box',
    animationEngine: 'css,
    layoutMode: 'masonry',
    transformsEnabled: false //Disable transformations
});

The following example helped me further in resolving my issue: http://isotope.metafizzy.co/tests/flash.html

Get CheckBoxList Values Using jQuery

To be able to retrieve values from a ASP.NET CheckBoxList control or a group of HTML checkboxes, use the following jQuery:

$(document).ready(function () {
    var checkboxValues = [];

    $('#<%=MyCheckBoxList.ClientID %> input[type=checkbox]').click(function () {
        $('input[type=checkbox]:checked').each(function () {
            checkboxValues.push(this.value);
        });        
    });
    
    var values = checkboxValues.toString(); //Output Format: 1,2,3
});

If you do use this code snippet on a CheckBoxList, take a look that this article on how to create a custom CheckBoxList control with a value attribute.

String.Format In JavaScript

Whenever I work with strings whilst programming in .NET, somewhere along the lines I always find myself using the awesome “string.format”. I think all of you will admit its the most useful and easiest way to build up your strings.

The only downside to using the “string.format” method is that it lures you into a false sense of security and you find yourself lost without it when it comes to working with strings in other languages. This happened to me when I had to build up a long string in JavaScript. It was long and tedious…or maybe I am just lazy.

Luckily, there have been a few developers who extended the string object in JavaScript to include “string.format”. Amazing! Its goes along the lines of adding this to your own JavaScript code:

String.format = String.prototype.format = function() {
    var i=0;
    var string = (typeof(this) == “function” && !(i++)) ? arguments[0] : this;

    for (; i < arguments.length; i++)
        string = string.replace(/\{\d+?\}/, arguments[i]);

    return string;
}

Here are some other useful links I have found on how to implement “string.format” into your JavaScript code:

Calling a ASP.NET Method Using jQuery

Over the last few months I have had the ability to mess around with a bit of jQuery. Even though I don’t have the complete understanding on how it works, I can see the benefits of writing my code in jQuery compared to bashing out lots of lines of JavaScript to do the same thing.

One the cool features I have used is calling one of my .NET methods using the “$.ajax” jQuery command. In my example (below), I have created two aspx pages. The code-behind of my first page  (jQueryMethodTest.aspx) will only contain a public static method called “WhatIsYourName”, which returns a string value.

[WebMethod]
public static string WhatIsYourName(string name)
{
    if (!String.IsNullOrEmpty(name))
    {
        return String.Concat("Hello ", name, "!");
    }
    else
    {
        return String.Empty;
    }
}

Remember, the jQueryMethodTest.aspx page only needs to contain our method nothing else! Additional methods can be added. Just don’t add any web controls.

The second page (jQueryAjax.aspx), will contain our jQuery code and some HTML to output our result from calling the “WhatIsYourName” method.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" language="javascript" src="javascript/jquery.js"></script>
</head>
<script type="text/javascript">
    $(document).ready(function() {
        $("#btnSubmitName").click(function(event) {
            $.ajax({
                type: "POST",
                url: "jQueryMethodTest.aspx/WhatIsYourName",
                data: "{'name': '" + $('#name').val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(message) {
                    ShowPopup(message);
                },
                error: NameFailed
            });
        });
    });

    function ShowPopup(result) {
        if (result.d != "") {
            $("#Message").html(result.d);
        }
        else {
            $("#Message").html("I didn't get your name.");
        }
    }

    function NameFailed(result) {
        $("#Message").html(result.status + ' ' + result.statusText);
    }  
  </script>  

<body>
    <form id="form1" runat="server">
    <div>
        <input id="name" name="name" type="text" />
        <br />
        <input id="btnSubmitName" name="btnSubmitName" type="button" value="Submit" />
        <br /><br />
        <span id="Message" style="color:Red;"></span>
    </div>
    </form>
</body>
</html>

If all goes well, you should get the following result:

Calling ASP Method Using jQuery

The “$.ajax” jQuery command requires the following parameters in order to work:

  • url – links to where our .NET method is placed.
  • data – retrieves the value from some control in our page to pass to our method. Remember, the name of the parameter must be named the same as the parameter from our .NET method.
  • dataType – the response type.
  • contentType – the request content type.
  • success – the JavaScript function that gets fired on postback.
  • error – the Javascript function that gets fired if there is a failure. This is an optional parameter.

 

I guess jQuery’s motto really is true: “write less, do more”.