Closures – closely guarded secrets


JavaScript Secrets

Inside a closure

As briefly described in the previous post, a closure is the scope that is created when a function is able to access variables that are defined outside the function. Normally a function only has access to variables defined within it’s own body. The following code sample illustrates this:

var externalVar = "port";
var sail;

function harbour (){
   var internalVar = "dock";

   function quay () {
      if(externalVar){
      alert("I can see the port");
      }
      if(internalVar){
      alert("I can see the dock");
      }

   }
   sail = quay;

  }
   harbour();

   sail();

run the code

Animation with Closures

In the example below, one anonymous function is used to access three variables (tick, elem and timer) in order to animate the div element. The function maintains reference to these variables throughout the setInterval loop. As a result the variables should not be in global scope where other objects could interfere and cause a conflict.

<!doctype html>
   <head>
      <title>Animation with Closures</title>
	  <style>
	   #ship{
	      width: 120px;
		  height: 120px;
		  background-color: red;
		  position: relative;
	   }
	  </style>
   </head>
   <body>
   <div id="ship">Sailing</div>
   <script type="text/javascript">
      function animateShip(elemId){
         var elem = document.getElementById(elemId);
         var tick = 0;

         var timer = setInterval(function(){
           if(tick < 120) {
              elem.style.left = elem.style.top = tick + "px";
			  console.log(tick);
              tick++;
            }
           else {
               clearInterval(timer);
               if(tick == 120) {
               alert("Tick was accessed via a closure");
               }
               if(elem && timer) {
               alert("Element elem and timer also accessed via a closure");
              }

           }
         }, 10);
     }
   animateShip("ship");
   </script>

   </body>
</html>

run the code
It should be noted that the previous example would still work even the variables were defined in global scope, outside the animateShip() function. This is shown in the next example:

<!doctype html>
   <head>
      <title>Animation with Closures</title>
	  <style>
	  #ship {
            width: 150px;
            height: 70px;
            background-color: #fdd;
            color: #fff;
            text-align: center;
            font-size: 18px;
            position: relative;
        }
	  </style>
   </head>
   <body>
   <div id="ship">Sailing</div>
   <script type="text/javascript">
      var tick = 0;
      var elem;
      var timer;
      function animateShip(elemId){
         elem = document.getElementById(elemId);

         timer = setInterval(function(){
           if(tick < 120) {
              elem.style.left = elem.style.top = tick + "px";
			  console.log(tick);
              tick++;
            }
           else {
               clearInterval(timer);
               if(tick == 120) {
               alert("Tick was accessed via a closure");
               }
               if(elem && timer) {
               alert("Element elem and timer also accessed via a closure");
              }

           }
         }, 10);
     }
   animateShip("ship");
   </script>

   </body>
</html>

run the code
However when you try to animate two or more elements with this setup, as shown below, a serious problem arises. Only the last element gets animated, because it over writes all previous instances of the variables.

<!doctype html>
   <head>
      <title>Animation with Closures</title>
      <style>
         #ship {
         width: 150px;
         height: 70px;
         background-color: #fdd;
         color: #fff;
         text-align: center;
         font-size: 18px;
         position: relative;
        }
        #ship2 {
        width: 150px;
        height: 70px;
        background-color: orange;
        color: #fff;
        text-align: center;
        font-size: 18px;
        position: relative;
        left: 150px;
        }
   </style>
   </head>
   <body>
   <div id="ship">Sailing ship1</div>
   <div id="ship2">Sailing ship2</div>
   <script type="text/javascript">
      var tick = 0;
      var elem;
      var timer;
      function animateShip(elemId){
         elem = document.getElementById(elemId);

         timer = setInterval(function(){
           if(tick < 120) {
              elem.style.left = elem.style.top = tick + "px";
			  console.log(tick);
              tick++;
            }
           else {
               clearInterval(timer);

           }
         }, 10);
     }
   animateShip("ship");
   animateShip("ship2");
   </script>

   </body>
</html>

run the code
When we restore the variables to the initial scope within the animateShip() function, then both divs are animated simultaneously. This insightful example shows the real power of closures.It’s sort of an Aha! moment in the JavaScript closure ecosystem. Imagine creating multiple animations in a complex application, for example an accordion with several items; All the items can be animated by a single jQuery object. You can now understand why the concept of closures is so important in object oriented JavaScript. Libraries like jQuery, Backbone, Knockout and Ember could not exist without closures.

<!doctype html>
   <head>
      <title>Animation with Closures</title>
      <style>
	   #ship {
         width: 150px;
         height: 70px;
         background-color: #fdd;
         color: #fff;
         text-align: center;
         font-size: 18px;
         position: relative;
        }
        #ship2 {
        width: 150px;
        height: 70px;
        background-color: orange;
        color: #fff;
        text-align: center;
        font-size: 18px;
        position: relative;
        left: 150px;
        }
   </style>
   </head>
   <body>
   <div id="ship">Sailing</div>
   <script type="text/javascript">

      function animateShip(elemId){
         var tick = 0;
         var elem = document.getElementById(elemId);

         var timer = setInterval(function(){
           if(tick < 120) {
              elem.style.left = elem.style.top = tick + "px";
			  console.log(tick);
              tick++;
            }
           else {
               clearInterval(timer);

           }
         }, 10);
     }
   animateShip("ship");
   animateShip("ship2");
   </script>

   </body>
</html>

run the code

Binding a function’s context

In the code sample below, shows how a functions context can be forced to have a certain value. The bind() function has a closure within which an anonymous function is being used to change the context of another method. The code is rather convoluted and needs to be untangled. This technique is being used to resolve the problem caused the browsers default behaviour of assigning the context of a click event to the button element that was clicked. Here, the context has been switched to the myButton object.

<html>
   <head><title>Binding context</title></head>
   <body>
   <button id="btn">Click here</button>
<script type="text/javascript">
   function bind(context, name){
     return function(){
       return context[name].apply(context, arguments);
     };
   }

var myButton = {
    clicked: false,
    click:  function (){
      this.clicked = true;
      if(myButton.clicked){
      alert("You clicked myButton!" + "in this context " + this);
      }

      }
    };

var el = document.getElementById("btn");
el.addEventListener("click", bind(myButton, "click"), false);
</script>
</html>

run the code

Binding function context in JavaScript

Posted in Code, Tutorials, Web design & development | Leave a comment

Elements of Arguments in JavaScript Functions


Variable length argument lists

JavaScript functions can accept variable length argument lists. By taking advantage of this powerful feature, developers have greater control over how functions are defined and invoked. This post will discuss:

  • How to insert variable number of arguments into a function
  • How JavaScript can implement function overloading
  • The length property of argument lists

First let’s look at how the apply() method can be used in this situation. Suppose you need to find out the largest or smallest number in an Array. JavaScript has no built in function that can perform this simple task. Even though the Math object has min() and max() methods neither one accepts an Array as the argument list. That’s amazing but true. Fortunately there is a work around for this problem shown in the code below:

function minimum(array){
   return Math.min.apply(Math, array);
}

function maximum (array) {
   return Math.max.apply(Math, array);
}

myArray = [3, 6, 7, 12, 2, 8];

if(minimum(myArray) == 2){
   alert("Found the smallest number");
}

if(maximum(myArray) == 12){
   alert("Found the largest number");
}

run the code

Function overloading

The key to variable arguments list is the arguments parameter, which all JavaScript functions possess.
It provides access to all passed arguments in a function even if not all have been defined when the function was created.
In other object oriented languages like Java, method overloading is implemented by defining separate methods for each possible argument list. However in JavaScript, there is only one function definition which can then be invoked with various argument lists.
The code sample below illustrates how to merge the properties of several objects into one root object. The initial function definition has one argument, this corresponds to the {name: "Titanic"} object at initialization. After looping through the parameters list, the object becomes {name: "Titanic", port: "Pier 24", company: "Disney"}

  function merge(root){
	for (var i = 1; i < arguments.length; i++){
		for (var key in arguments[i]) {
			root[key] = arguments[i][key];
		}
	}
	return root;
}

var merged = merge (
	{name: "Titanic"},
	{port: "Pearl Harbour"},
	{company: "Disney"}

);

if(merged.name =="Titanic"){alert("The name is still the same")};
if(merged.port == "Pearl Harbour") {alert("The port has been moved over")};
if(merged.company == "Disney") {alert("The company has also been moved over")};

run the code

You can find examples in JavaScript libraries such as jQuery, the animate() function below accepts one object argument in the first case and two in the second:

// animate() takes one object, an integer and a function as arguments
 $('#port').animate({
   opacity: 0.25,
   left: '+=50',
   height: 'toggle'
   }, 5000, function() {
   // Animation complete.
   });

// here animate() takes two objects and a method as arguments
 $('#port').animate({
   width: 'toggle',
   height: 'toggle'
   }, {
   duration: 5000,
   specialEasing: {
     width: 'linear',
     height: 'easeOutBounce'
   },
   complete: function() {
     $(this).after('<div>The Easing Animation is complete.</div>');
   }
});

Functions also have a length property, similar to the arguments parameter’s length property. The function length property has a value equal to the number of items in the arguments list when the function is invoked. Whereas the arguments length property is the number of items when the function is defined. These two values may be equal except when you have function overloading.

The code sample below illustrates a simple function overloading example. Here we three methods with the same name – find bound to a base object. The three methods accept different number of arguments. The first accepts no argument, while the second accepts one argument, and the third accepts two arguments.

One important fact is that these methods are referenced from within closures. A closure is created when a function is able to access variables that are defined outside its normal scope. This topic will be discussed further in the next post.

Even though function overloading is a powerful technique, this example has some fundamental weaknesses. It only works for functions with different arguments length, and does not differentiate between argument type or name. Since the functions all have the same name, there’s a function call overhead that could affect performance.

run the code

   	function addMethod(object, name, fn){
	var old = object[name];

	object[name] = function(){
		if(fn.length == arguments.length){
			return fn.apply(this, arguments)}
			else if (typeof old == 'function')
			return old.apply(this, arguments);
		};
}

var ninjas = {
	values: ["Abraham Lincoln", "George Washington", "Charles Drew"]
};

addMethod(ninjas, "find", function(){
	return this.values;
});

addMethod(ninjas, "find", function(name){
	var ret =[];
	for(var i = 0; i < this.values.length; i++)
	if(this.values[i].indexOf(name) == 0)
	ret.push(this.values[i]);
	return ret;
});

addMethod(ninjas, "find" , function(first, last){
	var ret =[];
	for  (var  i = 0; i <this.values.length; i++)
		if (this.values[i] == (first + " " + last))
		ret.push(this.values[i])
		return ret;
});

if(ninjas.find().length == 3){ alert("Found all Ninjas")};

if(ninjas.find("George").length == 1){alert("Found Ninja by first name")};

if(ninjas.find("Abraham", "Lincoln").length == 1){alert("Found Ninja by first  and last name")};
Posted in Code, Tutorials, Web design & development | Leave a comment

Even More JavaScript Secrets


This post will focus on exploiting the similarities between functions and objects. Just as you can attach properties to objects, functions can also have properties attached.

   var myObj = {};
   var myFn = function() {};
   myObj.prop = "ship (cruise)";
   myFn.prop = "frigate (mission)";

Event callback management is one of several uses for this aspect of functions. In the following code sample by using the function’d id property fn.id we can add the frigate function to the shipyard object’s dock.

var shipyard = {
  pierId: 1,

  dock: {},

  add: function(fn) {
         if(!fn.id) {
            fn.id = shipyard.pierId++;
            return !!(shipyard.dock[fn.id] = fn); // the !! returns the Boolean value of any JavaScript expression
         }
    }

}

function frigate() {};
if(shipyard.add(frigate)){
  alert("frigate was added to shipyard");

 if(!shipyard.add(frigate)){
  alert("frigate was added once");
}
}

Memoization

This technique is used to store processor intensive calculated values. It makes your code much more efficient, especially when the same calculation is repeated several times. One common application is to store DOM elements by tag name.

function isPrimeNbr(val) {
   if(!isPrimeNbr.answers) isPrimeNbr = {};
if(isPrimeNbr.asnwers[val] != null) {
     return isPrimeNbr.answers[val];
     }
   var prime = val != 1;
for( var i = 2; i < val; i++) {
    if (val % i == 0) {
    prime = false;
    break
}
}
return isPrimeNbr.answers[val] = prime;
}
if(isPrimeNbr(57){
  alert("57 is a prime number");
}
if(isPrimeNbr.answers[57]){
 alert("The answer was safely cached");
}

The code below shows an example of memoizing DOM elements by tag name. The downside of this is memory that gets tied down, the improved performance compensates for this. Also some may argue that caching should not be performed by functions meant for business logic in order to keep separation of tasks intact.

function getElements(name){
   if (!getElements.cache) getElements.cache = {}
return getElements.cache[name] = getElements.cache[name] || document.getElementByTagName(name);
}

Array methods

Javascript Arrays are also Objects and this commonality can be used to create some interesting techniques. In situations where an Object contains a collection of data and also needs to store certain metadata concerning the data collection. Simply creating a new Object each time we need different metadata properties would be inefficient and time consuming. The example below shows how you can create an Object and then apply existing Array methods to it.

<body>
<input id="ying" />
<input id="yang" />
<script type="text/javascript">
var elems = {
    length:0,

    add: function(elem) {
         Array.prototype.push.call(this, elem);
    },

    gather: function(id) {
    this.add(document.getElementById(id));
    }
};

elems.gather("ying");
if(elems.length == 1 && elems[0].nodeType){
  alert("Verify that there's an element in our store");
}

elems.gather("yang");
if(elems.length == 2 && elems[0].nodeType){
  alert("Verified that Ying has got a Yang");
}
</script>

</body>

The code sample above shows a conventional object elems that has been set up to behave like an array. First it has a length property. It also has a method add() that inserts new elements, this method is implemented using Array.prototype.push. Normally, the context of Array.prototype.push is the array itself, however in this case by using the call() method the context is defined as the elems object. By so doing the length property is also incremented as in a regular array. The gather() method is more of a helper function that retrieves the DOM elements by id and invokes the add() method to insert the elements into storage.

Posted in Code, Tutorials, Web design & development | Leave a comment

More JavaScript Secrets


JavaScript Secrets

Anonymous functions

Why anonymous functions are so very important: they can be used for various purposes such as event handlers, callbacks, methods for objects etc

// using anonymous function as event handler
button.onclick =
    function(){alert("hello portfour");};
// using anonymous functions as a method of an object
var port = {
    dock: function() {
          alert("Portfour is good for docking");
    }
};

port.dock();
// as a callback in an event handler

setTimeout(
    function(){alert("Ship leaves port in 500 milliseconds"); },
    500);

In the second example, even though the anonymous function is assigned a property named dock, the function does not acquire this name. To confirm this test for the function’s name property and you will find that it is still an empty string, not Null or undefined, but a string with length zero.

Recursion

The simplest definition is a self referencing function that converges toward termination. If it is self referencing but does not converge then you have an infinite loop!

// simple recusion, where a function returns a reference to itself
  function isPalindrome(text){
      if (text.length <= 1) return true;
      if(text.charAt(0) != text.charAt(text.length - 1)) return false;
   return isPalindrome(text.substr(1, text.length - 2));
}
// a simple function that counts backwards using recursion
function countDown(nbr){
  console.log("count is " +nbr);
  if (nbr > 1 ) {
   return countDown(nbr - 1); }
return false;
}

var port = {
   countDown: function(nbr){
              console.log("port count is " + nbr);
              if( nbr > 1 ) {
              this.countDown(nbr - 1)};
              return false;
};

}
port.countDown(7); // counts down from 7 to 1

run the code
The first example above shows recursion using a named function, that calls itself by name. This is a simple illustration of the concept, how about anonymous functions? How do you call something that has no name? Remember the example of anonymous functions used as methods? Well, since the method can be invoked using the property name, the anonymous function is also invoked this way. This allows you to call the method from another object property of the same name. The reference to the anonymous function still works even after the initial object has been reset and its properties no longer exist

var ship = {
    signal: function(n) {
            return n >1 ? this.signal(n-1) + "-beep" : "beep";
    }
};

var frigate = { signal: ship.signal };

ship = {};

if(frigate.signal(3) == "beep-beep-beep") alert("The method correctly calls itself");
alert(typeof ship.signal); // returns undefined

run the code

Inline named functions

What do you do when the methods have a different name from the property being referenced? The previous example only applies in a specific case where signal is the name used for both method and property. A more flexible approach would involve giving the anonymous function a name, this is called an inline function.

var port = {
    ship: function signal(n) {
       return n > 1 ? signal (n - 1) + "-beep" : "beep";
   }
};
if(port.ship(3) == "beep-beep-beep"){
   alert("Inline function recursion worked");
};

var frigate = { ship: port.ship };

port = {};
if(frigate.ship(3) == "beep-beep-beep"{
   alert("The inline function correctly calls itself");
};

Next post will look into functions as object and self-memoizing functions

Posted in Code, Tutorials, Web design & development | Leave a comment

Javascript Secrets: Scoping Functions and Function Scope


JavaScript Secrets

Intro

Over the last few years, JavaScript has become an increasingly important Web Development language. Several Libraries and frameworks have been created by leveraging the functional nature of the language to simulate Object Oriented properties intrinsic to more robust languages like Java and C++. (For those who still think Java and JavaScript are similar here’s a great analogy: JavaScript is to Java like hamburger is to ham)

More about Functions

In order to be very good in JavaScript, it is very important to have a good grasp of Functions. Unlike most other languages JavaScript Functions are “first class objects”. This means that Functions can:

  • have methods and properties
  • be assigned to variables, array members or properties of other objects
  • be passed as arguments in other functions
  • be returned as values from other functions

Code samples of Functions

// assigning value to a function
var value1 = function() { return true};

//function as argument in a method call
document.addEventListener("click", function(){
    //do something cool here
    }, false);

// returning a function
function myFun () {
   var nbr = 0;
   return function (){
      var nbr2 = nbr + 2;
   };
}
  • Functions are first class objects they can be created vis literals, assigned to variables, passed as parameters, returned as function results, possess properties and methods
  • Passing a function as a parameter usually involves anonymous functions. Yes, functions can either have a declared name or no name at all
  • Each function invocation is assigned two implicit parameters: arguments and this. The arguments parameter is an “array like” collection of the function’s arguments, it is similar to an array since it has a length property and can be iterated with a for loop, however the data type is object not array.
  • Functions can be invoked via the apply() and call() methods, this allows us to change the context i.e value of this parameter
  • variables in a function are in scope from declaration point to end of the function (n.b declaring a variable with var makes it declared but not defined within that function before it’s defined, so it will be type undefined)
  • Inner named functions are in scope throughout the function enclosing them, even before being defined( this is called hoisting)
//function's name is myName
function myName (arg1, arg2){
// do something here
return value1

}
// function is anonymous has no name
function (arg1, arg2){
// do something here
return value2
}
<script>
	function assert (value, desc) {
		var li = document.createElement("li");
		li.className = value ? "pass" : "fail";
		li.appendChild(document.createTextNode(desc));
		document.getElementById("results").appendChild(li);
		}

		window.onload = function(){
			assert(true, "The test suite is running yay!");
			assert(false, "Fail");
		};
</script>
// css for the assert test function
<style>
	#results li.pass { color: green;}
	#results li.fail { color: red;}
</style>
// HTML for the assert test function
<body>
        <ul id="results"></ul>
</body>
Posted in Code, Tutorials, Web design & development | Leave a comment

jQuery TO



The upcoming two-day conference (1-2 March 2013) in Toronto ( @ The Delta Chelsea 33 Gerrard St. W. Toronto, M5G 1Z4), promises to be very educational and essential for all Front-End Web Developers in the GTA.Featuring over 30 speakers including:

  • Paul Irish – Google Chrome Web development leader and modernizr co-creator read more
  • Addy Osmani – Google Chrome Developer Programs Engineer, read more
  • Scott Gonzalez – jQuery UI Project lead, read more
  • Scott Methvin – President jQuery Foundation.

Even though “Mr jQuery” himself – John Resig, will not be there it’s still worth the $250 registration fee.
Get more details and register @ jQueryTO

Posted in Media, Web design & development | 1 Comment

HTML5 vs Flash – a web based TKO?


Agent 008 Ball

HTML5 vs Flash – a turff war on the WWW

Recently, I stumbled upon some amazing HTML5 demos and apps. One example, Agent 008 Ball (image above), could easily pass for a Flash based game. After playing this game and reviewing a few other apps, I was motivated to write another blog post about the pros and cons of Flash vis-a-vis HTML5. Over a year ago, I published a blog post supporting Flash against HTML5. Back then it seemed to make sense because there were so many features in Flash that HTML5 could not match (a powerful OOP language, a mature IDE, multimedia integration etc.). Now with the countless developments in HTML5, it seems Flash is facing very serious competition. Thanks partly to people like Google’s Paul Irish and others at HTML5rocks.com.

Making Javascript more object oriented

Google’s Closure library allows you to extend Javascript Event Handling feature. You can define custom events and listeners.Thus improving Javascript’s built-in Observer (publisher/subscriber) pattern (e.g. onMouseover, onClick, onLoad etc.). Imagine what can be done with that… in Game Development you can trigger other functions when the player gets a certain score. Or if you have collision detection, fire some other actions whenever certain objects collide. You can also create an event for when the game ends.From an OOP perspective, it is much easier to decouple the Objects in your application. In other words you can separate the “cause from the effect”. An event created in one class can have a listener in a different class. Changing the event trigger (e.g. from a mouseover to an onclick event) requires a single event definition code edit which is then dispatched to all subscribers or listeners. Javascript’s native events would require code changes everywhere the event has been used. Therefore, with the Close library your code is much more flexible, adaptable and reusable.The example below is a call to goog.events.listen() and shows how a click event on contentElement triggers the openEditor() function.

eightball.PocketDropEvent = function(ballNumber, opt_target) {
  goog.events.Event.call(this, eightball.PocketDropEvent.TYPE, opt_target);

  /**
@type {number}
*/
  this.ballNumber = ballNumber;

};
 this._dispatchGameEvent(eightball.Game.EventType.END);
 goog.events.listen(this.contentElement, goog.events.EventType.CLICK,this.openEditor, false, this);

The Closure Library also implements true OOP inheritance mechanism. Allowing you to make your applications much more modular and reusable. Normally Javascript would require you to define a “Prototype chain” for each pair of Objects in a “Parent – Child” relationship. Using the Closure library makes this process less painless, more reliable and consistent across different browsers.

goog.ui.MenuButton = function(content, opt_menu, opt_renderer, opt_domHelper) {
  goog.ui.Button.call(this, content, opt_renderer ||
      goog.ui.MenuButtonRenderer.getInstance(), opt_domHelper);

  // Menu buttons support the OPENED state.
  this.setSupportedState(goog.ui.Component.State.OPENED, true);

  if (opt_menu) {
    this.setMenu(opt_menu);
  }
  this.timer_ = new goog.Timer(500);  // 0.5 sec
};
goog.inherits(goog.ui.MenuButton, goog.ui.Button);

Extended and Improved CSS3

With SASS, you can now define variables in your CSS code. Commonly used values like font colors or margins can be replaced with variables. Instead of changing multiple instances of these values, you simple change the variable once, thus reducing code errors and allowing you to create more consistent page layouts.

/* style.scss */

#navbar {
  width: 80%;
  height: 23px;

  ul { list-style-type: none; }
  li {
    float: left;
    a { font-weight: bold; }
  }
}

/* style.scss */

$main-color: #ce4dd6;
$style: solid;

#navbar {
  border-bottom: {
    color: $main-color;
    style: $style;
  }
}

a {
  color: $main-color;
  &:hover { border-bottom: $style 1px; }
}

HTML5 Resources

A list of useful HTML5, Javascript and CSS3 links
Flash to HTML5 using CreateJS

Google Closure library – time tested library, brings true OOP to Javascript

jQuery Boilerplate -Jump-start jQuery plugins development

SASS CSS3 extension -adds nested rules, variables, mixins, selector inheritance to CSS3

LESS – CSS extension -extends CSS with dynamic behavior such as variables, mixins, operations and functions (similar to SASS)

Compass – an open-source CSS Authoring Framework (uses SASS).

Jangaroo project – AS3 to Javascript compiler

Aptana Studio 3 – develop and test your entire web application using a single environment.

CodeKit – Mac toolkit for HTML5 developers

Agent 008 Ball – A cool pool game using HTML5 and Google Closure library

List of cool HTML5 games

Javascript and HTML5 fireworks animation

WebGL examples

Posted in Design, Web design & development | 1 Comment

Shield and Ribbon Tutorial


Proudly Naija
Introduction

This tutorial will show you how to create the shield and ribbon graphic, using Adobe Illustrator and Photoshop. an intermediate skill level is required as well as some artistic skills. However you don’t have to be a Picasso to create the design. So go ahead get your creative muse in the zone and have fun while learning a few new tricks!

Step 1

Step 1 - Shield and Ribbon Tutorial
In Adobe Illustrator draw the outline of the shield using line weight of 2pt, with black stroke and a white fill.

Step 2

Step 2 Shield and Ribbon Tutorial

Draw the rivers outline using line weight 1pt, with black stroke.

Step 3

Step 3 Shield and Ribbon Tutorial

Draw the ribbon outline as shown, using 1pt line weight and black stroke.

Step 4

Step 4 Shield and Ribbon Tutorial



Import the vector images from Illustrator into Photoshop.

Step 5

Step 5 Shield and Ribbon Tutorial

Create a new gradient and save it, this will be used to fill both the shield and ribbon.

Step 6

Step 6 Shield and Ribbon Tutorial

Duplicate the shield layer, then use the radial type gradient to fill the shield.

Step 7

Step 7 Shield and Ribbon Tutorial

Apply the outer glow layer style to the other shield outline layer.

Step 8

Step 8 Shield and Ribbon Tutorial

Fill the ribbon with the gradient, check the reverse box to invert the gradient.

Step 9

Step 9 Shield and Ribbon Tutorial

Select the middle section of the ribbon, and copy into a separate layer. Apply the layer style to this new layer.

Step 10

Step 10 Shield and Ribbon Tutorial

Select the “Rivers” layer and apply layer style.

Step 11

Step 11 Shield and Ribbon Tutorial

Create the ribbon text in Illustrator using text on a path. Switch to white text before importing to Photoshop

Step 12

Proudly Naija Logo

This is what your final image should look like. Feel free to make any layer style adjustments or Filter effects to suit your taste!
Lastly show off to your friends!

Posted in Design, Tutorials, Web design & development | Leave a comment

Adobe Design & Web Premium CS6




This suite of applications includes:

  1. Photoshop
  2. Illustrator
  3. Dreamweaver
  4. Fireworks
  5. Acrobat
  6. InDesign
  7. Flash Professional
  8. Bridge
  9. Media Encoder

Photoshop

The industry standard digital image editing software keeps getting better with each new version. The content aware algorithms allow you to edit images quickly for example in the demo the product manager was able to move the female figure to a different location while Photoshop automatically filled up the previous position with a seamless background. Looks just as if the woman was never there. The new layer search feature allows you to search for a layer by name or by type (text, vector etc.) In vector layers you can also change line type, fill or stroke color from the properties menu. There’s a new command that allows you to duplicate, change blend mode or layer style of multiple selected layers simultaneously, this will save a lot of production time.
Photoshop CS6 now has an amazing 3D mode with tools that can change the camera angle, zooming in/out, adjust the lighting. applying the 3D mode to a type layer for example allows you to extrude the type, change font size, font type, color and even alter the geometry completely, all from within the 3D object and in real time!
The crop tool has also been overhauled with several new menu options such as selection overlays and preset crop sizes, shapes and aspect ratios. Also if you change your mind about cropping the original image is still saved. Finally the blur filter has a new photographic addition: Blur Gallery – iris blur, field blur, tilt shift. These allow you create camera lens effects like depth of field and even some effects that a camera cannot do, such as multiple focal points!

Illustrator

The new pattern editing mode allows you to create and manipulate tiled images seamlessly and easily. So you can change the color or scale the pattern image while the tile and swatches panel get instantly updated. The new image trace feature replaces the former Live trace, this makes converting bitmap graphics into vector objects, so much easier. It also has presets that allow you to control how much detail is transformed into the vector object. You can also create your own custom presets. The quality of the vector object is so good that you may find it difficult to see difference between the bitmap image and the vectorization. Another new feature in CS6 is the gradient on stroke option. It allows you to apply a gradient to a stroke and add cool effects like gradient along stroke, so the gradient is not linear or radial but follows the curve of the stroke.

Dreamweaver

Now you can easily create adaptive and responsive web layouts in Dreamweaver. This makes targeting various device screen sizes more manageable. Fluid grid layouts allow you to decide which blocks of content are displayed on different screen sizes and also change their relative positions. Adobe’s recent acquisition of PhoneGap is already yielding positive results with the integration of the web service into Dreamweaver CS6. Now you can build native apps for iOS and Android right inside Dreamweaver! jQuery support has also been improved. CSS3 transitions can also be edited and customized to suite your artistic muse.

Flash Professional

You can now convert your Flash projects directly into HTML5 using the amazing new extension in Flash CS6. It uses the createJS Javascript framework and the code generated can be reviewed and edited. You can now create apps for users on Android and iOS devices the export settings have the option to embed the Adobe Air runtimes with your app. You can also include device-specific extensions to target unique platform features such as vibrate, gyroscope and notifications.The new Flash includes Sprite sheets generation, allowing you combine several animation loops into one single object thereby improving performance.

Posted in Design, Media, Web design & development | Leave a comment

Custom sub-menu in WordPress


In this tutorial you will earn how to create a customized sub menu using WordPress 3.3.1. Using categories instead of pages to organize your posts and create a hierarchy of menu items. This approach also uses custom permalinks and you need to have a child theme setup. It is assumed that you have intermediate programming skills in PHP and HTML.
By default WordPress creates drop down sub–menus, however sometime your navigation and site design my require a horizontal sub–menu that is located beneath your main menu. Continue reading

Posted in Tutorials, Web design & development | Leave a comment