Archive for the ‘Mobile’ Category

As responsive design rapidly increases in popularity, we felt we would take a look at some of the varied solutions and techniques that are being adopted for managing the navigation/menu on smaller screened devices.

Planning and building your menu for mobiles will perhaps be the trickiest aspect of your responsive layout, not just with the coding but also having to decide what will stay and what will have to go to fit everything into the smaller screen. It is a juggling act between both readability and the desire to show as much on the screen as possible.

Hopefully the solutions we have for you below will help get you on your way.

Menu I used:-


Progressive And Responsive Navigation (Tutorial)

Progressive And Responsive Navigation

This tutorial, from Smashing Magazine, takes you through the steps for coding your navigation using a little forethought and considering the principles of progressive enhancement from the beginning and applying some responsive practices at the end, allowing your navigation to easily accommodate less-capable browsers and modern browsers in both desktop and mobile environments.

Progressive And Responsive Navigation →Demo →

Responsive Navigation Menu (Tutorial)

Responsive Navigation Menu

With this tutorial you will learn how to code a simple and effective responsive navigation menu, with a grid layout, that you will be able to easily modify and reuse in your own projects.

Responsive Navigation Menu →Demo →

TinyNav.js (jQuery Plugin)


TinyNav.js is a tiny jQuery plugin (362 bytes minified and gzipped) that converts <ul> and <ol> navigations to a select dropdowns for small screens. It also automatically selects the current page and adds selected="selected" for that item.

TinyNav.js →Demo →

Responsive Drop Down Navigation Menu (Tutorial)

Responsive Drop Down Navigation Menu

The code for this menu is based on the famous Suckerfish Dropdown menu, restyled to make it responsive. It will work great in all modern desktop browsers without Javascript.

Responsive Drop Down Navigation Menu →Demo →

HorizontalNav (jQuery Plugin)


HorizontalNav is a jQuery plugin that spans a horizontal navigation to fit the full width of it’s container. It comes with an option to make it responsive, allowing the navigation to auto-adjust when the window is resized.

HorizontalNav →

Responsive, Mobile-First Navigation Menu (Tutorial)

Responsive, Mobile-First Navigation Menu

This tutorial demonstrates how to develop a complex responsive navigation menu using the “Mobile-First Approach”. The aim is to present mobile users with a pseudo-native, touch-conducive and interactive interface that enables them to navigate the website with ease.

Responsive, Mobile-First Navigation Menu →Demo →

SelectNav.js (Javascript Plugin)


SelectNav.js is a JavaScript plugin that lets you convert your website navigation into a <select> drop-down menu. Used together with media queries it helps you to create a space saving, responsive navigation for small screen devices.

SelectNav.js →Demo →

Convert a Menu to a Dropdown for Small Screens (Tutorial)

Convert a Menu to a Dropdown for Small Screens

Convert a Menu to a Dropdown for Small Screens →Demo →

Simple Responsive Menu

Simple Responsive Menu

This tutorial takes a typical desktop menu and shows you how to, using Modernizr, jQuery and media queries, convert it to a small menu button for smaller screens that only appears when pressed, and pressing it again will retract it.

Simple Responsive Menu →

Mobile Menu (jQuery Plugin)

Mobile Menu

Mobile Menu is a jQuery plugin that turns your site’s navigation into a dropdown (<select>) when your browser is at mobile widths. It comes with a handful of options, including the really useful “combine”, that allows you to convert multiple navigation lists into a single dropdown.

Mobile Menu →


Detect Mobile User Agents & Browsers

Posted: January 31, 2012 in Mobile

Helping detect and better serve mobile browsers

Follow us on Twitter for updates! DetectMobiles

This PHP function lets you choose how to manage your mobile visitors, they can be redirected to a page built for mobiles or you can use it to decide which markup language and stylesheet to show that user.

It’s main function is to answer this question:

Is this visitor to my website using a mobile phone or PC?

Download Code

Download the code, unzip the archive then upload it to your website. Then view the usage guide or use the function generator to build a custom function to suit you and your mobile visitors.


Usage guide

It’s not rocket science, it’s easy to use!

But you need to understand at least basic PHP to get it working.

You need to include the file with the function then call the function before your PHP pages do anything else. See Support.

$mobile = mobile_device_detect();

The function has eight parameters that can be passed to it which define the way it handles different scenarios. These paramaters are:

  • iPhone – Set to true to treat iPhones as mobiles, false to treat them like full browsers or set a URL (including http://) to redirect iPhones and iPods to.
  • iPad – Set to true to treat iPads as mobiles, false to treat them like full browsers or set a URL (including http://) to redirect iPads to.
  • Android – Set to true to treat Android handsets as mobiles, false to treat them like full browsers or set a URL (including http://) to redirect Android and Google mobile users to.
  • Opera Mini – Set to true to treat Opera Mini like a mobile, false to treat it like full browser or set a URL (including http://) to redirect Opera Mini users to.
  • Blackberry – Set to true to treat Blackberry like a mobile, false to treat it like full browser or set a URL (including http://) to redirect Blackberry users to.
  • Palm – Set to true to treat Palm OS like a mobile, false to treat it like full browser or set a URL (including http://) to redirect Palm OS users to.
  • Windows – Set to true to treat Windows Mobiles like a mobile, false to treat it like full browser or set a URL (including http://) to redirect Windows Mobile users to.
  • Mobile Redirect URL – This should be full web address (including http://) of the site (or page) you want to send mobile visitors to. Leaving this blank will make the script return true when it detects a mobile.
  • Desktop Redirect URL – This should be full web address (including http://) of the site (or page) you want to send non-mobile visitors to. Leaving this blank will make the script return false when it fails to detect a mobile.


This is the second part of a two-part tutorial, in which we use PHP, MySQL and jQuery mobile to build a simple computer web store. In the previous part we created the models and the controllers, and this time we will be writing our views.

jQuery mobile

First, lets say a few words about the library we will be using. jQuery mobile is a user interface library that sits on top of jQuery and provides support for a wide array of devices in the form of ready to use widgets and a touch-friendly development environment. It is still in beta, but upgrading to the official 1.0 release will be as simple as swapping a CDN URL.

The library is built around progressive enhancement. You, as the developer, only need to concern yourself with outputting the correct HTML, and the library will take care of the rest. jQuery mobile makes use of the HTML5 data- attributes and by adding them, you instruct the library how it should render your markup.

In this tutorial we will be using some of the interface components that this library gives us – lists, header and footer bars and buttons, all of which are defined using the data-role attributes, which you will see in use in the next section.

Rendering Views

The views are PHP files, or templates, that generate HTML code. They are printed by the controllers using the render() helper function. We have 7 views in use for this website – _category.php, _product.php, _header.php, _footer.php, category.php, home.php and error.php, which are discussed later on. First, here is render() function:


/* These are helper functions */

function render($template,$vars = array()){

	// This function takes the name of a template and
	// a list of variables, and renders it.

	// This will create variables from the array:

	// It can also take an array of objects
	// instead of a template name.

		// If an array was passed, it will loop
		// through it, and include a partial view
		foreach($template as $k){

			// This will create a local variable
			// with the name of the object's class

			$cl = strtolower(get_class($k));
			$$cl = $k;

			include "views/_$cl.php";

	else {
		include "views/$template.php";

The first argument of this function is the name of the template file in the views/ folder (without the .php extension). The next is an array with arguments. These are extracted and form real variables which you can use in your template.

There is one more way this function can be called – instead of a template name, you can pass an array with objects. If you recall from last time, this is what is returned by using the find() method. So basically if you pass the result of Category::find() to render, the function will loop through the array, get the class names of the objects inside it, and automatically include the _category.php template for each one. Some frameworks (Rails for example) call these partials.

Computer Store with PHP, MySQL and jQuery MobileComputer Store with PHP, MySQL and jQuery Mobile

The Views

Lets start off with the first view – the header. You can see that this template is simply the top part of a regular HTML5 page with interleaved PHP code. This view is used in home.php and category.php to promote code reuse.


<!DOCTYPE html>
	<title><?php echo formatTitle($title)?></title> 

	<meta name="viewport" content="width=device-width, initial-scale=1" /> 

	<link rel="stylesheet" href="" />
    <link rel="stylesheet" href="assets/css/styles.css" />
	<script type="text/javascript" src=""></script>
	<script type="text/javascript" src=""></script>

<div data-role="page">

	<div data-role="header" data-theme="b">
	    <a href="./" data-icon="home" data-iconpos="notext" data-transition="fade">Home</a>
		<h1><?php echo $title?></h1>

	<div data-role="content">

In the head section we include jQuery and jQuery mobile from jQuery’s CDN, and two stylesheets. The body section is where it gets interesting. We define a div with the data-role=”page” attribute. This, along with the data-role=”content” div, are the two elements required by the library to be present on every page.

The data-role=”header” div is transformed into a header bar. The data-theme attribute chooses one of the 5 standard themes. Inside it, we have a link that is assigned a home icon, and has its text hidden. jQuery Mobile comes with a set of icons you can choose from.

The closing tags (and the footer bar) reside in the _footer.php view:



	<div data-role="footer" id="pageFooter">
		<h4><?php echo $GLOBALS['defaultFooter']?></h4>


Nothing too fancy here. We only have a div with the data-role=”footer” attribute, and inside it we print the globally accessible $defaultFooter variable, defined in includes/config.php.

Neither of the above views are printed directly by our controllers. They are instead used by category.php and home.php:


<?php render('_header',array('title'=>$title))?>

<p>Welcome! This is a demo for a ...</p>
<p>Remember to try browsing this ...</p>

<ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b">
    <li data-role="list-divider">Choose a product category</li>
    <?php render($content) ?>

<?php render('_footer')?>

If you may recall, the home view was rendered in the home controller. There we passed an array with all the categories, which is available here as $content. So what this view does, is to print the header, and footer, define a jQuery mobile listview (using the data-role attribute), and generate the markup of the categories passed by the controller, using this template (used implicitly by render()):


<li <?php echo ($active == $category->id ? 'data-theme="a"' : '') ?>>
<a href="?category=<?php echo $category->id?>" data-transition="fade">
	<?php echo $category->name ?>
    <span><?php echo $category->contains?></span></a>

Notice that we have a $category PHP variable that points to the actual object this view is being generated for. This is done in lines 24/25 of the render function. When the user clicks one of the links generated by the above fragment, he will be taken to the /?category=someid url, which will show the category.php view, given below.

<?php render('_header',array('title'=>$title))?>

	<ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="c">
        <?php render($products) ?>

    <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b">
        <li data-role="list-divider">Categories</li>
        <?php render($categories,array('active'=>$_GET['category'])) ?>

<?php render('_footer')?>

This file also uses the header, footer and _category views, but it also presents a column with products (passed by the category controller). The products are rendered using the _product.php partial:

	<img src="assets/img/<?php echo $product->id ?>.jpg" alt="<?php echo $product->name ?>" />
	<?php echo $product->name ?> <i><?php echo $product->manufacturer?></i>
	<b>$<?php echo $product->price?></b>

As we have an image as the first child of the li elements, it is automatically displayed as an 80px thumbnail by jQuery mobile.

One of the advantages to using the interface components defined in the library is that they are automatically scaled to the width of the device. But what about the columns we defined above? We will need to style them ourselves with some CSS3 magic:


media all and (min-width: 650px){




.product i{

.product img{

.product b{
	position: absolute;
	right: 15px;
	top: 15px;
	font-size: 0.9em;

	height: 80px;

Using a media query, we tell the browser that if the view area is wider than 650px, it should display the columns side by side. If it is not (or if the browser does not support media queries) they will be displayed one on top of the other, the regular “block” behavior.

We’re done!

In the second and last part of this tutorial, we wrote our views to leverage the wonderful features of jQuery mobile. With minimal effort on our part, we were able to describe the roles of our markup and easily create a fully fledged mobile website.


In this two-part tutorial, we will be building a simple website with PHP and MySQL, using the Model-View-Controller (MVC) pattern. Finally, with the help of the jQuery Mobile framework, we will turn it into a touch-friendly mobile website, that works on any device and screen size.

In this first part, we concentrate on the backend, discussing the database and MVC organization. In part two, we are writing the views and integrating jQuery Mobile.

The File Structure

As we will be implementing the MVC pattern (in effect writing a simple micro-framework), it is natural to split our site structure into different folders for the models, views and controllers. Don’t let the number of files scare you – although we are using a lot of files, the code is concise and easy to follow.

The Directory StructureThe Directory Structure

The Database Schema

Our simple application operates with two types of resources – categories and products. These are given their own tables – jqm_categories, and jqm_products. Each product has a category field, which assigns it to a category.

jqm_categories Table Structurejqm_categories Table Structure

The categories table has an ID field, a name and a contains column, which shows how many products there are in each category.

jqm_products Table Structurejqm_products Table Structure

The product table has a name, manufacturer, price and a category field. The latter holds the ID of the category the product is added to.

You can find the SQL code to create these tables in tables.sql in the download archive. Execute it in the SQL tab of phpMyAdmin to have a working copy of this database. Remember to also fill in your MySQL login details in config.php.

The Models

The models in our application will handle the communication with the database. We have two types of resources in our application – products and categories. The models will expose an easy to use method – find() which will query the database behind the scenes and return an array with objects.

Before starting work on the models, we will need to establish a database connection. I am using the PHP PDO class, which means that it would be easy to use a different database than MySQL, if you need to.


	This file creates a new MySQL connection using the PDO class.
	The login details are taken from includes/config.php.

try {
	$db = new PDO(

    $db->query("SET NAMES 'utf8'");
catch(PDOException $e) {
	die("A database error was encountered");

This will put the $db connection object in the global scope, which we will use in our models. You can see them below.


class Category{

		The find static method selects categories
		from the database and returns them as
		an array of Category objects.

	public static function find($arr = array()){
		global $db;

			$st = $db->prepare("SELECT * FROM jqm_categories");
		else if($arr['id']){
			$st = $db->prepare("SELECT * FROM jqm_categories WHERE id=:id");
			throw new Exception("Unsupported property!");

                // This will execute the query, binding the $arr values as query parameters

		// Returns an array of Category objects:
		return $st->fetchAll(PDO::FETCH_CLASS, "Category");

Both models are simple class definitions with a single static method – find(). In the fragment above, this method takes an optional array as a parameter and executes different queries as prepared statements.

In the return declaration, we are using the fetchAll method passing it the PDO::FETCH_CLASS constant. What this does, is to loop though all the result rows, and create a new object of the Category class. The columns of each row will be added as public properties to the object.

This is also the case with the Product model:


class Product{

	// The find static method returns an array
	// with Product objects from the database.

	public static function find($arr){
		global $db;

			$st = $db->prepare("SELECT * FROM jqm_products WHERE id=:id");
		else if($arr['category']){
			$st = $db->prepare("SELECT * FROM jqm_products WHERE category = :category");
			throw new Exception("Unsupported property!");


		return $st->fetchAll(PDO::FETCH_CLASS, "Product");

The return values of both find methods are arrays with instances of the class. We could possibly return an array of generic objects (or an array of arrays) in the find method, but creating specific instances will allow us to automatically style each object using the appropriate template in the views folder (the ones that start with an underscore). We will talk again about this in the next part of the tutorial.

There, now that we have our two models, lets move on with the controllers.

Computer Store with PHP, MySQL and jQuery MobileComputer Store with PHP, MySQL and jQuery Mobile

The controllers

The controllers use the find() methods of the models to fetch data, and render the appropriate views. We have two controllers in our application – one for the home page, and another one for the category pages.


/* This controller renders the home page */

class HomeController{
	public function handleRequest(){

		// Select all the categories:
		$content = Category::find();

			'title'		=> 'Welcome to our computer store',
			'content'	=> $content

Each controller defines a handleRequest() method. This method is called when a specific URL is visited. We will return to this in a second, when we discuss index.php.

In the case with the HomeController, handleRequest() just selects all the categories using the model’s find() method, and renders the home view (includes/views/home.php) using our render helper function (includes/helpers.php), passing a title and the selected categories. Things are a bit more complex in CategoryController:


/* This controller renders the category pages */

class CategoryController{
	public function handleRequest(){
		$cat = Category::find(array('id'=>$_GET['category']));

			throw new Exception("There is no such category!");

		// Fetch all the categories:
		$categories = Category::find();

		// Fetch all the products in this category:
		$products = Product::find(array('category'=>$_GET['category']));

		// $categories and $products are both arrays with objects

			'title'			=> 'Browsing '.$cat[0]->name,
			'categories'	=> $categories,
			'products'		=> $products

The first thing this controller does, is to select the category by id (it is passed as part of the URL). If everything goes to plan, it fetches a list of categories, and a list of products associated with the current one. Finally, the category view is rendered.

Now lets see how all of these work together, by inspecting index.php:


	This is the index file of our simple website.
	It routes requests to the appropriate controllers

require_once "includes/main.php";

try {

		$c = new CategoryController();
	else if(empty($_GET)){
		$c = new HomeController();
	else throw new Exception('Wrong page!');

catch(Exception $e) {
	// Display the error page using the "render()" helper function:

This is the first file that is called on a new request. Depending on the $_GET parameters, it creates a new controller object and executes its handleRequest() method. If something goes wrong anywhere in the application, an exception will be generated which will find its way to the catch clause, and then in the error template.

One more thing that is worth noting, is the very first line of this file, where we require main.php. You can see it below:


	This is the main include file.
	It is only used in index.php and keeps it much cleaner.

require_once "includes/config.php";
require_once "includes/connect.php";
require_once "includes/helpers.php";
require_once "includes/models/product.model.php";
require_once "includes/models/category.model.php";
require_once "includes/controllers/home.controller.php";
require_once "includes/controllers/category.controller.php";

// This will allow the browser to cache the pages of the store.

header('Cache-Control: max-age=3600, public');
header('Pragma: cache');
header("Last-Modified: ".gmdate("D, d M Y H:i:s",time())." GMT");
header("Expires: ".gmdate("D, d M Y H:i:s",time()+3600)." GMT");

This file holds the require_once declarations for all the models, controllers and helper files. It also defines a few headers to enable caching in the browser (PHP disables caching by default), which speeds up the performance of the jQuery mobile framework.

Continue to Part 2

With this the first part of the tutorial is complete! Continue to part 2, where we will be writing the views and incorporate jQuery Mobile. Feel free to share your thoughts and suggestions in the comment section below.