Author Archives: Prasad

About Prasad

UI I am a UI Designer with a passion for designing clean and simple user interfaces. I do smart UI design, My career path is simple "Challenges are always interesting as they keep me moving, but learning from them and implementing is my motto" Understanding good UI design can help you create the more user friendly portals. UI I am a User Interface Developer with experience in coding XHTML, HTML, HTML5, CSS, CSS3, Bootstrap UI Framework, SEO, jQuery, JavaScript, PHP and MySQL. I focus on writing clean and efficient code.

Understanding the JavaScript Closures

Understanding the JavaScript Closures

What is a closure?

A closure is an inner function that has access to the outer/enclosing function’s variables scope chain.
Closure has three scope chains i.e.,
1) It has access to its own scope (variables defined between its curly brackets)
2) It has access to the outer function’s variables, and
3) It has access to the global variables.

The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters.

Note that the inner function cannot call the outer function’s arguments object; however, even though it can call the outer function’s param’s directly.

In simpler way to say what is closure? If you create a function inside / within another function its called as closure / private function.

Understanding the JavaScript Closures

An Example of Closures in JavaScript:

 

Will come up with next article on this with more details of closures and some more example’s & Closures’ Rules and Side Effects, usage and so on….
 
You can find more even in W3C about closures:
URL : http://www.w3schools.com/js/js_function_closures.asp

Remove input field and textarea inner shadow in iOS

Remove input field and textarea inner shadow in iOS

How to Remove input field text and text-area inner shadow in iOS:

Apple/iOS products are great, but the mobile iOS is adding extra styles to form elements.

This can be quite annoying if you want to get your design to look exactly the same in most browsers/hybrid apps.

Here is how you can remove inner shadow from text input fields and textareas by simply applying the CSS to your input text field and textarea.


/* Remove inner shadow from input type="text" and textarea on mobile iOS */

textarea, input[type="text"] {
-webkit-appearance: none;
}

What is CSS Box Shadow?

CSS Box Shadow. Used in casting shadows off block-level elements (like divs). … The vertical offset of the shadow, a negative one means the box-shadow will be above the box, a positive one means the shadow will be below the box.


inner shadow in iOS

Eat healthfully Feel great

Eat healthfully Feel great

Rich sauces, fried foods and sugary desserts taste great and can be hard to resist. However, if you eat too much of these kinds of foods that are high in fat and calories, you may feel sluggish and guilty. The extra pounds can build up while your energy level goes down. Making a few healthful changes to the way you eat can make a big difference in how you feel.

Create a food diary

Take an honest look at your eating habits. Each day, write down everything you eat and drink. Be sure to include all those quick nibbles. At the end of the week, your diary might surprise you.

Tips for healthful eating

Is it really hunger? Don’t eat out of habit, boredom or just because food is near.

Try following these tips:

  • Control portion size Take the focus off how much. Put it on variety. Small amounts of several foods can keep your meals fun. Use a smaller plate to limit how much you take.
  • Eat slowly Savor flavors and smells. Notice the visual appeal of your meal. It can take 20 minutes for your stomach to feel full. The faster you eat, the more likely  you are to overeat.
  • Skip seconds Make it a rule not to take second helpings. Remember that tomorrow will bring good things to eat, too.
  • Limit high-fat, high-calorie desserts. Try to eat dessert half as often as you do now. Or, if you need something sweet, try fruit as a dessert instead.
  • Don’t skip meals: When you come to the table starved, you’re more likely to overeat. Plus, you’re more likely to eat the wrong foods.
  • Never say never: Don’t try to always avoid your favorite foods. But, plan on when and how much you’ll have. Or, you might give in to sudden cravings.
  • Don’t sabotage yourself: There always seems to be a perfect excuse for having too much “just this once.” Maybe you’re celebrating a special occasion, such as a birthday or holiday. Don’t let these occasions stand between you and your health.

Adopt healthful habits

Think carefully before you eat:

  • Limit foods with full-fat cheese or cream sauces and mayo.
  • Choose meats and fish that are grilled or broiled rather than fried.
  • Eat steamed vegetables. Limit butter, margarine or cream sauces.
  • If you use salad dressing, use a low-fat one.
  • Avoid empty calories like those found in sugar-sweetened beverages and alcohol.
  • Drink an adequate amount of water each day.
  • When snacking, choose unsalted, whole-grain pretzels; air-popped popcorn; low-fat yogurt or fresh fruit.
  • Try not to eat anything close to bedtime.
  • Remember, “fat-free” doesn’t always mean“calorie-free.”
  • Limit take-out meals or fast food.

AngularJS the MVVM way better modular UI Development

AngularJS the MVVM way better modular UI Development

Lot of buzz about Plug and Play and design patterns in the UI development round the clock!
Plug and Play is possible with good architecture and adoption of good design pattern. Most popular are – MVC, MVP and MVVM. Most of us are familiar with MVC (Model-View-Controller), MVP (Model-View-Presentation) and the one picking up now is – MVVM.

MVVM (Model-View-ViewModel) is actually an architectural pattern used in software engineering that originated from Microsoft as a specialization of the Presentation Model design pattern introduced by Martin Fowler. For those who want to understand more on – MVC, MVP, can refer to http://www.codeproject.com/Articles/288928/Differences-between-MVC-and-MVP-for-Beginners and also MVVM included here – http://www.codeproject.com/Articles/66585/Comparison-of-Architecture-presentation-patterns-M.

The above details are all specific to the design pattern. So let’s now understand how we can adopt to this (MVVM) good pattern in UI development, especially, the Hybrid App development projects.

MVVM components include:
1. Model
2. View
3. View Model
Here, the controller of MVC is replaced by a ViewModel and the View Model is a JavaScript function which acts as a model for the view and is responsible for maintaining relationship between view and the model. If we update anything in view, it gets updated in model, change anything in model, it reflects in the view, and it’s called 2-way data binding. MVVM separates business logic from UI using the ViewModel. AngularJs helps in achieving this using plain JavaScript objects. $scope is the important object in AJS (AngularJS), which allows defining both the data and methods that will be available for the view.
Let’s look into the details of MVVM AJS:
Model:
Holds application/domain specific data along with actual information what our app needs to deal with. Eg: user name, age, DOB etc. in a form.
Services or Factories can be used to handle Model in AJS.
Services are view- control logic handlers as well. We can call it as a View-Model interface (or a VM Interface), where all the common business logic reside. This helps in easy plug and play of two dependent modules.
View:
View handles the events, behaviour and actual UI representation.
Eg: A visual representation of a Submit button, button click behaviour etc. The behaviour is actually handled by ViewModel. Eg: On click of a submit button, AJAX Post may be performed and data is posted to server etc (handled by ViewModel); and a pop-up message for success or
failure should be shown up (View).
Angular templates (using directives) act as the Views in AJS Hybrid apps.

ViewModel:
Holds the presentation logic and interacts with Model on state changes. Example is discussed in the View details above.

AJS Controllers serve this purpose in Hybrid apps. An AJS controller (the ViewModel) should –

• Include the state of the presentation – like which item is selected using radio button, if a switch is turned on/off etc.
• Utilize and process data from Model/Server – fetch DB, make a post / get AJAX request and pre-process data if required, before presenting.
• Be able to communicate with other Controllers via methods/interfaces.

This is all about AJS MVVM insights. 🙂

Please find the detailed tutorials on AJS here for more information:
http://zaiste.net/2013/07/concisely_how_to_get_started_with_angularjs/
http://codechutney.in/blog/javascript/mvc-and-mvvm-with-angularjs/
https://www.safaribooksonline.com/library/view/angularjs-up-and/9781491901939/ch01.html
https://angularjs.org/ (Official AJS site).
Disclaimer:

• This article is intended to explain the idea of MVVM design pattern using AJS in Hybrid apps. This will not give any in-depth details of neither MVVM nor AJS.
• AJS can be done in MVC as well.
• MVC handled in a better way is also a good candidate that supports Modularity, and Plug and Play. MVVM enforces MVC in a better modular approach.

All about hammer.js a start to touch gestures and multitouch

All about hammer.js a start to touch gestures and multitouch

Hammer is a open-source JavaScript Library for adding touch gestures support that can recognize gestures made by touch, mouse and pointerEvents to any website so that users can interact with them easier on touch devices. It doesn’t have any dependencies, and it’s small, only 3.71 kB minified + gzipped!

It supports tap, double tap, press, hold, drag, horizontal pan and swipe and the multi-touch pinch and rotate recognizers and also transform.

Getting Started

What’s new in 2.0?

It’s completely rewritten, with reusable gesture recognizers, and improved support for the recent mobile browsers by making use of the touch-action css property when possible. Also support for multiple Hammer instances the same time, so multi-user became possible.


Usage

It’s easy to use, just include the library and create a new instance.

var hammertime = new Hammer(myElement, myOptions);
hammertime.on('pan', function(ev) {
    console.log(ev);
});

By default it adds a set of tap, doubletap, press, horizontal pan and swipe, and the multi-touch pinch and rotate recognizers. The pinch and rotate recognizers are disabled by default because they would make the element blocking, but you can enable them by calling:

hammertime.get('pinch').set({ enable: true });
hammertime.get('rotate').set({ enable: true });

Enabling vertical or all directions for the pan and swipe recognizers:

hammertime.get('pan').set({ direction: Hammer.DIRECTION_ALL });
hammertime.get('swipe').set({ direction: Hammer.DIRECTION_VERTICAL });

Also the viewport meta tag is recommended, it gives more control back to the webpage by disableing the doubletap/pinch zoom. More recent browsers that support the touch-action property don’t require this.

<meta name="viewport" content="user-scalable=no, width=device-width,
 initial-scale=1, maximum-scale=1">

More control

You can setup your own set of recognizers for your instance. This requires a bit more code, but it gives you more control about the gestures that are being recognized.

var mc = new Hammer.Manager(myElement, myOptions);

mc.add( new Hammer.Pan({ direction: Hammer.DIRECTION_ALL, threshold: 0 }) );
mc.add( new Hammer.Tap({ event: 'quadrupletap', taps: 4 }) );

mc.on("pan", handlePan);
mc.on("quadrupletap", handleTaps);

The example above creates an instance containing a pan and a quadrupletap gesture. The recognizer instances you create a being executed in the order they are added, and only one can be recognized at the time.

Simultaneous recognizing

If you want to recognize two gestures simultaneously, you can use the the recognizeWith() method. The example below does this with the pinch and rotate recognizers, which will improve usability.

var pinch = new Hammer.Pinch();
var rotate = new Hammer.Rotation();
pinch.recognizeWith(rotate);

Now Hammer is able to run pinch and rotate the same time. You can also separate them with the dropRecognizeWith() method on the recognizer instance.

Require failure of an other recognizer

With the method requireFailure() you can let a recognizer require the failure of an other recognizer before recognizing. This could become useful when you want to nest two gestures, like pan-horizontal and pan-vertical. Removing the dependency could be done with the dropRequireFailure() method.

var horizontal = new Hammer.Pan({
    event: 'panh',
    direction: Hammer.DIRECTION_HORIZONTAL
});
var vertical = new Hammer.Pan({
    event: 'panv',
    direction: Hammer.DIRECTION_VERTICAL
});
vertical.requireFailure(horizontal);

Using requireFailure to recognize multiple taps

Because multiple gestures can be recognized simultaneously and a gesture can be recognized based on the failure of other gestures. Multiple taps on the same element can be easily recognized on this way:

var hammer = new Hammer(el, {});

var tap = new Hammer.Tap();
var doubleTap = new Hammer.Tap({event: 'doubleTap', taps: 2 });
var tripleTap = new Hammer.Tap({event: 'tripleTap', taps: 3 });

hammer.add([tripleTap, doubleTap, tap]);

tripleTap.recognizeWith([doubleTap, tap]);
doubleTap.recognizeWith(tap);

doubleTap.requireFailure(tripleTap);
tap.requireFailure([tripleTap, doubleTap]);

When a tap gesture requires a failure to be recognized, its recognizer will wait a short period to check that the other gesture has been failed. In this case, you should not assume that its tap gesture event will be fired immediately.

Tips ‘n Tricks

Try to avoid vertical pan/swipe

Vertical panning is used to scroll your page, and some (older) browsers don’t send events so Hammer isn’t able to recognize these gestures. An option would be to provide an alternative way to do the same action.

Test on a real device

Sometimes Hammer just needs some fine-tuning, like the swipe velocity or some other thresholds. Also, for better performance on slower devices your should try to keep you callbacks as simple as possible.

Remove tap highlight on Windows Phone

IE10 and IE11 on Windows Phone have a small tap highlight when you tap an element. Adding this meta tag removes this.

<meta name="msapplication-tap-highlight" content="no" />

“I can’t select my text anymore!”

Hammer is setting a property to improve the UX of the panning on desktop. Regularly, the desktop browser would select the text while you drag over the page. The user-select css property disables this.

If you care about the text-selection and not so much about the desktop experience, you can simply remove this option from the defaults. Make sure you do this before creating an instance.

delete Hammer.defaults.cssProps.userSelect;


Browser/device support

Don’t worry if your browser or OS isn’t listed, it might work anyway! Internet Explorer 8 and older aren’t supported.

Browsers that have native support for touch-action might have an improved experience then the browsers that don’t.

Browser Pan Pinch Press Rotate Swipe Tap Multi-user Touch-action
Windows Phone 8 – IE10
Android 2.3 – browser
Android 2.3 – FireFox
Android 4.x – browser
Android 4.4 – browser
Android 4 – Chrome
Android 4 – Opera ?
Android 4 – FireFox
Android 4 w/ mouse n/a
iOS 6
iOS 7
BlackBerry 10 ? ?
FireFox OS (simulator) ? ?
Desktop – IE11
Desktop – IE10
Desktop – IE9
Desktop – Chrome
Desktop – Firefox
Desktop – Opera ?
Chromebook ?
Windows 8 /w pen n/a
Windows 8 /w touch n/a
Windows 8 /w mouse n/a
Windows 8 /w mixed n/a

backbone.js tutorial a walk through

backbone.js tutorial

BACKBONE.JS

Why do you need Backbone.js?

Building single-page web apps or complicated user interfaces will get extremely difficult by simply using jQuery or MooTools. The problem is standard JavaScript libraries are great at what they do – and without realizing it you can build an entire application without any formal structure. You will with ease turn your application into a nested pile of jQuery callbacks, all tied to concrete DOM elements.

I shouldn’t need to explain why building something without any structure is a bad idea. Of course you can always invent your own way of structuring your application but you miss out on the benefits of the open source community.

Why single page applications are the future

Backbone.js enforces that communication to the server should be done entirely through a RESTful API. The web is currently trending such that all data/content will be exposed through an API. This is because the browser is no longer the only client, we now have mobile devices, tablet devices, Google Goggles and electronic fridges etc.

So how does Backbone.js help?

Backbone is an incredibly small library for the amount of functionality and structure it gives you. It is essentially MVC for the client and allows you to make your code modular. If you read through some of the beginner tutorials the benefits will soon become self evident and due to Backbone.js light nature you can incrementally include it in any current or future projects.

What is a model?

Across the internet the definition of MVC is so diluted that it’s hard to tell what exactly your model should be doing. The authors of backbone.js have quite a clear definition of what they believe the model represents in backbone.js.

Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control.

So for the purpose of the tutorial let’s create a model.

    Person = Backbone.Model.extend({
        initialize: function(){
            alert("Welcome to this world");
        }
    });

    var person = new Person;

So initialize() is triggered whenever you create a new instance of a model( models, collections and views work the same way ). You don’t have to include it in your model declaration but you will find yourself using it more often than not.

Setting attributes

Now we want to pass some parameters when we create an instance of our model.

    Person = Backbone.Model.extend({
        initialize: function(){
            alert("Welcome to this world");
        }
    });

    var person = new Person({ name: "Thomas", age: 67});
    // or we can set afterwards, these operations are equivelent
    var person = new Person();
    person.set({ name: "Thomas", age: 67});

So passing a JavaScript object to our constructor is the same as calling model.set(). Now that these models have attributes set we need to be able to retrieve them.

Getting attributes

Using the model.get() method we can access model properties at anytime.

    Person = Backbone.Model.extend({
        initialize: function(){
            alert("Welcome to this world");
        }
    });

    var person = new Person({ name: "Thomas", age: 67, child: 'Ryan'});

    var age = person.get("age"); // 67
    var name = person.get("name"); // "Thomas"
    var child = person.get("child"); // 'Ryan'

Setting model defaults

Sometimes you will want your model to contain default values. This can easily be accomplished by setting a property name ‘defaults’ in your model declaration.

    Person = Backbone.Model.extend({
        defaults: {
            name: 'Fetus',
            age: 0,
            child: ''
        },
        initialize: function(){
            alert("Welcome to this world");
        }
    });

    var person = new Person({ name: "Thomas", age: 67, child: 'Ryan'});

    var age = person.get("age"); // 67
    var name = person.get("name"); // "Thomas"
    var child = person.get("child"); // 'Ryan'

Manipulating model attributes

Models can contain as many custom methods as you like to manipulate attributes. By default all methods are public.

    Person = Backbone.Model.extend({
        defaults: {
            name: 'Fetus',
            age: 0,
            child: ''
        },
        initialize: function(){
            alert("Welcome to this world");
        },
        adopt: function( newChildsName ){
            this.set({ child: newChildsName });
        }
    });

    var person = new Person({ name: "Thomas", age: 67, child: 'Ryan'});
    person.adopt('John Resig');
    var child = person.get("child"); // 'John Resig'

So we can implement methods to get/set and perform other calculations using attributes from our model at any time.

Listening for changes to the model

Now onto one of the more useful parts of using a library such as backbone. All attributes of a model can have listeners bound to them to detect changes to their values. In our initialize function we are going to bind a function call everytime we change the value of our attribute. In this case if the name of our “person” changes we will alert their new name.

    Person = Backbone.Model.extend({
        defaults: {
            name: 'Fetus',
            age: 0
        },
        initialize: function(){
            alert("Welcome to this world");
            this.on("change:name", function(model){
                var name = model.get("name"); // 'Stewie Griffin'
                alert("Changed my name to " + name );
            });
        }
    });

    var person = new Person({ name: "Thomas", age: 67});
    person.set({name: 'Stewie Griffin'}); // This triggers a change and will alert()

So we can bind the change listener to individual attributes or if we like simply ‘this.on(“change”, function(model){});‘ to listen for changes to all attributes of the model.

Interacting with the server

Models are used to represent data from your server and actions you perform on them will be translated to RESTful operations.

The id attribute of a model identifies how to find it on the database usually mapping to the surrogate key.

For the purpose of this tutorial imagine that we have a mysql table called Users with the columns idnameemail.

The server has implemented a RESTful URL /user which allows us to interact with it.

Our model definition shall thus look like;

    var UserModel = Backbone.Model.extend({
        urlRoot: '/user',
        defaults: {
            name: '',
            email: ''
        }

    });

Creating a new model

If we wish to create a new user on the server then we will instantiate a new UserModel and call save. If the id attribute of the model is null, Backbone.js will send a POST request to the urlRoot of the server.

    var UserModel = Backbone.Model.extend({
        urlRoot: '/user',
        defaults: {
            name: '',
            email: ''
        }
    });
    var user = new Usermodel();
    // Notice that we haven't set an `id`
    var userDetails = {
        name: 'Thomas',
        email: 'thomasalwyndavis@gmail.com'
    };
    // Because we have not set a `id` the server will call
    // POST /user with a payload of {name:'Thomas', email: 'thomasalwyndavis@gmail.com'}
    // The server should save the data and return a response containing the new `id`
    user.save(userDetails, {
        success: function (user) {
            alert(user.toJSON());
        }
    })

Our table should now have the values

1, ‘Thomas’, ‘thomasalwyndavis@gmail.com’

Getting a model

Now that we have saved a new user model, we can retrieve it from the server. We know that the id is 1 from the above example.

If we instantiate a model with an id, Backbone.js will automatically perform a get request to the urlRoot + ‘/id’ (conforming to RESTful conventions)

    // Here we have set the `id` of the model
    var user = new Usermodel({id: 1});

    // The fetch below will perform GET /user/1
    // The server should return the id, name and email from the database
    user.fetch({
        success: function (user) {
            alert(user.toJSON());
        }
    })

Updating a model

Now that we have a model that exist on the server we can perform an update using a PUT request. We will use the save api call which is intelligent and will send a PUT request instead of a POST request if an id is present(conforming to RESTful conventions)

    // Here we have set the `id` of the model
    var user = new Usermodel({
        id: 1,
        name: 'Thomas',
        email: 'thomasalwyndavis@gmail.com'
    });

    // Let's change the name and update the server
    // Because there is `id` present, Backbone.js will fire
    // PUT /user/1 with a payload of `{name: 'Davis', email: 'thomasalwyndavis@gmail.com'}`
    user.save({name: 'Davis'}, {
        success: function (model) {
            alert(user.toJSON());
        }
    });

Deleting a model

When a model has an id we know that it exist on the server, so if we wish to remove it from the server we can call destroydestroy will fire off a DELETE /user/id (conforming to RESTful conventions).

    // Here we have set the `id` of the model
    var user = new Usermodel({
        id: 1,
        name: 'Thomas',
        email: 'thomasalwyndavis@gmail.com'
    });

    // Because there is `id` present, Backbone.js will fire
    // DELETE /user/1 
    user.destroy({
        success: function () {
            alert('Destroyed');
        }
    });

Tips and Tricks

Get all the current attributes

      
    var person = new Person({ name: "Thomas", age: 67});
    var attributes = person.toJSON(); // { name: "Thomas", age: 67}
    /* This simply returns a copy of the current attributes. */

    var attributes = person.attributes;
    /* The line above gives a direct reference to the attributes and you should be careful when playing with it.   Best practise would suggest that you use .set() to edit attributes of a model to take advantage of backbone listeners. */

Validate data before you set or save it

    Person = Backbone.Model.extend({
        // If you return a string from the validate function,
        // Backbone will throw an error
        validate: function( attributes ){
            if( attributes.age < 0 && attributes.name != "Dr Manhatten" ){
                return "You can't be negative years old";
            }
        },
        initialize: function(){
            alert("Welcome to this world");
            this.bind("error", function(model, error){
                // We have received an error, log it, alert it or forget it :)
                alert( error );
            });
        }
    });

    var person = new Person;
    person.set({ name: "Mary Poppins", age: -1 }); 
    // Will trigger an alert outputting the error

    var person = new Person;
    person.set({ name: "Dr Manhatten", age: -1 });
    // God have mercy on our souls

What is a view?

Backbone views are used to reflect what your applications’ data models look like. They are also used to listen to events and react accordingly. This tutorial will not be addressing how to bind models and collections to views but will focus on view functionality and how to use views with a JavaScript templating library, specifically Underscore.js’s _.template.

We will be using jQuery 1.8.2 as our DOM manipulator. It’s possible to use other libraries such as MooTools or Sizzle, but official Backbone.js documentation endorses jQuery. Backbone.View events may not work with other libraries other than jQuery.

For the purposes of this demonstration, we will be implementing a search box. A live example can be found on jsFiddle.

    SearchView = Backbone.View.extend({
        initialize: function(){
            alert("Alerts suck.");
        }
    });

    // The initialize function is always called when instantiating a Backbone View.
    // Consider it the constructor of the class.
    var search_view = new SearchView();

The “el” property

The “el” property references the DOM object created in the browser. Every Backbone.js view has an “el” property, and if it not defined, Backbone.js will construct its own, which is an empty div element.

Let us set our view’s “el” property to div#search_container, effectively making Backbone.View the owner of the DOM element.

<div id="search_container"></div>

<script type="text/javascript">
    SearchView = Backbone.View.extend({
        initialize: function(){
            alert("Alerts suck.");
        }
    });

    var search_view = new SearchView({ el: $("#search_container") });
</script>

Note: Keep in mind that this binds the container element. Any events we trigger must be in this element.

Loading a template

Backbone.js is dependent on Underscore.js, which includes its own micro-templating solution. Refer to Underscore.js’s documentation for more information.

Let us implement a “render()” function and call it when the view is initialized. The “render()” function will load our template into the view’s “el” property using jQuery.

<script type="text/template" id="search_template">
  <label>Search</label>
  <input type="text" id="search_input" />
  <input type="button" id="search_button" value="Search" />
</script>

<div id="search_container"></div>

<script type="text/javascript">
    SearchView = Backbone.View.extend({
        initialize: function(){
            this.render();
        },
        render: function(){
            // Compile the template using underscore
            var template = _.template( $("#search_template").html(), {} );
            // Load the compiled HTML into the Backbone "el"
            this.$el.html( template );
        }
    });

    var search_view = new SearchView({ el: $("#search_container") });
</script>

Tip: Place all your templates in a file and serve them from a CDN. This ensures your users will always have your application cached.

Listening for events

To attach a listener to our view, we use the “events” attribute of Backbone.View. Remember that event listeners can only be attached to child elements of the “el” property. Let us attach a “click” listener to our button.

<script type="text/template" id="search_template">
  <label>Search</label>
  <input type="text" id="search_input" />
  <input type="button" id="search_button" value="Search" />
</script>

<div id="search_container"></div>

<script type="text/javascript">
    SearchView = Backbone.View.extend({
        initialize: function(){
            this.render();
        },
        render: function(){
            var template = _.template( $("#search_template").html(), {} );
            this.$el.html( template );
        },
        events: {
            "click input[type=button]": "doSearch"
        },
        doSearch: function( event ){
            // Button clicked, you can access the element that was clicked with event.currentTarget
            alert( "Search for " + $("#search_input").val() );
        }
    });

    var search_view = new SearchView({ el: $("#search_container") });
</script>

Tips and Tricks

Using template variables

<script type="text/template" id="search_template">
    <!-- Access template variables with <%= %> -->
    <label><%= search_label %></label>
    <input type="text" id="search_input" />
    <input type="button" id="search_button" value="Search" />
</script>

<div id="search_container"></div>

<script type="text/javascript">
     SearchView = Backbone.View.extend({
        initialize: function(){
            this.render();
        },
        render: function(){
            //Pass variables in using Underscore.js Template
            var variables = { search_label: "My Search" };
            // Compile the template using underscore
            var template = _.template( $("#search_template").html(), variables );
            // Load the compiled HTML into the Backbone "el"
            this.$el.html( template );
        },
        events: {
            "click input[type=button]": "doSearch"  
        },
        doSearch: function( event ){
            // Button clicked, you can access the element that was clicked with event.currentTarget
            alert( "Search for " + $("#search_input").val() );
        }
    });

    var search_view = new SearchView({ el: $("#search_container") });
</script>

What is a router?

Backbone routers are used for routing your applications URL’s when using hash tags(#). In the traditional MVC sense they don’t necessarily fit the semantics and if you have read “What is a view?” it will elaborate on this point. Though a Backbone “router” is still very useful for any application/feature that needs URL routing/history capabilities.

Defined routers should always contain at least one route and a function to map the particular route to. In the example below we are going to define a route that is always called.

Also note that routes interpret anything after “#” tag in the URL. All links in your application should target “#/action” or “#action”. (Appending a forward slash after the hashtag looks a bit nicer e.g. http://example.com/#/user/help)

<script>
    var AppRouter = Backbone.Router.extend({
        routes: {
            "*actions": "defaultRoute" // matches http://example.com/#anything-here
        }
    });
    // Initiate the router
    var app_router = new AppRouter;

    app_router.on('route:defaultRoute', function(actions) {
        alert(actions);
    })

    // Start Backbone history a necessary step for bookmarkable URL's
    Backbone.history.start();

</script>

Dynamic Routing

Most conventional frameworks allow you to define routes that contain a mix of static and dynamic route parameters. For example you might want to retrieve a post with a variable id with a friendly URL string. Such that your URL would look like “http://example.com/#/posts/12”. Once this route was activated you would want to access the id given in the URL string. This example is implemented below.

<script>
    var AppRouter = Backbone.Router.extend({
        routes: {
            "posts/:id": "getPost",
            "*actions": "defaultRoute" // Backbone will try match the route above first
        }
    });
    // Instantiate the router
    var app_router = new AppRouter;
    app_router.on('route:getPost', function (id) {
        // Note the variable in the route definition being passed in here
        alert( "Get post number " + id );   
    });
    app_router.on('route:defaultRoute', function (actions) {
        alert( actions ); 
    });
    // Start Backbone history a necessary step for bookmarkable URL's
    Backbone.history.start();

</script>

Dynamic Routing Cont. “:params” and “*splats”

Backbone uses two styles of variables when implementing routes. First there are “:params” which match any URL components between slashes. Then there are “splats” which match any number of URL components. Note that due to the nature of a “splat” it will always be the last variable in your URL as it will match any and all components.

Any “*splats” or “:params” in route definitions are passed as arguments (in respective order) to the associated function. A route defined as “/:route/:action” will pass 2 variables (“route” and “action”) to the callback function. (If this is confusing please post a comment and I will try articulate it better)

Here are some examples of using “:params” and “*splats”

        routes: {

            "posts/:id": "getPost",
            // <a href="http://example.com/#/posts/121">Example</a>

            "download/*path": "downloadFile",
            // <a href="http://example.com/#/download/user/images/hey.gif">Download</a>

            ":route/:action": "loadView",
            // <a href="http://example.com/#/dashboard/graph">Load Route/Action View</a>

        },

        app_router.on('route:getPost', function( id ){ 
            alert(id); // 121 
        });
        app_router.on('route:downloadFile', function( path ){ 
            alert(path); // user/images/hey.gif 
        });
        app_router.on('route:loadView', function( route, action ){ 
            alert(route + "_" + action); // dashboard_graph 
        });

Routes are quite powerful and in an ideal world your application should never contain too many. If you need to implement hash tags with SEO in mind, do a google search for “google seo hashbangs”. Also check out Seo Server

What is a collection?

Backbone collections are simply an ordered set of models. Such that it can be used in situations such as;

  • Model: Student, Collection: ClassStudents
  • Model: Todo Item, Collection: Todo List
  • Model: Animal, Collection: Zoo

Typically your collection will only use one type of model but models themselves are not limited to a type of collection;

  • Model: Student, Collection: Gym Class
  • Model: Student, Collection: Art Class
  • Model: Student, Collection: English Class

Here is a generic Model/Collection example.

  var Song = Backbone.Model.extend({
      initialize: function(){
          console.log("Music is the answer");
      }
  });

  var Album = Backbone.Collection.extend({
    model: Song
  });

Building a collection

Now we are going to populate a collection with some useful data.

    var Song = Backbone.Model.extend({
        defaults: {
            name: "Not specified",
            artist: "Not specified"
        },
        initialize: function(){
            console.log("Music is the answer");
        }
    });

    var Album = Backbone.Collection.extend({
        model: Song
    });

    var song1 = new Song({ name: "How Bizarre", artist: "OMC" });
    var song2 = new Song({ name: "Sexual Healing", artist: "Marvin Gaye" });
    var song3 = new Song({ name: "Talk It Over In Bed", artist: "OMC" });

    var myAlbum = new Album([ song1, song2, song3]);
    console.log( myAlbum.models ); // [song1, song2, song3]

Shlokas from the Bhagavad Gita

Shlokas from the Bhagavad Gita

1. Gita dhyaanam – Meditation on the Gita

vasudeva sutam devam
kamsa chaanuura mardanam |
devakii paramaa nandam
krishnam vande jagat gurum ||

I salute Lord Krishna, the son of Vasudeva, the one who gives great delight to Devaki, the destroyer of Kamsa and Chaanuura and the teacher of the world.

2. Chapter 4, Verse 8

paritraanaaya sadhuunaam vinaashaaya chadushkritaam |
dharma samsthaapanaarthaaya sambhavaami yuge yuge ||

For the protection of the good, for the destruction of the evil and for the establishment of dharma (righteousness), I (the Lord) am born from age to age.

3. Chapter 2, Verse 62

dhyaayato vishayaanh pumsah sangasteshhupajaayate |
sangaath samjaayate kaamah kaamaath krodho abhijaayate ||

When a person dwells longingly on sense objects, an inclination towards them is generated.
This inclination develops into desire and desire gives rise to anger.

4. Chapter 2, Verse 63

krodhaadbhavati sammohah sammohaatsmritivibhramah |
smritibhramshaadbuddhinaasho buddhinaashaatpranashyati ||

From anger comes delusion; from delusion, confused memory; from confused memory the ruin of reason; from ruin of reason, man finally perishes.

5. Chapter 6, Verse 5

uddharedaatmanaatmaanam naatmaanamavasaadayeth |
aatmaiva hyaatmano bandhuraatmaiva ripuraatmanah ||

Let a man raise himself by his own efforts. Let him not degrade himself.

Because a person’s best friend or his worst enemy is none other than his own self.

6. Chapter 6, Verse 6

bandhuraatmaatmanastasya yenaatmaivaatmanaa jitah |
anaatmanastu shatrutve vartetaatmaiva shatruvath ||

For a person who has conquered his lower self by the divine self, his own self acts as his best friend. But for that person who has not conquered his lower self, his own self acts as his worst enemy.

7. Chapter 4, Verse 7

yadaa yadaa hi dharmasya glaanirbhavati bhaarata |
abhyuktaanamadarmasya tadaatmaanam srijaamyahamh ||

When there is decay of dharma (righteousness) and rise of adharma (unrighteousness),
then I (the Lord) am born in this world.

8. Chapter 2, Verse 47

karmanyevaadhikaaraste maa phaleshu kadaachana |
maa karmaphalaheturbhuu maatesangotsvakarmani ||

A person has the right towards action alone and not towards the fruit of action. Let not the fruit of action be the motive for acting. Also, Let there not be any attachment to inaction.

9. Chapter 2, Verse 22

vaasaamsi jiirnaani yathaa vihaaya, navaani grihnaati naro aparaani |
tathaa shariiraani vihaaya jiirnaanyanyaani samyaati navaani dehii ||

Just as a person casts off worn out garments and puts on others that are new, even so, the embodies soul casts off worn out bodies and takes on others that are new.

10. Chapter 9, Verse 27

yatkaroshhi yadashnaasi yajjuhoshhi dadaasi yath |
yattapasyasi kaunteya tatkurushhva madarpanamh ||

Arjuna, whatever you do, whatever you eat, whatever you offer (in sacrifice), whatever you give away, whatever you do by way of penance, offer it all to me.

11. Chapter 4, Verse 9

janma karma cha me divyamevam yo vetti tattvatah |
tyaktvaa deham punarjanma naiti maameti so arjuna ||

Arjuna, My birth and activities are divine. He who knows this in reality is not reborn on leaving his body, but comes to Me.

12. Chapter 9, Verse 26

patram pushhpam phalam toyam yo me bhaktyaa prayachchati |
tadaham bhaktyupahritamashnaami prayataatmanah ||

I accept the offering of even a leaf, a flower, fruit or water, when it is offered with loving devotion.

13. Chapter 3, Verse 19

tasmaadasaktah satatam kaaryam karma samachara |
asakto hyaacharankarma paramaapnoti puurushah ||

(Therefore) You must always fulfill all your obligatory duties without attachment. By performing actions without attachment, one attains the Highest.

14. Chapter 3, Verse 37

kaama eshha krodha eshha rajogunasamudbhavah |
mahaashano mahaapaapma viddhyenamiha vairinamh ||

Desire and anger which are born out of passion are insatiable and prompt man to great sin and should be recognized as enemies.

15. Chapter 6, Verse 26

yato yato nishcharati manashcha.nchalamasthiramh |
tatastato niyamyaitadaatmanyeva vasham nayeth ||

By whatever cause the mind, which is restless and fidgeting, wanders away, the yogi should bring it back from that and concentrate only on the Self.

16. Chapter 5, Verse 10

brahmanyaadhaaya karmaani sangam tyaktvaa karoti yah |
lipyate na sa paapena padmapatramivaambhasaa ||

He who offers all actions to God, without attachment, remains untouched by sin, just as a lotus leaf by water.

17. Chapter 18, Verse 65

manmanaa bhava madbhakto madyaajii maam namaskuru |
maamevaishhyasi satyam te pratijaane priyo asi me ||

Give your mind to Me, be devoted to Me, worship Me and bow to Me. Doing so, you will come to Me alone, I truly promise you, for you are so exceptionally dear to Me.

18. Chapter 7, Verse 3

manushhyaanaam sahasreshhu kashchidyatati siddhaye |
yatataamapi siddhaanaam kashchinmaam vetti tatvatah ||

Hardly one among thousands of men strives to realize Me;
Of those who strive, again, only a very rare one (devoting himself exclusively to Me) knows Me in reality.

19. Chapter 8, Verse 5

antakaale cha maameva smaranmuktvaa kalevaramh |
yah prayaati sa madbhaavam yaati naastyatra samshayah ||

He who departs from the body, thinking of Me alone, even at the time of death, will definetely reach Me.

20. Chapter 9, Verse 14

satatam kiirtayanto maam yatantashcha dridhavrataah |
namasyantashcha maam bhaktyaa nityayuktaa upaasate ||

My determined devotees constantly chant My name and glories, strive for realizing Me and worship Me with single minded devotion.

21. Chapter 10, Verse 41

yadyadvibhuutimatsatvam shriimadurjitameva vaa |
tattadevaavagachcha tvam mama tejo nashasambhavamh ||

(Arjuna,) Know that every being that is glorious, brilliant and powerful is nothing but a mainfestation of a small part of my glory.

22. Chapter 11, Verse 12

divi suuryasahasrasya bhavedyugapadutthitaa |
yadi bhaah sadrishii saa syaad hbhaasastasya mahaatmanah ||

Even If the radiance of a thousand Suns, bursts forth all at once in the heavens, it would still hardly approach the splendor of the mighty Lord.

23. Chapter 12, Verse 15

yasmaannodvijate loko lokaannodvijate cha yah |
harshhamarshhabhayodvegairmukto yah sa cha me priyah ||

He, by whom the world is not agitated and whom the world cannot agitate, he who remains calm in times of joy, anger, fear and anxiety, is dear to me.

24. Chapter 1, Verse 40

kulakshaye praNashyanti kuladharmaah sanaatanaah |
dharme nashhte kulam kritsnamh adharmo abhibhavatyuta ||

In the decline of a clan, its ancient traditions perish. When traditions perish, the entire family is indeed overcome by lawlessness.

25. Chapter 2, Verse 27

jaatasya hi dhruvo mrityuh dhruvam janma mritasya cha |
tasmaadaparihaarye arthe na tvam shochitumarhasi ||

Death is certain of that which is born. Birth is certain of that which is dead. Therefore, you should not lament over the inevitable.

26. Chapter 2, Verse 67

indriyaanaam hi charataam yanmano anuvidhiiyate |
tadasya harati pragyaam vaayarnaavamivaambhasi ||

The mind, which follows in the wake of the wandering senses, carries away a man’s discrimination just as a gale tosses a ship on the high seas.

27. Chapter 3, Verse 9

yagyaarthaatkarmano anyatra loko ayam karmabandhanah |
tadartham karma kaunteya muktasangah samaachara ||

Arjuna, In this world all actions become causes of bondage, unless they are performed as an offering to God. Therefore, work for the sake of God, without personal attachments.

28. Chapter 6, Verse 40

paartha naiveha naamutra vinaashastasya vidhyate |
na hi kalyaanakritkashchidh durgatim taata gachchati ||

Oh Arjuna, there is no destruction either in this world or the next, for a spiritually fallen yogi. No man who does good can ever come to ruin.

29. Chapter 9, Verse 30

api chetsuduraachaaro bhajate maamananyabhaakh |
saadhureva sa mantavyah samyagvyavasito hi sah ||

Even a confirmed sinner, if he worships Me with unwavering faith and devotion, must be considered righteous, because, he has decided to reform himself.

30. Chapter 18, Verse 66

sarvadharmaanparityajya maamekam sharanam vraja |
aham tvaa sarvapaapebhyo mokshayishhyaami maa shuchah ||

Abandoning all paths, come to Me as the only refuge. Grieve not, for I will liberate you from all sins.

31. Chapter 18, Verse 78

yatra yogeshvarah krishhno yatra paartho dhanurdharah |
tatra shriirvijayo bhuutirdhruvaa niitir matirmama ||

Wherever there is Krishna, the Lord of Yoga and the bow weilding Arjuna, there reign good fortune, victory, prosperity and justice. Such is my conviction.

Introduction to LESS and Comparison to Sass

Introduction to LESS and Comparison to Sass

I’ve been using LESS ever since I stumbled upon it. CSS was never really a problem for me, in and of itself, but I was intrigued by the idea of using variables to create something along the lines of a color palette for my websites and themes.
less

As it turns out, LESS — and Sass for that matter — are so much more than that. LESS and Sass share a lot of similarities in syntax, including the following:

  • Mixins – Classes for classes.
  • Parametric mixins – Classes to which you can pass parameters, like functions.
  • Nested Rules – Classes within classes, which cut down on repetitive code.
  • Operations – Math within CSS.
  • Color functions – Edit your colors.
  • Namespaces – Groups of styles that can be called by references.
  • Scope – Make local changes to styles.
  • JavaScript evaluation – JavaScript expressions evaluated in CSS.

The main difference between LESS and Sass is the way in which they are processed. LESS is a JavaScript library and is, therefore, processed client-side.

Sass, on the other hand, runs on Ruby and is processed server-side. A lot of developers might not choose LESS because of the additional time needed for the JavaScript engine to process the code and output the modified CSS to the browser. There are a few ways around this. The way I get around it is to use LESS only during the development process. Once I’m finished, I copy and paste the LESS output into a minifier and then into a separate CSS file to be included in place of the LESS files. Another option is to use LESS.app to compile and minify your LESS files. Both options will minimize the footprint of your styles, as well as avoid any problems that might result from the client’s browser not running JavaScript. While this is not likely, it’s always a possibility.

Once you have Sass installed you can compile Sass locally into CSS and ship the code with your project.

LESS Is More

Installation

Including LESS in something that you’re building is about as easy as it gets:

  1. Go get yourself a copy of less.js;
  2. Create a file to put your styles in, such as style.less;
  3. Add the following code to your HTML’s <head>:
<link rel="stylesheet/less" type="text/css" href="styles.less">
<script src="less.js" type="text/javascript"></script>

Note the rel attribute of the link. You are required to append the /less to the end of the value in order for LESS to work. You are also required to include the script immediately after the link to the style sheet. If you’re using HTML5 syntax, and I can’t imagine why you wouldn’t be, you can leave out the type="text/css" and the type="text/javascript".

There’s also a server-side version of LESS. The easiest way to install LESS on the server is with Node Package Manager (NPM).

Variables

If you’re a developer, variables are one of your best friends. In the event that you’ll be using information repeatedly (in this case, a color), setting it to a variable makes sense. This way, you guarantee yourself consistency and probably less scrolling about looking for a hex value to copy and paste. You can even do some fun little adding and subtracting of hex values that you want to render. Take this example:

@blue: #00c;
@light_blue: @blue + #333;
@dark_blue: @blue - #333;

If we apply these styles to three divs, we can see the gradated effect created by adding and subtracting the hex values to and from the original blue:

A screenshot illustrating the transition from 3 shades of blue
The transition from @light_blue to @blue to @dark_blue.

The only difference in variables between LESS and Sass is that, while LESS uses @, Sass uses $. There are some scope differences as well, which I’ll get to shortly.

Mixins

On occasion, we might create a style that’s intended to be used repeatedly throughout the style sheet. Nothing is stopping you from applying multiple classes to the elements in the HTML, but you could also do this without ever leaving your style sheet, using LESS. To illustrate this, I have pasted some sample code that one might use to style two elements on the page.

.border {
border-top: 1px dotted #333;
}

article.post {
background: #eee;
.border;
}

ul.menu {
background: #ccc;
.border;
}

This will give you something similar to what you would get if you had gone back to the HTML file and added the .bordered class to the two elements there — except you’ve done it without leaving the style sheet. And it works just as well:

With Sass, you declare @mixin prior to the style to identify it as a mixin. Later, you declare @include to call it.

@mixin border {
border-top: 1px dotted #333;
}

article.post {
background: #eee;
@include border;
}

ul.menu {
background: #ccc;
@include border;
}

Parametric Mixins

Like having functions in your CSS, these can be immensely useful for those seemingly redundant tasks of modern-day CSS.
The best and most useful example of their use relates to the many vendor prefixes that we struggle with during this transition from CSS2 to CSS3.

Selector Inheritance

Here’s something not provided in LESS. With this ability, you can append a selector to a previously established selector without the need to add it in a comma-separated format.

.menu {
	border: 1px solid #ddd;
}

.footer {
	@extend .menu;
}

/* will render like so: */
.menu, .footer {
	border: 1px solid #ddd;
}

Nested Rules

Nesting classes and ids in CSS can be one of the only methods to keep your styles from interfering with and from being interfered with any other styles that may be added along the way. But this can get very messy. Using a selector like #site-body .post .post-header h2 is unappealing and takes up a lot of unnecessary space. With LESS, you can nest ids, classes and elements as you go. Using the example above, you could do something like this:

#site-body { …

    .post { …

        .post-header { …

            h2 { … }

            a { …

            	&:visited { … }
            	&:hover { … }
            }
        }
    }
}

The above code is essentially the same as the ugly selector in the previous paragraph, but it’s much easier to read and understand, and it takes up much less space. You can also refer in element styles to their pseudo-elements by using the &, which in this case functions similar to this in JavaScript.

Operations

This is about what you would expect: using fixed numbers or variables to perform mathematical operations in your styles.

@base_margin: 10px;
@double_margin: @base_margin * 2;

@full_page: 960px;
@half_page: @full_page / 2;
@quarter_page: (@full_page / 2) / 2;

For the record, I am aware that I could have also divided by four to get the @quarter_page variable, but I wanted to illustrate that the parentheses rule from the “order of operations” also applies. Parentheses are also required if you’re going to perform operations within compound properties; for example, border: (@width / 2) solid #000.

Sass is a lot more versatile with numbers than LESS. It has built into it conversion tables to combine comparable units. Sass can work with unrecognized units of measurement and print them out. This feature was apparently introduced in an attempt to future-proof the library against changes made by the W3C.

/* Sass */
2in + 3cm + 2pc = 3.514in

/* LESS */
2in + 3cm + 2pc = Error

Color Functions

Earlier, I mentioned how LESS helps me stick to a color scheme in my coding process. One of the parts that contributes to this the most is the color function. Suppose you use a standard blue throughout your styles, and you want to use this color for a gradated “Submit” button in a form. You could go into Photoshop or another editor to get the hex value for a slightly lighter or darker shade than the blue for the gradient. Or you could just use a color function in LESS.

@blue: #369;

.submit {
    padding: 5px 10px;
    border: 1px solid @blue;
    background: -moz-linear-gradient(top, lighten(@blue, 10%), @blue 100%); /*Moz*/
    background: -webkit-gradient(linear, center top, center bottom, from(lighten(@blue, 10%)), color-stop(100%, @blue)); /*Webkit*/
    background: -o-linear-gradient(top, lighten(@blue, 10%) 0%, @blue 100%); /*Opera*/
    background: -ms-linear-gradient(top, lighten(@blue, 10%) 0%, @blue 100%); /*IE 10+*/
    background: linear-gradient(top, lighten(@blue, 10%) 0%, @blue 100%); /*W3C*/
    color: #fff;
    text-shadow: 0 -1px 1px rgba(0,0,0,0.4);
}

The lighten function literally lightens the color by a percentage value. In this case, it will lighten the base blue by 10%. This method enables us to change the color of gradated elements and any other elements with that color simply by changing the base color itself. This could prove immensely helpful in theming. Plus, if you used a parametric function, like the ones listed above, you could alleviate some of that browser-prefix tedium with something as simple as .linear-gradient(lighten(@blue), @blue, 100%);.

Either way, you get an effect that’s rather nice:

Screenshot of a styled submit button
Our nicely gradated, variable-based “Submit” button.

There are a lot of other color functions for darkening and saturating colors and even spinning the color wheel to other colors. I recommend trying them out to see what you can come up with.

Sass seems to have a lot more color options — not that I would need them all. Lighten and darken are the only ones that I see myself using often.

Conditionals and Control

This is rather nifty, and another thing not provided by LESS. With Sass, you have the ability to use if { } else { } conditional statements, as well as for { } loops. It supports and, or and not, as well as the <, >, <=, >= and == operators.

/* Sample Sass "if" statement */
@if lightness($color) >; 30% {
  background-color: #000;
} @else {
  background-color: #fff;
}

/* Sample Sass "for" loop */
@for $i from 1px to 10px {
  .border-#{i} {
    border: $i solid blue;
  }
}

Namespaces

Namespaces can be used to add another level of organization to our CSS, by allowing us to create groups of commonly used styles and then pick from them along the way. For instance, if we created a group of styles called defaults, we could pull from this group when we come across an element that needs it.

#defaults {
	.nav_list () {
		list-style: none;
		margin: 0; padding: 0;
	}
	.button () { … }
	.quote () { … }
}

Later, in our code, if we come across a ul element within a nav element, we would know that we’ll need our default style. So, we can simply call it, and it will be applied.

nav ul {
	#defaults > .nav_list;
}

Scope

Scoping is standard throughout programming and thus standard in LESS. If you define a variable at the root level of your style sheet, it will be available and consistent throughout the document. If, however, you redefine the variable from within a selector such as an id or class, then it will be available — with the new value — only within that selector.

@color: #00c; /* blue */

#header {
	@color: #c00; /* red */

	border: 1px solid @color; /* will have a red border */
}

#footer {
	border: 1px solid @color; /* will have a blue border */
}

Because we’ve restated the variable within the #header selector, the value for that variable will be different and will apply only within that selector. Anything before or after it will retain the value of the original statement.

Scope is handled a little differently in Sass. In the above code, when the @color variable is changed to red, it will be interpreted as such from that point on within the code.

Comments

This part is pretty basic. Two types of comments are valid in LESS. The standard CSS comment, /* comment */, is valid and will get passed through the processing and outputted. Single-line comments, // comment, work as well but will not get passed and outputted and, as a result, are “silent.”

Importing

Importing is pretty standard, too. The standard @import: 'classes.less'; works just fine. If, however, you’re importing another LESS file, then the file extension is optional, so @import 'classes'; would work as well. If you want to import something without LESS processing it, you can use the .css extension (for example, @import: 'reset.css';).

String Interpolation

String values can also be used in variables and called within styles via @{name}.

@base_url = 'http://someurl.com';
background-image: url("@{base_url}/images/background.png");

Escaping

There will be times when you need to include a value that is not valid CSS syntax or that LESS doesn’t recognize. More often than not, it will be some crazy Microsoft hack. To avoid throwing errors and breaking LESS, you will need to escape them.

.class {
	filter: ~"progid:DXImageTransform.Microsoft.Alpha(opacity=20)";
}

/* Will actually be outputted like this: */
.class {
	filter: progid:DXImageTransform.Microsoft.Alpha(opacity=20);
}

JavaScript Evaluation

This is one of my favorite parts of LESS: using Javascript in style sheets — simply brilliant. You can use expressions and also reference aspects of the environment using backticks.

@string: `'howdy'.toUpperCase()`; /* @string becomes 'HOWDY' */

/* You can also use the previously mentioned interpolation: */
@string: 'howdy';
@var: ~`'@{string}'.topUpperCase()`; /* becomes 'HOWDY' */

/* Here we access part of the document */
@height = `document.body.clientHeight`;

Output Formatting

Whereas LESS has no output settings, Sass provides four output versions: nested, compact, compressed and expanded.

Final Thoughts

These two libraries share a lot of basics. Both of them are fantastic tools for designers who code, and they can also help developers work more efficiently and quickly. If you’re a fan of Ruby or HAML, then Sass might be right up your ally. For me, being a PHP and JavaScript geek, I tend to lean towards LESS for its ease of inclusion and access to JavaScript’s expressions and document attributes. I doubt that I’ve even come close to truly grasping the possibilities of programming in my style sheets, but I am intent on trying. If you’ve been using either, or both, of these in your work, I’d love to hear more about it and see some of your results. Tips, tricks and corrections are, of course, always welcome as well.

Sencha the Layout Manager

Sencha Using the hbox and vbox Layout Managers

I am just trying myself to brief about layout management in Sencha; Sencha the Layout Manager

The hbox layout manager orients nested components along the horizontal axis.
The vbox layout manager operates identically to the hbox layout manager, except that it orients components along the vertical axis.

The following example illustates using a simple hbox layout:

Ext.Viewport.add([
{
xtype: 'container',
layout: 'hbox',
cls: 'colorize',
width: 200,
height: 100,
defaults: {
xtype: 'component',
cls: 'colorize',
margin: '5 5 5 5'
},
items: [
{ html: 'Hello' },
{ html: 'World' }
]
}
]);

Using Flex Sizing

You can assign the flex property to any component that is participating in an hbox or vbox layout. The flex property sizes components relative to each other as illustrated by the following example. Note that the “Hello” component is flexed to be twice the size as the “World” component.

Ext.Viewport.add([
{
xtype: 'container',
layout: 'hbox',
cls: 'colorize',
width: 200,
height: 100,
defaults: {
xtype: 'component',
cls: 'colorize',
margin: '5 5 5 5'
},
items: [
{ html: 'Hello', flex: 2 },
{ html: 'World', flex: 1 }
]
}
]);

Centering Components in a Layout

Use the pack configuration property of the hbox or vbox layout to control whether the nested component items should align to the left edge, right edge, center, or be justified in their container.

The following example centers nested components in their parent container:

Ext.Viewport.add([
{
xtype: 'container',
layout: {
type: 'hbox',
pack: 'center'
},
cls: 'colorize',
width: 200
height: 100,
defaults: {
xtype: 'component',
cls: 'colorize',
margin: '5 5 5 5'
},
items: [
{ html: 'Hello' },
{ html: 'World' }
]
}
]);

Valid values for the pack attribute are ‘left’ (default), ‘right’, ‘center’, and ‘justify’:

Layout Config Result
{
type: ‘hbox’,
pack: ‘left’
}
pack: 'left'
{
type: ‘hbox’,
pack: ‘right’
}
pack: 'right'
{
type: ‘hbox’,
pack: ‘center’
}
pack: 'center'
{
type: ‘hbox’,
pack: ‘justify’
}
pack: 'justify'

 

Aligning Components in a Layout

Use the align configuration property of the hbox or vbox layout to designate whether the nested containers should “stretch” across the opposing axis. For example, in an hbox layout, configuring align: ‘stretch’ would expand the child components vertically. In a vbox layout, configuring align: ‘stretch’ would expand the child components horizontally.

Valid values for the align attribute are ‘stretch’,’start’, ‘end’, and ‘center’.

Layout Config Result
{
type: ‘hbox’,
pack: ‘center’,
align: ‘center’
}
using align:center in an hbox
{
type: ‘hbox’,
pack: ‘center’,
align: ‘stretch’
}
align: 'stretch'
{
type: ‘hbox’,
pack: ‘center’,
align: ‘start’
}
align: 'start'
{
type: ‘hbox’,
pack: ‘center’,
align: ‘end’
}
align: 'end'

Bootstrap Migrating from 2.x to 3.0

Bootstrap Migrating from 2.x to 3.0

Bootstrap 3 is not backwards compatible with v2.x. Use this section as a general guide to upgrading from v2.x to v3.0. For a broader overview, see what’s new in the v3.0 release announcement.

Major class changes
This table shows the style changes between v2.x and v3.0.

Bootstrap 2.x Bootstrap 3.0
.container-fluid .container
.row-fluid .row
.span* .col-md-*
.offset* .col-md-offset-*
.brand .navbar-brand
.nav-collapse .navbar-collapse
.nav-toggle .navbar-toggle
.btn-navbar .navbar-btn
.hero-unit .jumbotron
.icon-* .glyphicon .glyphicon-*
.btn .btn .btn-default
.btn-mini .btn-xs
.btn-small .btn-sm
.btn-large .btn-lg
.alert-error .alert-danger
.visible-phone .visible-xs
.visible-tablet .visible-sm
.visible-desktop Split into .visible-md .visible-lg
.hidden-phone .hidden-xs
.hidden-tablet .hidden-sm
.hidden-desktop Split into .hidden-md .hidden-lg
.input-small .input-sm
.input-large .input-lg
.control-group .form-group
.control-group.warning .control-group.error .control-group.success .form-group.has-*
.checkbox.inline .radio.inline .checkbox-inline .radio-inline
.input-prepend .input-append .input-group
.add-on .input-group-addon
.img-polaroid .img-thumbnail
ul.unstyled .list-unstyled
ul.inline .list-inline
.muted .text-muted
.label .label .label-default
.label-important .label-danger
.text-error .text-danger
.table .error .table .danger
.bar .progress-bar
.bar-* .progress-bar-*
.accordion .panel-group
.accordion-group .panel .panel-default
.accordion-heading .panel-heading
.accordion-body .panel-collapse
.accordion-inner .panel-body

What’s new

Bootstrap added new elements and changed some existing ones. Here are the new or updated styles.

Element Description
Panels .panel .panel-default .panel-body .panel-title .panel-heading .panel-footer .panel-collapse
List groups .list-group .list-group-item .list-group-item-text .list-group-item-heading
Glyphicons .glyphicon
Jumbotron .jumbotron
Extra small grid (<768px) .col-xs-*
Small grid (≥768px) .col-sm-*
Medium grid (≥992px) .col-md-*
Large grid (≥1200px) .col-lg-*
Responsive utility classes (≥1200px) .visible-lg .hidden-lg
Offsets .col-sm-offset-* .col-md-offset-* .col-lg-offset-*
Push .col-sm-push-* .col-md-push-* .col-lg-push-*
Pull .col-sm-pull-* .col-md-pull-* .col-lg-pull-*
Input groups .input-group .input-group-addon .input-group-btn
Form controls .form-control .form-group
Button group sizes .btn-group-xs .btn-group-sm .btn-group-lg
Navbar text .navbar-text
Navbar header .navbar-header
Justified tabs / pills .nav-justified
Responsive images .img-responsive
Contextual table rows .success .danger .warning .active
Contextual panels .panel-success .panel-danger .panel-warning .panel-info
Modal .modal-dialog .modal-content
Thumbnail image .img-thumbnail
Well sizes .well-sm .well-lg
Alert links .alert-link

What’s removed

The following elements have been dropped or changed in v3.0.

Element Removed from 2.x 3.0 Equivalent
Form actions .form-actions N/A
Search form .form-search N/A
Form group with info .control-group.info N/A
Fluid container .container-fluid .container (no more fixed grid)
Fluid row .row-fluid .row (no more fixed grid)
Controls wrapper .controls N/A
Controls row .controls-row .row or .form-group
Navbar inner .navbar-inner N/A
Navbar vertical dividers .navbar .divider-vertical N/A
Dropdown submenu .dropdown-submenu N/A
Tab alignments .tabs-left .tabs-right .tabs-below N/A
Nav lists .nav-list .nav-header No direct equivalent, but list groups and .panel-groups are similar.

Additional notes

Other changes in v3.0 are not immediately apparent. Base classes, key styles, and behaviors have been adjusted for flexibility and our mobile first approach. Here’s a partial list:

  • By default, text-based form controls now receive only minimal styling. For focus colors and rounded corners, apply the .form-control class on the element to style.
  • Text-based form controls with the .form-control class applied are now 100% wide by default. Wrap inputs inside <div></div> to control input widths.
  • .badge no longer has contextual (-success,-primary,etc..) classes.
  • .btn must also use .btn-default to get the “default” button.
  • .container and .row are now fluid (percentage-based).
  • Images are no longer responsive by default. Use .img-responsive for fluid <img> size.
  • The icons, now .glyphicon, are now font based. Icons also require a base and icon class (e.g. .glyphicon .glyphicon-asterisk).
  • Typeahead has been dropped, in favor of using Twitter Typeahead.
  • Modal markup has changed significantly. The .modal-header, .modal-body, and .modal-footer sections are now wrapped in .modal-content and .modal-dialog for better mobile styling and behavior.
  • The HTML loaded by the remote modal option is now injected into the .modal instead of into the .modal-body. This allows you to also easily vary the header and footer of the modal, not just the modal body.
  • JavaScript events are namespaced. For example, to handle the modal “show” event, use 'show.bs.modal'. For tabs “shown” use 'shown.bs.tab', etc.

User Interface Design Basics and Fundamental Principles

User Interface Design Basics and Fundamental Principles

User Interface / UI Design focuses on what users might need to do and ensuring that the interface has elements that are easy to access, understand, and use to facilitate the actions.

UI is all about the concepts of interaction design, visual design, and information architecture.

Choosing Interface Elements

Users have become familiar with interface elements and acting in a certain way; So try to be consistent & predictable in your choices with the layout, Doing so will help with task completion, efficiency, and satisfaction.

Interface elements include but are not limited to:

  • Input Controls: buttons, text fields, checkboxes, radio buttons, dropdown lists, list boxes, toggles, date field
  • Navigational Components: breadcrumb, slider, search field, pagination, slider, tags, icons
  • Informational Components: tooltips, icons, progress bar, notifications, message boxes, modal windows
  • Containers: accordion

Best Practices for Designing an Interface

Everything stems from knowing your users, including understanding their goals, skills, preferences, and tendencies.  Once you know about your user, make sure to consider the following when designing your interface:

  • Keep the interface simple & Know your user: The best interfaces are almost invisible to the user. They avoid unnecessary elements and are clear in the language they use on labels and in messaging.
    Your user’s goals are your goals, so learn them. Restate them, repeat them. Then, learn about your user’s skills and experience, and what they need. Find out what interfaces they like and sit down and watch how they use them. Do not get carried away trying to keep up with the competition by mimicking trendy design styles or adding new features. By focusing on your user first, you will be able to create an interface that lets them achieve their goals.
  • Pay attention to patterns: Users spend the majority of their time on interfaces other than your own (Facebook, MySpace, Blogger, Bank of America, school/university, news websites, etc). There is no need to reinvent the wheel. Those interfaces may solve some of the same problems that users perceive within the one you are creating. By using familiar UI patterns, you will help your users feel at home.
  • Be consistent and use common UI elements: Users need consistency. They need to know that once they learn to do something, they will be able to do it again. By using common elements in your UI, users feel more comfortable and are able to get things done more quickly.  It is also important to create patterns in Language, layout, and design are just a few interface elements that need consistency throughout the site to help facilitate efficiency.
    A consistent interface enables your users to have a better understanding of how things will work, increasing their efficiency.
  • Be purposeful in page layout & Keep it simple:  Consider the spatial relationships between items on the page and structure the page based on importance. Careful placement of items can help draw attention to the most important pieces of information and can aid scanning and readability.
  • Strategically use color and texture: You can direct attention toward or redirect attention away from items using color, light, contrast, and texture to your advantage.
  • Use typography to create hierarchy and clarity: Carefully consider how you use typeface. Different sizes, fonts, and arrangement of the text to help increase scanability, legibility and readability.
  • Make sure that the system communicates what’s happening:  Always inform your users of location, actions, changes in state, or errors. The use of various UI elements to communicate status and, if necessary, next steps can reduce frustration for your user.
  • Think about the defaults: By carefully thinking about and anticipating the goals people bring to your site, you can create defaults that reduce the burden on the user.  This becomes particularly important when it comes to form design where you might have an opportunity to have some fields pre-chosen or filled out.

Understanding event handlers in JavaScript

Understanding event handlers in JavaScript

What is event handlers? Its very powerful and useful;

They are JavaScript code that are not added inside the <script> tags, but rather, inside the html tags, that execute JavaScript when something is triggered or called, such as pressing a button, moving your mouse over a link, submitting a form and so on.

The basic syntax of these event handlers is:

name_of_handler=”JavaScript code here”

For example:

<a href="http://www.prasadk.com" onClick="alert('Hi')">prasadk.com Home</a>

Click here to have a look prasadk.com Home

This is certainly unlike a regular JavaScript code, here we are inserting it directly inside a HTML tag, via the onClick event handler. When the above link is clicked, the user will first see an alert message before being taken to home / index page of http://www.prasadk.com.

Different event handlers with with different HTML tags. For example, while “onclick” can be inserted into most HTML tags to respond to that tag’s onclick action, something like “onload” only works inside the <body> and <img> tags.

Listed some of the most commonly used event handlers supported by JavaScript below:

 Event Handlers:

onclick: Use this to invoke JavaScript on clicking (a link, or form boxes)
onload: Use this to invoke JavaScript after the page or an image has finished loading.
onmouseover: Use this to invoke JavaScript if the mouse has been hovered on some link
onmouseout: Use this to invoke JavaScript if the mouse goes pass some link or gets triggered when mouse is taken out of link
onunload: Use this to invoke JavaScript right after someone leaves the page.

In OOP / Object Oriented Event Handlers in Javascript

By default, when an event occurs in javascript, the this reference in the handler function refers to the HTML element.
But what if we want the ‘this’ to refer to the class that houses our handler? We can use the bind()function – see below.

It works like this / snippet


Function.prototype.bind = function (obj) {
    var fn = this;
    return function () {
      var args = [this];

      for (var i = 0, ix = arguments.length; i < ix; i++) {
        args.push(arguments[i]);
      }
      return fn.apply(obj, args);
    }
  }

  function myClass() {
    this.name = "Member variable of myClass()!!";

    myClass.prototype.alertThis = function(el, e) {
      if (!e) var e = window.event;
      alert(this.name);   //we have access to our class object
      alert("id: " + el.id);       //we have access to the element that was clicked
      alert("id: " + e.target.id); //we have access to our event
    }.bind(this);

    var el = document.getElementById("myDiv");
    el.onclick=this.alertThis;
  }

  function onLoad() {
    window.c = new myClass();
  }

  if (window.addEventListener){
    window.addEventListener('load', onLoad, false); 
  } else if (window.attachEvent){
    window.attachEvent('onload', onLoad);
  }

 

Touch Event handlers for touch screen devices :

Some more event handlers are like touchstart, touchmove, touchend, touchcancel, tap, taphold, swipe, swipeleft, swiperight

snippet given below

function touchHandler(event) {
    var touch = event.changedTouches[0];

    var simulatedEvent = document.createEvent("MouseEvent");
        simulatedEvent.initMouseEvent({
        touchstart: "mousedown",
        touchmove: "mousemove",
        touchend: "mouseup"
    }[event.type], true, true, window, 1,
        touch.screenX, touch.screenY,
        touch.clientX, touch.clientY, false,
        false, false, false, 0, null);

    touch.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}

function init() {
    document.addEventListener("touchstart", touchHandler, true);
    document.addEventListener("touchmove", touchHandler, true);
    document.addEventListener("touchend", touchHandler, true);
    document.addEventListener("touchcancel", touchHandler, true);
}
$(document).ready(function(){
  init();
});

 

PN : while handling the touch event don’t forget to include jQuery, jQuery UI and jQuery mobile from cdn