Preventing console.log issues in IE

In some older browsers, including versions of Internet Explorer, window.console doesn’t exist and therefore calling console.log() will result in an error.

One way of fixing this is to create a function which checks whether console exists and use this function instead:

function consolelog(v){
    if (window.console
        && window.console.log){
        window.console.log(v);
    }
}

However this requires all developers knowing about this function, and if someone forgets and directly calls console.log() then older browsers will still throw an error.

Therefore a better solution is to check whether console.log() exists, and if not, create an empty function which prevents the error occurring.

if (!(window.console
    && window.console.log)){
    window.console = {
       log:function(v){return;}
    }
}

Round to the nearest decimal

If we need round to the nearest whole number, we can use the Math.round() function to return this:

Math.round(1.34234); //returns 1

However what if we need to round to a decimal place? For example 0.5.

The following function can be used to do just that, and the logic itself can be adapted to be used for other languages too (C#, SQL etc).

function roundToMultiple(value, multiple){
    var t = (1/multiple);
    return (Math.round(value*t)/t).toFixed(2);
}

This can then be used like so:

roundToMultiple(1.34234, 0.5);  //returns 1.50
roundToMultiple(1.34234, 0.25); //returns 1.25
roundToMultiple(1.34234, 0.1);  //returns 1.30
roundToMultiple(1.34234, 0.05); //returns 1.35

It can also be used to round to values greater than 1:

roundToMultiple(25.3423423, 4); //returns 24.00

Mixing Revealing Module and Singleton Javascript Patterns

Until recently I’ve been using the Singleton pattern for my javascript objects.

This works well as my functions are namespaced and therefore the risk of clashing object names across Javascript files is reduced.

For this example I’ve created a singleton pattern javascript object which will show an alert window displaying “hello world”.

var MyFunction = {
   Init: function(){
      this.Config.foo = "hello world";
   },
   Config:{
      foo:null
   },
   ShowAlert:function(){
      alert(this.Config.foo);
   }
}

MyFunction.Init();
MyFunction.ShowAlert();

View Demo

With this object it’s possible for me to change the value of foo so that the alert displays a different message.

MyFunction.Init();
MyFunction.Config.foo = "lorem ipsum";
MyFunction.ShowAlert();

View Demo

However, what if I didn’t want it to be possible to change foo outside of the MyFunction object itself? This is where the “Revealing Module” javascript pattern comes in use.

Using the Revealing Module pattern we can encapsulate “private” functions and expose only the functions that we wish to.

var MyFunction = function(){

    var foo = null;

    function Init(){
      foo = "hello world";   
    }

    function ShowAlert(){
     alert(foo);   
    }

    return {
        Init: Init,
        ShowAlert: ShowAlert
    };
}();

MyFunction.Init();
MyFunction.ShowAlert();

View Demo

With this pattern only Init and ShowAlert are exposed outside of the object. Outside the scope of MyFunction its not possible to change foo.

This works great, but I believe it loses the organisation and scale-ability of the singleton pattern.

Therefore we can change the functions in MyFunction to use a Singleton pattern and expose functions from with this inner object using the Revealing Module pattern:

var MyFunction = function(){

    var _ = {
       Init: function(){
          _.Config.foo = "hello world";
       },
       Config:{
          foo:null
       },
       ShowAlert:function(){
          alert(_.Config.foo);
       }
    }

    return {
        Init: _.Init,
        ShowAlert: _.ShowAlert
    };
}();

MyFunction.Init();
MyFunction.ShowAlert();

View Demo

Another additional benefit of this mixed pattern is that we can have a complex singleton structure, which can expose particular functions with more “friendly” names.

Using our existing example, ShowAlert might be nested inside other objects:

var MyFunction = {
   Init: function(){
      this.Config.foo = "hello world";
   },
   Config:{
      foo:null
   },
   UI:{
        Display:{
            ShowAlert:function(){
                alert(MyFunction.Config.foo);
            }
        }
    }
}

With the Singleton pattern we would have to call MyFunction.UI.Display.ShowAlert.

With the Module/Singleton pattern this can be exposed as just ShowAlert despite its more complex position in the object structure.

var MyFunction = function(){

    var _ = {
       Init: function(){
          _.Config.foo = "hello world";
       },
       Config:{
          foo:null
       },
       UI:{
            Display:{
                ShowAlert:function(){
                    alert(_.Config.foo);
                },
            }
        }
    }

    return {
        Init: _.Init,
        ShowAlert: _.UI.Display.ShowAlert
    };
}();

MyFunction.Init();
MyFunction.ShowAlert();

View Demo

I’m still reasonably new to adopting this Singleton/Module pattern mix-up, so if you have any suggestions or questions, all comments are welcome!

What is cache busting?

A cache-buster is a unique string which is appended to a URL in the form of a query string.

It is generally not read by the server-side and is used purely to form a unique URL. For example:

/Scripts/foo.js?v=1

This is often used on client side files such as Javascript, CSS and Images in order to force a browser/cache-system to retrieve the latest version of a file from its source.

When a webpage is downloaded, any associated files are also downloaded and stored in the browser’s cache. This is for performance purposes so that the webpage doesn’t have to download the files every time the page is refreshed.

However, as a developer, if you are to make a change to any of those files, you need to ensure the client will download the latest version.

Therefore the cache-buster query string can be updated so that the browser doesn’t recognise the file in it’s cache and downloads a new version.

Here a different types of cache-buster methods you can use:

Static Cache-Buster

When the file is updated, all references to the file could be manually updated to increment a version number.

For example:

<script type="text/javascript" src="/Scripts/foo.js?v=1"></script>

Becomes:

<script type="text/javascript" src="/Scripts/foo.js?v=2"></script>

However this isn’t a clean solution because this task will have to be carried out every time the file is updated. And in cases where its forgotten, browsers will potentially still use an older version of the file.

Date/Time Cache-Buster

The current date/time could be appended to the reference so that every call to the webpage will return a unique cache-buster. For example this can be done like so in .NET MVC:

<script type="text/javascript" src="@string.Format("/Scripts/foo.js?v={0}", DateTime.Now.Ticks)"></script>

However this won’t be great for performance, and defeats the point of browsers caching files at all.

Software Version Cache-Buster

Another method of cache-busting is to use the Software Version of the application. This ensures that whenever a new version of the application is deployed, the cache-buster will be updated:

<script type="text/javascript" src="/Scripts/foo.js?v=2014.9.25.75285"></script>

The down-side to this method is that a change could be made to the application which creates a new version number even when a change to the file has not been made. In which case the browser would download the file again when it already has the file stored locally in cache.

Hashed-Content Cache-Buster

My preferred method of cache-busting is to create a hash of the content and use this as the cache-buster.

This is the same method that ASP.NET MVC Bundling & Minification uses for it’s cache-busting.

<script type="text/javascript" src="/Scripts/foo.js?v=r0sLDicvP58AIXN_mc3QdyVvVj5euZNzdsa2N1PKvb81"></script>

Whichever method you choose, cache-busting is a great way to ensure your clients are using the most up-to-date version of your files.

Quickly create HTML elements in jsFiddle

In case you haven’t already heard of it, jsFiddle is a web application which allows you to enter HTML, CSS and Javascript into different windows and render the output. It’s a great tool for testing various front-end concepts, and then “fiddles” can be saved and shared.

Because of this feature it’s a popular tool on StackOverflow for demonstrating issues/solutions.

One feature I’ve come across is the ability to quickly create elements in the HTML window by using CSS selectors. This makes jsFiddle even more quick and easy to create demos!

For example if I write the following in the HTML window:

div#a.b

And then hit tab, this will be converted to:

<div id="a" class="b"></div>

Awesome!

This can be taken a step further to include nested elements:

div#a.b>span.c

Which will produce:

<div id="a" class="b"><span class="c"></span></div>

Or we can create multiple nested elements:

div#a.b>span.c+span.d

Which will produce:

<div id="a" class="b"><span class="c"></span><span class="d"></span></div>

Finally we can also add other attributes in the same way we would select them in CSS:

a[href='http://curtistimson.co.uk']

Which produces:

<a href="http://curtistimson.co.uk"></a>

jsfiddle

Abstract config settings from web.config

In ASP.NET, application settings can be specified in the web.config file such as:

<appSettings>
    <add key="PostsPerPage" value="6" />
    <add key="CookieName" value="Foo" />
</appSettings>

The beauty of this is that you don’t need to edit code to make changes to the application, and a single pre-compiled application can be used across multiple environments with different settings.

However, there are times when an application can have 100′s of configuration settings, which will bloat the size of the web.config file.

Therefore in these instances it’s best to abstract the application settings away from the main web.config file.

To do this a configSource attribute can be applied to the appSettings node of the web.config with a path to a seperate config file:

<appSettings configSource="Config\AppSettings.config" />

Then the Config\AppSettings.config can contain the appSettings node which would usually be in the web.config:

<appSettings>
    <add key="PostsPerPage" value="6" />
    <add key="CookieName" value="Foo" />
</appSettings>

Copy table schema to new a table

In SQL Server, SELECT INTO is used to copy data from an existing table/s into a new one.

However by adding a WHERE clause which will always return false, this will prevent any data from being copied, and therefore create an empty copy of the table schema into a new table.

For example if we have a table, “TableA”, the schema of this table can be copied into a new table, “TableB”, by executing the following:

SELECT *
INTO TableB
FROM TableA
WHERE 1=0

Create a flashing tab notification page title

Page title notifications switch between the default page title and a notification message continously in order to grab the user’s attention. This is commonly used with chat applications.

newchatmessage

I’ve written a small javascript object which can be used to switch on and off page title notifications.

To activate the page title notification call the following:

PageTitleNotification.On("New Chat Message!");

Then call the following to turn it off:

PageTitleNotification.Off();

The default speed is 1000 milliseconds, but this can be customised by passing a 2nd parameter to the On() function.

PageTitleNotification.On("New Chat Message!", 5000);

Download
To use this download the minified javascript version here:

PageTitleNotification.min_.js

Or you can use the un-minified source code here:

var PageTitleNotification = {
    Vars:{
        OriginalTitle: document.title,
        Interval: null
    },    
    On: function(notification, intervalSpeed){
        var _this = this;
        _this.Vars.Interval = setInterval(function(){
             document.title = (_this.Vars.OriginalTitle == document.title)
                                 ? notification
                                 : _this.Vars.OriginalTitle;
        }, (intervalSpeed) ? intervalSpeed : 1000);
    },
    Off: function(){
        clearInterval(this.Vars.Interval);
        document.title = this.Vars.OriginalTitle;   
    }
}

View Demo
http://fiddle.jshell.net/Curt/w8QBM/show/light/

Hope this comes in help, comment if you have any issues/suggestions!

Namespacing jQuery event handlers

If we are to attach 2 or more event handlers to an element these will become stacked and run linear in the order they were attached.

For example:

$(".foo").on("click", function(e){
    console.log("bar");
});

$(".foo").on("click", function(e){
    console.log("baz");
});

If .foo is then clicked, the browser console will log:

"bar"
"baz"

If we wish to remove these event handlers we can call:

$(".foo").off("click");

Simple.

However, what if we wish to only remove 1 of these event handlers and retain the other? This is where jQuery event namespacing comes in handy.

When adding the event handlers we can include a namespace name which will act as a reference when removing the event:

$(".foo").on("click.barevent", function(e){
   console.log("bar");
});

$(".foo").on("click.bazevent", function(e){
   console.log("baz");
});

Here click has been changed to click.xxxx where xxxx is the name of the namespace for this particular event handler.

With this in place we can remove 1 of the event handlers by referencing it’s namespace when calling .off().

For example if we wish to remove only the “bar” console log, we can call:

$(".foo").off("click.barevent");

Therefore if .foo is then clicked, the browser console will only log:

"baz"

Default negative variables to zero in javascript

If you need to default a value to 0 if its negative, you could do:

var i = -45;
if (i<0){
    i = 0;
}
console.log(i); //0

However, a shorter way of doing this would be to use Math.max() passing 0 as one of the parameters:

var i = -45;
i = Math.max(0,i);
console.log(i); //0

Likewise Math.min() can be used to set a maximum value:

var i = 999;
i = Math.min(500,i);
console.log(i); //500

Or combine the two to set an available range. For example a percentage variable could be sanitised to ensure its between 0 and 100:

function sanitisePercentage(i){
    return Math.min(100,Math.max(0,i));   
}

console.log(sanitisePercentage(50));    //50
console.log(sanitisePercentage(99999)); //100
console.log(sanitisePercentage(-123));  //0

View Demo

© 2014 Curtis Timson

Theme by Anders NorenUp ↑