Using JQuery Templates

Recently I was working on a project that required the user to add a date range then add the times for each day within that range. After looking into doing this the old fashioned, embed it in the javascript, way I decided to look at using jQuery templates where the content is defined in a templating language then loaded at run time and the data is injected into the template.

A case study
The project I was using this technology with required that the user select a start and end date then the interface would respond and create time picker fields for each day selected. The advantage of using the templates in this instance was that if anything needed to be changed in the template it would be far easier than if the html elements had been declared and added in jQuery.

A jQuery snippet adding dynamic html

var html ='
<div data-id="' +  obj.id + '">' +
'<img src="' + src + '" alt="" />' +
'<input class="linkto" type="text" value="' + obj.url + '" placeholder="Linked url" />' +
'<input class="remove-button button-primary" type="button" value="Remove Icon" data-id="' + obj.imageid +'" />' +
' <input class="moveup-button button-secondary" type="button" value="Move Up" />' +
'<input class="movedown-button button-secondary" type="button" value="Move Down" />' +
'</div>
';

A jQuery template:

<script id="dateTemplate" type="x-jquery-tmpl">
<div data-id="${id}">
	<img src="${src}" />
    <input type="text" class="linkto" placeholder="Linked url" value="${url}"/>
    <input type="button" class="remove-button button-primary" data-id="${imageid}" value="Remove Icon" />
    <input type="button" class="moveup-button button-secondary" value="Move Up">
    <input type="button" class="movedown-button button-secondary" value="Move Down">
</div>
</script>

The advantage here is that we can change this easily and we don’t have any nasty apostrophes all over the place. To get started with this technology head over to https://github.com/BorisMoore/jquery-tmpl and include a copy of the js in your project. After creating a template we can load it like so:

$.get('js/create/step_two/_date.tmpl.htm', function(templates) {
$('body').append(templates);
});

We then append and render the template using something like the following:

var item = {
day: weekday[dateTime.getDay()],
pId: id,
dId: i,
date : dateTime.getTime()
};
//Add the template
$('#dayTemplate').tmpl(item).appendTo(container);

Importantly jQuery templates have now been superseeded by JsRender: http://www.jsviews.com/#jsrender

The user is your friend…surely!?

Recently I’ve been encountering an increasing number of usability issues when visiting websites and accessing services and I feel it’s time to put a stop to these confusing and hard to use systems. When I visit a website I want to be able to get to the information quickly and easily but it never seems to be that easy, what I’m continually noticing is a trend of big companies with complex phone systems just trasferring that logic to their online offerings.

Don’t get me wrong, I’m a developer and often users are the enemy, they do things you don’t expect and end up with some mind boggling issues but I feel that is a good thing. What I’m talking about is the obscuring of information through complexity. I believe that simple is best and there has to be a better way!

Case Study One

Take the following example: I needed to cancel my home contents insurance policy due to a house move. This could have been a simple web form for me to send an enquiry and receive a confirmation call back however what I faced was this:

Claims Process

I continued to phone the correct number only to discover that they wanted me to key in only the numbers on my policy, when your policy number looks like the following ‘C12FQSK3D9D04B’ it becomes over complicated. What’s more, try doing that on a phone that goes dark every time you put it up to your ear and you have a serious usability problem. I think there would be a much more streamlined way of doing this if you could request a call back or resolve this online.

Case Study Two

This one really annoyed me as the user as I was doing something I didn’t really want to do anyway, paying council tax. (It should be noted at this point that I actually have previous experience in developing council websites).

Upon entering the home page there is no mention of council tax apart from a small quick link half way down on the right which isn’t ideal as most website users ignore that area of the screen, so I clicked services. This page is just a series of links, but I found and clicked ‘pay your council tax’, where did this go you ask? Well to a page that describes paying your council tax! The link for paying is half way down contained in a block of text.
Text Block

This is shown again further down :
Block Two

At this point I’ve already clicked twice and I just want a big shiny button that says pay online but I as a user am expected to read six lines of text to work out what the little link with an exclamation mark actually does. My favourite part of this is that the second link takes you to another page describing online payments!

Following the second link through brings you to a page of links with this :

Important

clicking this FINALLY takes me to the payments page. I’ve now clicked four times, had to scroll down twice, read an essay and lose the will to live all to find a single payment form.

Going the other route takes you to a third party system where you have to tediously navigate through and sign up etc to pay.

The point of all this is that websites and online systems need to really focus their design around the user and the activities that will be carried out on the site. The precursor to any website design and development work should be consultation on who will use the site and what their journey will be. Ultimately, we want every process to be simple and painless with as little room for error as possible. I’ve been involved in a number of projects where the design and development were created from a perspective of ‘this is what we want to show’ as opposed to ‘this is what the user will be looking for’ and I think we are seeing a shift in this mentality in website design and development. I believe that websites should be a service and as a such should be subject to the same efficiency critique as other services. The irony of this is that the result of a successful information site is that the user session time will be short! I can see another post on vanity metrics waiting to happen…

How to enable shortcodes for widgets in wordpress

This recently became a requirement of some simple work that I did creating a plugin that allowed a single piece of content to be added in wordpress then output using a shortcode. I added the shortcode to the text widget but it was simply output as a the shortcode itself. After some googling and hunting through forums I discovered the solution:

 add_filter('widget_text', 'do_myplugin_content_shortcode');

Or when in an object context use:

 add_filter('widget_text', array($this,'do_myplugin_content_shortcode'));

where the ‘do_myplugin_content_shortcode’ is the function that outputs the shortcode content.

JavaScript for Responsive Sites

When you have a responsive website there are many things that need consideration in terms of changes to the layout for each breakpoint. Often this can be done with pure CSS but occassionally there are instances where using CSS doesn’t quite manage to do what you need it to. Examples of this would be moving content blocks to different locations in the DOM or adding extra content based on the current screen size. I usually have a single script that I use to handle this functionality although I do sometimes do something a bit unusual, let me explain:

In our CSS we will see something like the following to define a breakpoint:

 @media(min-width:480px){
   //do something 
 }

The regular jQuery equivalent of this would be

  //do something 
   if((document).width() &gt;= 480){
   }

what I dislike about this is that we’re hard coding values into our javascript and once we have three or more breakpoints it can become confusing and leave us with multiple changes that need to be made if we want to update a breakpoint or add a new one. Another drawback of this is that on occcasion the measured width in JavaScript can be different to the width in the CSS at a certain point leading to the JavaScript functionality not executing when the CSS layout has been triggered which is something we don’t want.

I get around this using a div, that’s right a div. I like to add an empty div as the first element in the body and give it an id eg. responsive div. Then in the CSS I will have something like the following:

#responsivediv{
 z-index:0; 
 width:100%;
}

@media(min-width:480px){
   #responsivediv{
   z-index:1; 
  } 
}

@media(min-width:768px){
   #responsivediv{
   z-index:2; 
  } 
}

Then I can use the z-index as a guide to which breakpoint the layout is currently in, this will be the same in the CSS and JavaScript and gets around that issue. This approach also means that the breakpoint value can be changed in the CSS without the JavaScript needing to be modified.

The following is a real life example of how I’ve used this in practice.

var previousIndex = 0;
var zIndex = parseInt($('#responsivediv').css('z-index'));

/*
* On Resize, respond as appropriate
*/
$(window).resize(function () {
  //Get the zindex and the previous
  var viewLevel = parseInt($('#responsivediv').css('z-index'));

  //If we passed a breakpoint
  if (previousIndex != viewLevel) {
    for (var i = 0; i &lt; mItems.length; i++) {
       mItems[i].Resize(viewLevel);
    }
    previousIndex = viewLevel;
  }
});

An example of one of the items in the MItems array would be a carousel that needs to be paused when the user is in mobile view as it has been restyled as a list. This would look like the following (using an object oriented approach to JavaScript)


var Carousel = {
  exists: false,
  Init: function (level) {
    //Initialize
    this.exists = $('.carousel').length &gt; 0 ? true : false;
  },
  Resize: function (viewLevel) {
    //It's broke so return
    if (!this.exists) {
      return false;
    }

    //Disable the carousel in responsive.
    if (viewLevel === 0) {
      if (!$('.carousel').hasClass('paused')) {
        //Pause the carousel
        $('.carousel').carousel('pause');
        $('.carousel').addClass('paused');
      }
    } else {
      if ($('.carousel').hasClass('paused')) {
        //Pause the carousel
        $('.carousel').carousel('cycle');
        $('.carousel').removeClass('paused');
     }
   }
  }
};

Wrapping Tables

One other thing I commonly include in my Javascripts is a wrapper around all tables that just adds a horizontal scroll in the mobile view. I usually achieve this using the following code.

$('table').each(function () {
  $(this).css('min-width', '500px');
  $(this).wrap('&lt;div class="tablewrapper" style="width:100%; overflow:auto;"&gt;&lt;/div&gt;');
});

I feel that this approach to responsive JavaScript greatly simplifies the process and allows for an inter connectivity between the JavaScript and CSS that you don’t get when using regular methods for breakpoints.

Simple CSS image Zooming

Recently I’ve see a rise in the effect of an image zooming when the user hovers over it. This movement provides feedback to the user and the added movement should improve engagement.

I had a little look into this and it can be achieved with very few lines of code. An example of the effect is shown below.

How it’s done

The html is structured as follows:

<code>&lt;div id=&quot;bgzoom&quot; style=&quot;width:300px; height:225px;&quot;&gt; 
 &lt;a style=&quot;background-image:url('http://www.htmlstudio.co.uk/wp-content/uploads/2015/03/black-and-white-cat-1395009210V6g.jpg');&quot;&gt;&lt;/a&gt; 
&lt;/div&gt;
</code>

Obviously you could have all of the styles in an external stylesheet but this is often a little impractical when using a CMS and allowing the admin to modify the background images.

The CSS is output as follows :

#bgzoom{
  overflow:hidden;
}
#bgzoom a{
     display:block;
     width:300px;
     height:225px;
     background-repeat:no-repeat;
     background-position:center center;
     background-size:cover;
     -webkit-transition: all 0.5s ;
     transition:all 0.5s;
}
#bgzoom a:hover{
    transform: scale(1.15,1.15); 
    -webkit-transform:scale(1.15,1.15); 
    -moz-transform:scale(1.15,1.15); 
    -ms-transform:scale(1.15,1.15); 
    -o-transform:scale(1.15,1.15);
     -webkit-transition: all 0.5s ;
     transition:all 0.5s;
}

The key element here is the transform function which scales the anchor tag by 115% in the x and y directions. The overflow on the parent tag takes care of any overflow caused by this and creates a nice zoom effect. I have applied a transition to make the whole thing appear smooth.

Scaling with background images IE8

Occasionally you may have the need to make some parts of a reponsive site work in IE8 as painful as that is. Often background images are used in newer browsers and scaled to fit their element. In IE this doesn’t work that well so the following jQuery snippet allows you to get rid of the background image that has been set and replace it with an IE specific filter that should resolve this issue. This is best used when the background image has been set using inline CSS (which often happens in content managed sites)

           var image = $(this).css('background-image');  
           image = image.replace('url("',"").replace('")',"");                                             
           $(this).css('filter',"progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + image + ", sizingMethod='scale'");     
           $(this).css('-ms-filter',"progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + image +  ", sizingMethod='scale')");             
           $(this).css('background-image',"none"); 

Combine this with my solution for detecting if the user is using IE 8 and a you have a useful solution.

 if (!$.support.leadingWhitespace) {
            if ($.browser.msie && parseFloat($.browser.version) <= 8) {
                var image = $(this).css('background-image');  
                image = image.replace('url("',"").replace('")',"");                                             
                $(this).css('filter',"progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + image + ", sizingMethod='scale'");     
                $(this).css('-ms-filter',"progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + image +  ", sizingMethod='scale')");             
                $(this).css('background-image',"none"); 
            }
        }

Adding an External Link Icon using Font Awesome and JQuery

Sometimes you need to add an icon to your external links to mark them out as different to your regular site links. This makes sense in terms of usability as it stops users becoming suprised that they are taken away from your site on clicking the link. I recently worked on a site where one of the links read ‘University’ and was an external link. On the surface of it that would be difficult for a human user to differentiate as being an external link.

It can be an absolute maintenance nightmare and lead to massive code bloating if you try to add an icon after every external link using your server side language or CSS. I’ve seen it a few times and it’s caused hours of wasted development time and effort. This is why I rely on a javascript based solution as then when a change happens it only occurs in a single place rather than a few. Don’t get me wrong, it can be done on the server side or in the CSS but it’s my preference to make the user’s browser do the work for this.

I achieve this using jQuery and Font awesome to add a little icon after all external links. In my main script file, inside the standard $(document).ready function I add the following:

 

<code>
/*
* InitExternal
* Initialise external links
*/
var comp = location.host;

$('a').each(function () {
  //Get the link
  var link = undefined === $(this).attr('href') ? '' : $(this).attr('href');
  if (link != '' &amp;&amp; link.indexOf(comp) &lt;= -1 &amp;&amp; link.length &gt; 0) {
    if ($(this).text().trim().length == 0 || link.indexOf('javascript(') &gt; -1) {
      return;
    }

    if (link.charAt(0) != '/' &amp;&amp; link.charAt(0) != '#') {
       $(this).append('&lt;i class="fa fa-external-link external-link"&gt;&lt;/i&gt;');
       $(this).attr('target', '_blank');
    }
  }
});
</code>

 

The code analyses each a tag and checks for an href, without this there’s no point in continuing for that item. It then looks for whether the link has any inner content or whether it’s meant to invoke a javaScript function, if these cases match then it ignores that link. It then checks for invalid starting characters such as ‘#’ or ‘/’ . Finally it can add the icon and set the target to blank to mark the link as external. There may be permutations on your site where this doesn’t quite work, one such case is when the a tag is empty but has been used as an image box with a background image. In that case you could add

<code>
if($(this).css('background-image')){
      return;
}
</code>

The output :
Exteral Link Icon
 

Detecting Internet Explorer using JavaScript

Sometimes in JavaScript you need to detect whether the current user is using IE8 or below as generally support should be maintained for the previous three versions of IE (my opinion) and therefore the user may need to be prompted that perhaps they aren’t getting the best experience.
The script below checks the user’s browser capability for leading whitespace see: (http://stackoverflow.com/questions/8890460/how-to-detect-ie7-and-ie8-using-jquery-support) and then checks the browser version. This is because firefox doesn’t seem to support leading whitespace in all versions so the browser version then needs to be checked.

    
 if (!$.support.leadingWhitespace) {
            if ($.browser.msie && parseFloat($.browser.version) <= 8) {
                alert('This website is best viewed in Internet Explorer 9 and above, please upgrade your browser for the best experience.');
            }
        }

In this example an alert is shown but you could easily add a custom stylesheet or perform some other useful function.

An introduction to codeigniter

Codeigniter is my MVC framework of choice when working with PHP as it is straightforward and lightweight. MVC stands for Model View Controller which is a software development method that takes revolves around separating the data layer (the model), the business logic (controller) and the layout (the view). The idea behind this is that the software produced is easier to maintain and more robust than with other types of development, I think this is particularly prevalent in PHP where the ‘code behind’ model or inline PHP is often seen.

I particularly like the way that Codeigniter handles forms and validation and it allows the developer to keep the code clean and free from clutter.

Getting Started
To get started in Codeigniter head over to: http://www.codeigniter.com/ and download the latest version. Install this on your development server and you’re ready to get started.

Codeigniter Anatomy
The installed folder contains a system folder, an application folder and some other bits that we don’t really need to worry about. What we’re interested in is the application folder.

Initially there is a single controller in the controller folder with a single function: index() This function loads the ‘welcome_message’ view. Each public function inside of a controller generally is used to represent a page or response to a HTTP request. Other functions may be added but should generally be marked as private or protected to prevent them from being invoked by site users.

It is important to note here that convention is very important in MVC. A public function in a controller can be invoked via a HTTP request. Consider the following controller:

class Welcome extends CI_Controller {
     public function index(){
	 $this->load->view('welcome_message');
     }

     public function show(){
            $this->load->view('welcome_message_2');
     }
}

In this instance the show function can be executed using the following request:
www.test.com/index.php/Welcome/show

and the index function can be executed using the following request:
www.test.com/index.php/Welcome/index

however, the index function can also be executed using the following request
www.test.com/index.php/Welcome/

This is because the default function for a controller is the index function. A standard url in Codeigniter will consist of a Controller/Function/Variables

The Model
The default installation in Codeigniter does not come with a model installed however this is where the data will be loaded and manipulated, this will more often than not involve database interactions.

The View

 $this->load->view('welcome_message');

This function loads the view named ‘welcome_message.php’ in the view folder of the application and displays it to the end user.

Routes
In the config folder is a file called routes.php. This is an important file in Codeigniter as it allows you to map your URI requests to specific controllers and classes. The initial install only contains the following route :

$route['default_controller'] = "welcome";

If for some inexplicable reason we wanted to create a URI for our previous show function in the Welcome controller via the following url : www.test.com/index.php/yo/ we could create the following route :

$route['yo'] = "welcome/show";

Which maps our request onto the appropriate Controller and method.

That’s all for now, in the next post I will cover the basics of creating a Codeigniter Application.

Running codeigniter inside another application

Sometimes you may have the need to run codeigniter inside of another application, I often do this for client work when I need to install multiple codeigniter instances on my development server. This can cause nightmarish consequences and many hours of running around in circles if this isn’t done correctly.

Initially deploying the application is fine but you must ensure that the url of the codeigniter subfolder is entered directly and does not match any existing routes in your main application. It may be necessary to add a htaccess in to your sub-application that allows access to that folder.

The important thing is to set the base_url in the config file for your Codeigniter application :

$config['base_url'] = 'http://www.example.com/testsite/';

You may then have issues with relative links inside your child application, the solution to this is to set the base href in the header of each page of the sub-application

  &lt;base href="&lt;?php echo base_url();?&gt;"/>
To the top
css.php