Feb 9, 2015

Set up SSH for Git in Windows

Do the following to verify your installation:

Double-click the Git Bash icon to start a terminal session. Enter the following command to verify the SSH client is available:


$ ssh -v

If you have ssh installed, go to the next step. List the contents of your ~/.ssh directory.


$ ls -a ~/.ssh

If you have not used SSH on Bash you might see something like this:


rishi@rishi-PC ~
$ ls -a ~/.ssh
ls: /c/Users/rishi/.ssh: No such file or directory

If you have a default identity already, you'll see two id_* files:


rishi@rishi-PC ~
$ ls -a ~/.ssh
.    ..    id_rsa    id_rsa.pub

Enter ssh-keygen at the command line. The command prompts you for a file to save the key in:


ssh-keygen
ssh-agent /bin/bash
ssh-add ~/.ssh/id_rsa
ssh-add -l

In your terminal window, cat the contents of the public key file.


Image Source

Feb 6, 2015

How to add hash (#) link in Drupal (7.x) menu

Below is the code which shows how we can use the hash link, once it has been declared in our custom module.

Create a module with .info and .module extensions. In your .module extension, use the below mention code.
/**
 * Implements hook_menu().
 *
 * Defines a valid link to use when creating menu items.
 */
function MYMODULE_menu() {
  $items = array();
  $items['hash_link'] = array(
    'page callback' => 'drupal_not_found',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Implements hook_menu_link_alter().
 *
 * Flags the link to be altered at runtime.
 *
 * Note: Changes here would be saved back to the database.
 */
function MYMODULE_menu_link_alter(&$item, $menu) {
  if ($item['link_path'] == 'hash_link') {
    $item['options']['alter'] = TRUE;
  }
}

/**
 * Implements hook_translated_menu_link_alter().
 *
 * Refactors the link to go to the fragment #hash_link.
 */
function MYMODULE_translated_menu_link_alter(&$item, $map) {
  if ($item['link_path'] == 'hash_link') {
    $item['href'] = '';
    $item['localized_options']['fragment'] = 'hash_link';
  }
}
Once you have activated your module, go to your menu where you want to add the hash link, for instance I would like to add hash link in my main menu so I will access admin/structure/menu/manage/main-menu/add and there I will create a menu such as "About" with path as "hash_link"

Jun 17, 2014

How To Avoid Fieldset In Drupal Date Field

<?php
function MYTHEME_date_combo($variables) {
  return theme('form_element', $variables);
}
?>

Here 'MYTHEME' should be you theme name defined in you .info file placed inside your theme directory.

Apr 11, 2014

Getting Started With Graph Database Neo4j

What is Neo4j? Its a graph database.

What is a graph database?

A graph database is a database that uses graph structures with nodes, edges, and properties to represent and store data. A graph database is any storage system that provides index-free adjacency.This means that every element contains a direct pointer to its adjacent elements and no index lookups are necessary. General graph databases that can store any graph are distinct from specialized graph databases such as triplestores and network databases.WikiPedia

Why do I use it?

Its not a compulsion to use a graph db everytime, it depends on your projects schema and its relations. MySql gets weak in deep relations and graph db get stronger over here. Let me give you a simple example: Consider a social networking schema. I want a user from db who is a friend of my friends friend. This can be done using joins in mysql but it will take very long queries. But now if you use a graph db over here, it would be quick with a very small query. The reason to use a graph database is that the data stored by the system and the operations the system does with the data are exactly the weak spot of relational databases and are exactly the strong spot of graph databases. The system needs to store collections of objects that lack a fixed schema and are linked together by relationships. In graph db everything is represented by a node. If there are 10 users, then 10 nodes can be created. Users information can be stored in nodes property or in new nodes. Each node can be connected to other nodes and this linking is called as Relations. Now using this model its very easy to get a user who is a friend of my friends friend. Many popular websites uses graph database, facebook, linkedin, Cisco, HP, Accenture, Deutsche Telekom and many more.

Neo4j is a open source project developed by Neo Technology using JAVA. The developers describe Neo4j as "embedded, disk-based, fully transactional Java persistence engine that stores data structured in graphs rather than in tables". Neo4j is the most popular graph database.

Neo4j queries are built on Cypher language. Its really simple to learn.

Installation of neo4j is really simple.

So lets create a simple node in neo4j using cypher. After installation, just goto your browser at this URL http://localhost:7474/browser/ This will be the UI for executing neo4j queries.

CREATE (u:USER {uid:1})
Above code will create a simple node in Neo4j. Now lets see the node.
MATCH (u:USER {uid:1}) return u;
  Lets play around with nodes property. We will create few nodes
CREATE (u:USER {uid:1 , firstName:"Niraj", lastName:"Chauhan", gender:"Male"})
CREATE (u:USER {uid:2 , firstName:"Rishi", lastName:"Kulshreshtha", gender:"Male"})
CREATE (u:USER {uid:3 , firstName:"Leroy", lastName:"Bhavighar", gender:"Male"})
CREATE (u:USER {uid:4 , firstName:"Torrie", lastName:"Zacharia", gender:"Female"})
Lets see all nodes together
MATCH (u:USER) return u;

Now lets make some relation with nodes. Each relation needs a name. So I ll create a relation of friends.

MATCH (u1:USER{uid:1}),(u2:USER{uid:2}) CREATE (u1)-[:ARE_FRIENDS]->(u2);
MATCH (u2:USER{uid:2}),(u3:USER{uid:3}) CREATE (u2)-[:ARE_FRIENDS]->(u3);
MATCH (u3:USER{uid:3}),(u2:USER{uid:4}) CREATE (u3)-[:ARE_FRIENDS]->(u4);
So now I have made a simple relation of friends, Niraj has a friend Rishi has a friend Leroy has a friend Torrie. Lets get a user for Niraj who is female in third degree of friendship.
MATCH (niraj{firstName:"Niraj"})-[:ARE_FRIENDS*3..3]-(friend_of_friend)where friend_of_friend.gender = "Female" return friend_of_friend;

So the above query is simple, I selected as "Niraj" as my start and am looking for friends friends friend who is female. This was just a basic of Neo4j. Neo4j is really strong. I have used it in many projects, but only where its essential or in simple words schema with deep relations. You can learn more about queries of neo4j here: http://docs.neo4j.org/chunked/stable/cypher-query-lang.html

Apr 10, 2014

Output user profile picture programmatically in Drupal

Drupal is a wonderful platform to create complex websites in simpler way but sometimes, a simple task is too difficult to achieve in Drupal.
There are many pros of using Drupal in terms of other CMS available in market, such as its:

  • Extremely Flexible
  • Developer Friendly
  • Strong SEO
  • Capabilities Enterprise
  • Friendly Stability 

For instance lets take the example of user profile, if someone wants to show the user profile picture in Drupal then its a complicated task for him/her. Let me simply this for you in the below code. I've created the code in such a way if the user profile picture is not set, then it will show you the default profile pic.

Code:

global $user;
if ($user->uid) {
$user = user_load($user->uid);
print theme(
'image_style',
array(
'style_name' => 'thumbnail',
'path' => !empty($user->picture->uri)?$user->picture->uri:variable_get('user_picture_default'),
'attributes' => array(
'class' => 'avatar'
)
)
);
}
Cheers!
Photo Credit: Instagram

Nov 7, 2013

Truncate long text with CSS

Truncate Text CSS

While making websites we usually face width issues for long title text or headings. We can wrap that to next line or using some server side language we truncate it. But this can be done using CSS also.



 


 



[html]
<style type="text/css">
p {
width:170px;
margin:10px;
font-family:Arial;
font-size:14px;
}
p.truncate {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
<p title="I am a long text and I am wrapped to next line">I am a long text and I am wrapped to next line</p>
<p class="truncate" title="I am a long text and I am truncated">I am a long text and I am truncated</p>
[/html]

Demo:

Aug 14, 2013

Top 10 Inane Mistakes which WordPress Users Make

Wordpress
WordPress has touched our lives and how?! This uber simple blogging and content management platform is an apple of eye for anyone looking to mark an online presence. However, often we let ourselves go blind by the simplicity and SEO benefits of this platform, and do not consider various mistakes which we might actually by doing that are affecting the performance of the site. In this write up we aim to discuss 10 top inane mistakes which bloggers make, which may actually be lethal to the holistic health of their website or blog.

Please read ahead to discover these mistakes, and we hope you are not the one making them. But if you are, please try to nullify the same – either on your own, with our help being right in place or by consulting a professional.

Top 10 Inane Mistakes which WordPress Users Make

Still running the older version of WP?
We ask this with a tone of shocking incredibility. And if the answer is an affirmative, please tell us what exactly is wrong with you? Why do you hate your blog so much? There is an entire living, breathing, thriving community of WP developers who are working tirelessly to improve the CMS for you, so that you get to enjoy far superior and much improved features. Why would you decide against it? So please, just stop doing whatever you are doing and update your WP backend to the latest version. But wait, you might want to complete reading this post before you leave.


Painfully slow loading time
One of the biggest mistakes that every WordPress user is prone to committing is not paying due attention to the loading speed of the blog or site. Whether you are using too much of plugins, or you have just not optimized the page for better performance, please stop doing it and pay heed to the loading speed. This is more important now because Google has included the loading speed into its search engine algorithms, and you are more than certain to lose your Google rankings of you do not fix the loading speed NOW!


Please, no more “Just another WordPress blog”
Do yourself and all of us a favor and please use a theme which overrides the tagline that we have all grown so sick of. And if your blog does have this tagline, you should know you are just one amongst the ocean full of other users. You definitely would not want yourself or your blog to be remembered that way.


Bloating up deactivated plugins in the content folder of WP
You deactivat ed a plugin? Kick it out of your systems. As simple as that! Because not only do these plugins not serve any purpose to you, they also is bad for the performance of your blog or site. Hence, get over it already!

wp-plugins

A messed up Wp-Admin Section
If the admin section of your blog isn’t fine tuned, with no deactivated plugins and an updated version of each and everything, you are obviously doing the job as an admin wrong. Take a moment off and cleanse it, would you?


Blog posts of the length of the entire home page
So the home page of your blog looks longer than the Eiffel Tower, simply because it contains your recent blog updates in entirety? You know how backward that sounds? Unless of course if you have a specific reason behind doing it. If not, then please use the inbuilt ‘Read More’ section of WordPress to span the posts on the homepage accordingly. Besides, certain themes have the excerpts section to assist you with the same.


The white screen of death
As WordPress users, we all have experienced the white screen of death. Whether you have messed up your wp-config.php or there is some other complication with it, please do fix the issue ASAP. Trust us, no user will be interested in staring at your URL and a blank screen.

screen-of-death

Problems with database connections and gateways
Talking about what users are not so warmly going to react to, we come to another aspect, which surely does not rank high on the user’s popularity list anyway. It is getting a server down or installation error each time they visit your page. Thus, ensure that the database connections are right in place and there are no installation errors.


Indexing your site to private
It’s lethal! – One of the perks of WordPress is that it allows the users to own a site and blog simultaneously. And how users misuse this privilege is by indexing the site to private after owning a blog, thinking that blog will take care of all the SEO and site would rather enjoy an elite attention – or whatever the thought process is, we are not really discussing that. What we are pointing out at is that don’t! Don’t do this to your site and to your blog as by opting for this option, you would put the noindex tag on each of your web pages. You don’t really want the traffic to fall to a zero, do you?


Making your server information visible
You were wondering why your WP blog or website gets hacked ever so often? The hackers with their wonderful notorious minds obviously are going to target you, if you provide them with all the PHP information or the info about the current version of WP that you are running. To check the same, visit yoursite.com/phpinfor.php or yoursite.com/readme.html. Got the point, right? Instead opt for professional WordPress development services, and get a secured and well optimized WP blog or site.
This brings us to an end of this post. We hope that we were helpful in letting you fix some of the major performance and security blunders that may have previously existed in your blog. Also, please do consider opting for professional services, should you feel stuck up with the same at any moment.





About Auhtor

John Pitt is a blogging junkie and also a developer working with an
Offshore WordPress Development
company. You can often find him either thinking about his next blog posts or ganging up with his fellow WordPress Developers. For your project you may
hire WordPress developers
and avail the expert services provided by them.

May 1, 2013

jQuery Context Menu


In this tutorial I am sharing my newly created jQuery Plugin, jQuery Simple Context Menu.


jQuery Simple Context Menu


GITHUB REPO :
https://github.com/nirajmchauhan/jquery-simple-context-menu




Currently this plugin accepts two paramenters:

  • Custom HTML - You have to give entire HTML code with proper attributes in it wrapped inside ul


  • Simple HTML - You have to pass href link and the text to be shown.



Simple HTML usage
Include the jquery file, you can download this from github.


[js]

jQuery(function($){
$(document).ready(function(){

$('#Simple').simpleContextMenu({
options : {
'Home' : '#',
'About Us' : '#',
'Services' : '#',
'Contact Us' : '#'
}
});

});
});

[/js]



Inside options you need to pass text and the link, the above code will generate a HTML in following format :


[html]
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About Us</a>
</li>
<li>
<a href="#">Services</a>
</li>
<li>
<a href="#">Contact Us</a>
</li>
</ul>
[/html]



Custom HTML usage


[js]

jQuery(function($){
$(document).ready(function(){

$('#CustomHTML').simpleContextMenu({
html: '<div class="dropdown clearfix"><ul style="display: block; position: static; margin-bottom: 5px; *width: 180px;" aria-labelledby="dropdownMenu" role="menu" class="dropdown-menu"><li><a href="#" tabindex="-1">Action</a></li><li><a href="#" tabindex="-1">Another action</a></li><li><a href="#" tabindex="-1">Something else here</a></li><li class="divider"></li><li><a href="#" tabindex="-1">Separated link</a></li></ul></div>'
});

});
});

[/js]



Inside html you need to pass entire html which will be the context menu. Above I am using bootstrap.




Both parameters cannot be used together, use only one at a time. You can have multiple context menus on a single page. Check out the demo and fork me.

Mar 25, 2013

How To Make A Chat Program In Node JS

Today we will start with NodeJS.


NodeJS

So what is NodeJS?


In simple terms, JavaScript on server side. NodeJS uses Googles V8 engine. Its basically a javascript library which is executed on server side. Its also known as JavaScript without browser.


When and why to use nodejs?


Choosing a technology depends on the developer who is going to take it ahead. NodeJS is very simple, you just need to know javascript. NodeJS can be used for online gaming, chat programming, CRM management and also for blogging. There are several plugins available which make your job easy.



So today lets start with a simple chat program.



Installing NodeJS on Windows




First download the latest copy of nodejs from here. After installation open cmd and just type node -v. This will output you the current installed version of nodejs.




Now create a folder on desktop, name it as node-chat, using cmd navigate to that directory. Now inside that folder create a file package.json. This file contains all the dependencies and other plugin information. Paste below code inside it:



[js]
{
"name": "node_chat",
"version": "1.0.0-4",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"dependencies": {
"socket.io": "0.9.11",
"connect": "2.7.1"
},
"author": "Niraj Chauhan",
"license": "BSD",
"subdomain": "node-chat",
"engines": {
"node": "0.6"
}
}
[/js]

Above json is simple, it takes few parameters like name of author, filename which is going to be executed first, dependencies etc.



Now in cmd just type npm install. This will install all required dependencies which are mentioned inside the json file.



After above command if you check the folder, it consists with a new folder named as node_modules This ensures that all the important modules are installed.



Create a file app.js and paste the below code in it.


[js]
var io = require('socket.io'),
connect = require('connect'),
url = require('url'),
sys = require('sys'),
http = require('http'),
fs = require('fs');

var port = 3000;


var app = connect().use(connect.static('public')).listen(port);
var chat_room = io.listen(app);
console.log('Listening to port ' + port);

chat_room.sockets.on('connection', function (socket) {
socket.emit('entrance', {
message: 'Welcome to the chat room!'
});

socket.on('disconnect', function () {
chat_room.sockets.emit('exit', {
message: 'A chatter has disconnected.'
});
});

socket.on('chat', function (data) {
message = {
user: data.message.user,
message: data.message.message
};
chat_room.sockets.emit('chat', {
message: message
});
});

chat_room.sockets.emit('entrance', {
message: 'A new chatter is online.'
});
});
[/js]

If you have worked with server side technology like php, java etc then you ll understand the basic from above. Firstly we have included some modules which we will need. We will be using socket.io to make a flawless connection between server and client. We will also be using connect


Connect offers a createServer method, which returns an object that inherits an extended version of http.Server. Connect's extensions are mainly there to make it easy to plug in middleware. That's why Connect describes itself as a "middleware framework," and is often analogized to Ruby's Rack.

After including required files we listen to a port which redirects to a folder public and finally we open the socket after successful connection between server and client.


Using opened socket variable, we define different methods inside the connection function.




  • entrance: Used when a socket connection established between server and client

  • disconnect: Used when a client breaks the connection

  • chat: Used to transfer messages between different clients via server.



So now lets create a foder and name it to public. This folder will contain all the UI html and css files. Here I ll be using twitter bootstrap.



So by now your folder structure should be something like this:




node-chat/
|--node_modules/
|--public/
|----css/
|----img/
|----js/
|----index.html
|--app.js
|--package.json



Inside your index.html file paste the below code


[js]
<script src="js/jquery-1.7.2.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script type="text/javascript" charset="utf-8">
var socket = io.connect('ws://localhost:3000/');
var user = {
name: ''
}
jQuery(document).ready(function() {

jQuery('#chat_box').keypress(function(event) {
if (event.which == 13) {
socket.emit('chat', {
message: {
user: user.name,
message: jQuery('#chat_box').val()
}
});
jQuery('#chat_box').val('');
}
});

});

function startChat() {
user.name = $('#username').val();

var log_chat_message = function(message, type) {

if (type == 'chat') {
var li = jQuery('<li />').html('<span>' + message.user + '</span>: ' + message.message);
} else {
var li = jQuery('<li />').html('<span>' + message + '</span>');
}


jQuery('#chat_log').append(li);
};

if (user.name != '') {
$('#loginDiv').fadeOut();
$('#chat').fadeIn();

socket.on('chat', function(data) {
log_chat_message(data.message, 'chat');
});

socket.on('entrance', function(data) {
log_chat_message(data.message, 'system');
});

socket.on('exit', function(data) {
log_chat_message(data.message, 'system');
});

} else {
alert('Please enter your username');
}
}
</script>
[/js]


Above code is simple jquery, which contains some functions for chatting, login, printing message etc. So quickly I ll explain you the important part of chat.




When user opens the page, we call the socket file, this file is installed inside modules using the json file. Then first we open a socket connection between server and user. This triggers the app.js file and entire connection is established. Then by using the functions of connection which is declared inside app.js file(chat, entrance, exit) we call those functions from here. Each function passes and takes some message. Using chat we take message from user who typed, passed it to server, server takes that message and throws to all user within the socket connection.



To execute this chat, just run this command in cmd within the directory where app.js file exists node app.js, then in browser navigate to http://localhost:3000/


You can check the working demo and download the files. I have just covered the important flow of the code and how nodejs and sockets can be helpful. This chat works in almost all browsers and devices, this is the plus point of using sockets via nodejs

Dec 15, 2012

Website content management system – what is it all about?

CMS or the Content management system, in simple words can be explained as PC
software that helps you to amend, alter, make public and maintain the contents from
the central interface end. Initially CMS was designed with the purpose of simplifying
the complex task of writing codes of various versions and to ease up the development
process more flexible and handy. This type of software helps to manage system that
controls and manages the complete content with the help of a workflow procedure
including a collaborative environment.


CMS


CMS helps to centralize data edit, publish and modify at the single back end interface.
This web CMS technique is best used to be in charge of active set of web materials that
are made available online such as websites, media files and document.


Different types of CMS


We have three major types of Content Management System (CMS) namely, online
processing, offline processing and hybrid systems. These processes are being used
in the implementation procedure to describe the deployment pattern for Web CMS via
presentation templates that provide a structural content pattern for your web page.


Online processing system is all about implementing templates requisite condition.
Usually a web page HTML is being generated during a visitor’s entry or when the
page is being pulled off from web cache. It is known that most of the open source web
content management system has the capability to support add-ons that offers the
required support including blogs, forums, web stores, etc. It’s being referred to as add-
ons, widgets, modules, or extensions with open source of paid license model.


Offline processing system is something that is also termed as static site generators.
Pre-process all the content by implementing the right templates ahead of issuing to
generate your web pages. As pre-processing system does not call for server to make
use of the templates at the right time, they subsist as design-time tools.


Hybrid systems
There are systems where both online and offline techniques are being implemented.
Some systems write their exec codes to move on with dynamic HTML condition where
CMS is not deployed on all servers. While the other types of Hydrid systems are either
offline or online base on the functionality.

Nov 20, 2012

jQuery Form Validation Plugin

If you are developing websites then you will come across Form validation. I too and I was using jQuery Validation plugin. This is an awesome plugin but really buggy in IE7/8 browser with different jQuery versions. Its not stable and the developer of this plugin is not looking after the bugs. I reported several times but no response. So finally I decided to make my own validation plugin.

Before I start further let me tell you that currently this plugin only validates INPUT types with number, email and blank value fields. Its still in beta or under development mode.

GITHUB REPO : https://github.com/nirajmchauhan/jQuery-form-validation





Form-Validation



I ll explain you the usage of this plugin by a simple form example



HTML:



[html]
<section>
<form method="post" class="form-horizontal" id="loginForm" onsubmit="return false;">
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<input type="text" id="inputEmail" name="user" placeholder="Email" class="required email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<input type="password" id="inputPassword" name="password" class="required" placeholder="Password">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox"> Remember me
</label>
<button id="submit" type="submit" class="btn" onclick="javascript:ajaxThrow('#loginForm','#response');">Sign in</button>



</div>
</div>
<div class="alert alert-info" id="response"></div>
</form>
</section>
[/html]




To make a field mandatory, you need to add a class required.
Currently on input types will be accepted so to make if mandatory, use the following attributes :


















class Output
class="required email" This will check for blank field and whether the value is EMAIL ID
class="required number" This will check for blank field and whether the value is a NUMBER
class="required" This field will check for blank values


So now the final is the jQuery:



JS:


[js]
jQuery(function($) {
$(document).ready(function() {

$('#submit').click(function() {
val = $('#loginForm :input').validateForm();
if (val) {
var qstring = $('#loginForm').serialize();
$('#response').fadeIn().html('Form Validated successfully with following fields<br>' + qstring);
}
});

});
});
[/js]




To validate the form, you ll just need to add a line :
val = $('#loginForm :input').validateForm();

This will return a boolean value. And will also add a class error to the respective input field.

Check this in action here :





Oct 4, 2012

iPhone 5 Will Cost You at Least $1,800

You might have heard that

Buy an iPhone 5 From $199
Buy online and get free shipping.
Or visit your favorite Apple Retail Store.

Here's the Info-graphic which shows that iPhone 5 Can Cost You at Least $1,800!


iPhone 5 Infographic

Aug 27, 2012

JQuery Treeview List

JQuery Treeview List - Creates a nice expanding and collapsing tree view control using jQuery.

JQuery Treeview List

Tree view Displays a hierarchical collection of labeled items, each represented by a TreeNode. This you'll normally see in windows or MAC folder navigation.

Today I am making it in JQuery for ul, li list.



Basic HTML Markup


[html]
<ul>
<li><a>First Level</a>
<ul>
<li><a>Second Level</a></li>
<li><a>Second Level</a></li>
<li><a>Second Level</a></li>
</ul>
</li>
<li><a>First Level</a>
<ul>
<li><a>Second Level</a>
<ul>
<li><a>Third Level</a></li>
<li><a>Third Level</a></li>
<li><a>Third Level</a>
<ul>
<li><a>Fourth Level</a></li>
<li><a>Fourth Level</a></li>
<li><a>Fourth Level</a>
<ul>
<li><a>Fifth Level</a></li>
<li><a>Fifth Level</a></li>
<li><a>Fifth Level</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a>Second Level</a></li>
</ul>
</li>
<li><a>First Level</a>
<ul>
<li><a>Second Level</a></li>
<li><a>Second Level</a></li>
</ul>
</li>
</ul>
[/html]

We just created a normal list formation in hierarchical way.



Now lets add some styling - CSS


[css]
.tree {
-moz-border-bottom-colors: none;
-moz-border-image: none;
-moz-border-left-colors: none;
-moz-border-right-colors: none;
-moz-border-top-colors: none;
background: -moz-linear-gradient(center top , #E3E3E3, #FFFFFF 85px) repeat scroll 0 0 transparent;
border-color: #BFC0C2 #BFC0C2 #B6B7BA;
border-radius: 3px 3px 3px 3px;
border-style: solid;
border-width: 1px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.17), 0 -2px 0 rgba(0, 0, 0, 0.08) inset;
display: inline-block;
margin: 0 0 50px;
min-width: 300px;
padding: 10px 15px 15px;
}
.tree ul {
list-style: none outside none;
}
.tree li a {
line-height: 25px;
}
.tree > ul > li > a {
color: #3B4C56;
display: block;
font-weight: normal;
position: relative;
text-decoration: none;
}
.tree li.parent > a {
padding: 0 0 0 28px;
}
.tree li.parent > a:before {
background-image: url("../images/plus_minus_icons.png");
background-position: 25px center;
content: "";
display: block;
height: 21px;
left: 0;
position: absolute;
top: 2px;
vertical-align: middle;
width: 23px;
}
.tree ul li.active > a:before {
background-position: 0 center;
}
.tree ul li ul {
border-left: 1px solid #D9DADB;
display: none;
margin: 0 0 0 12px;
overflow: hidden;
padding: 0 0 0 25px;
}
.tree ul li ul li {
position: relative;
}
.tree ul li ul li:before {
border-bottom: 1px dashed #E2E2E3;
content: "";
left: -20px;
position: absolute;
top: 12px;
width: 15px;
}
[/css]


In css we are making tree nodes usinf :before

Last we will add jquery functionality to toggle the list on click events.



JQuery


[js]
$('.tree li').each(function(){
if($(this).children('ul').length > 0){
$(this).addClass('parent');
}
});

$('.tree li.parent > a').click(function(){
$(this).parent().toggleClass('active');
$(this).parent().children('ul').slideToggle('fast');
});
[/js]

Here first we search for all parent nodes and if found then we are adding a class named as .parent

Then on click of any parent elements, we just add a class .active and slide the li's in it.

This can be used to show the navigation of the website.

Aug 23, 2012

Collection of Special iPhone Meta Tags

I am not an iPhone developer nor a user but just found some special meta tags for developing iPhone webapps and iPhone prove websites. Hope this helps you.
 
Disable horizontal scrolling


[html]
<meta name="viewport" content="width=device-width, user-scalable=no" />
[/html]


  
When bookmarked the website runs in fullscreen, like a normal App.


[html]
<meta name="apple-mobile-web-app-capable" content="yes" />
[/html]


  
When bookmarked as fullscreen, set the color of the status bar


[html]
<meta name="apple-mobile-web-app-status-bar-style" content="black">
[/html]


  
When bookmarked, add an 57x57 Icon and the iPhone will add the shiny effect itself.


[html]
<link rel="apple-touch-icon" href="icon.png" />
[/html]


  
Prefer non glossy Icon or made the gloss yourself? Precomposed stops from adding the gloss on bookmarks


[html]
<link rel="apple-touch-icon-precomposed" href="icon" />
[/html]


  
Remove auto-recognition of Phone numbers


[html]
<meta name="format-detection" content="telephone=no">
[/html]


  
Forces the iPhone to use a number pad


[html]
<input type="number">
[/html]


  
Guess what? A phone number keypad


[html]
<input type="tel">
[/html]


  
Keyboard optimized for typing urls.


[html]
<input type="url">
[/html]


 

Credits : Robert

Aug 16, 2012

Forrst Invites Giveaway | CLOSED

Forrst.com A website for designers and also for developers. Here you will find a great resource of Web Development. Its a community where a developer and designers improve thier craft. Its just a invite based website so that only real people enter it.

Forrst

So you want it???? Then

  • Comment your latest or best work below with your actual EMAIL ID(Design or Development or both - Mandatory)

  • Share this post on twitter and other social sites(Advantage)


And just wait for results. I have total 2 invites so hurry up!!!

Results will be announced on 22 Aug 2012

 




We have selected two winners. TRAVIS and SUMON SELEEM Congratulations and welcome to forrst

Aug 8, 2012

Wordpress Bloginfo Shortcode

A small snippet for Wordpress Bloginfo. This will help you to add images directly without giving the entire path. Its a shortcode snippet

[php]
function get_bloginfo_shortcode( $atts ) {
extract(shortcode_atts(array(
'info' => '',
), $atts));
return get_bloginfo($info);
}
add_shortcode('bloginfo', 'get_bloginfo_shortcode');
[/php]

Usage :

[html]
<img src="[bloginfo info='template_url']/images/logo.jpg" alt="[bloginfo info='name'] logo" />
[/html]

Now you can easily call your images without giving actual path.

Credits Forrst

Aug 2, 2012

CSS3 Visiting Card 3D Transform

My friend Asif made a nice design on visiting card, so I decided to convert that into a 3D flipping Visiting Card

CSS3 Visiting Card

To rotate a div with 3D transform :-

  • transform-style: preserve-3d;

  • perspective: 800px;

  • transform: rotateY(180deg);

  • backface-visibility: hidden;


After setting the above CSS a div will transform.




Final Product

Visiting Card Front-Back

Visiting Card Back-Front




So lets start




[html]
<div id="card">
<div class="front">
<div class="strips">
<p class="strip red"></p>
<p class="strip orange"></p>
<p class="strip green"></p>
<p class="strip blue"></p>
<p class="strip lOrange"></p>
</div>
<div class="businessName">
Webs Tutorial
</div>
</div>
<div class="back">
<div class="strips">
<p class="strip red"><span>www.webstutorial.com</span></p>
<p class="strip orange"><span>Mumbai, India</span></p>
<p class="strip green"></p>
<p class="strip blue"><span>PHP, HTML5, CSS3</span></p>
<p class="strip lOrange"><span>niraj@webstutorial.com</span></p>
</div>
<div class="myName">
<p>Niraj Chauhan</p>
Developer
</div>
</div>
</div>
[/html]




Above we made a parent div and inside that two divs, one will be the front side and another will be the backside. When we :hover on the front facing div, it rotates in Y axis. As we have set the transform style to preserve-3d it will maintain its view and the transform will be displayed in 3D.




[css]
@font-face {
font-family: roboto;
src: url('../Roboto-Regular.ttf');
}

* {
font-family: roboto !important;
}

.container {
position: relative;
}

#card {
position: absolute;
z-index: 11;
-webkit-perspective: 800px;

-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
-ms-transform-style: preserve-3d;
transform-style: preserve-3d;
left: 30%;
}

#card .front,#card .back {
background: #000;
width: 480px;
height: 205px;
display: block;
position: absolute;
color: #fff;
border-radius: 8px;

-webkit-transition: -webkit-transform 1s ease-in-out;
-moz-transition: -moz-transform 1s ease-in-out;
-o-transition: -o-transform 1s ease-in-out;
-ms-transition: -ms-transform 1s ease-in-out;
transition: transform 1s ease-in-out;
}

#card .front {
-webkit-transform: rotateY(0deg);
-moz-transform: rotateY(0deg);
-o-transform: rotateY(0deg);
-ms-transform: rotateY(0deg);
transform: rotateY(0deg);
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
z-index: 13;
}

#card:hover .front {
-webkit-transform: rotateY(180deg);
-moz-transform: rotateY(180deg);
-o-transform: rotateY(180deg);
-ms-transform: rotateY(180deg);
transform: rotateY(180deg);
}

#card .back {
-webkit-transform: rotateY(-180deg);
-moz-transform: rotateY(-180deg);
-o-transform: rotateY(-180deg);
-ms-transform: rotateY(-180deg);
transform: rotateY(-180deg);
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
z-index: 12;
background: #000;
}

#card:hover .back {
-webkit-transform: rotateY(0deg);
-moz-transform: rotateY(0deg);
-o-transform: rotateY(0deg);
-ms-transform: rotateY(0deg);
transform: rotateY(0deg);
z-index: 14;
}

/* Front Strips */
.strips {
clear: both;
margin: 0 auto;
position: relative;
width: 125px;
}

.strip {
float: left;
height: 140px;
margin-right: 12px;
position: relative;
width: 12px;
font-family: roboto;
}

.red {
background: #b70000;
color: #b70000;
border: 1px solid #890000;
border-top: 0px;
}

.orange {
background: #f25d07;
color: #f25d07;
border: 1px solid #b64605;
border-top: 0px;
}

.green {
background: #a69e33;
color: #a69e33;
border: 1px solid #837726;
border-top: 0px;
}

.blue {
background: #0092b2;
color: #0092b2;
border: 1px solid #006e86;
border-top: 0px;
}

.lOrange {
background: #ee913f;
color: #ee913f;
margin: 0 !important;
border: 1px solid #b36d2f;
border-top: 0px;
}

.businessName {
clear: both;
font-family: roboto;
font-size: 22px;
padding: 5px 0 0;
text-align: center;
}

/* Back strips */
.back .red {
height: 70px;
}

.back .orange {
height: 100px;
}

.back .green {
height: 140px;
}

.back .blue {
height: 100px;
}

.back .lOrange {
height: 70px;
}

.strip span {
position: absolute;
font-size: 15px;
}

.red span {
left: -162px;
top: 50px;
}

.orange span {
left: -102px;
top: 80px;
width: 100px;
}

.green span {
left: 0;
}

.blue span {
left: 20px;
top: 80px;
width: 140px;
}

.lOrange span {
left: 18px;
top: 50px;
}

.myName {
clear: both;
color: #999999;
font-family: roboto;
font-size: 20px;
padding: 0;
text-align: center;
}

.myName p {
color: #a69e33;
}

#designedBy {
border-radius: 5px 0 0 0;
bottom: 0;
color: #FFFFFF;
min-height: 10px !important;
padding: 10px;
position: fixed;
right: 0;
}
[/css]




Now in CSS we set the backface-visibility: hidden;. With this property the backside of the card will be hidden. When we hover on the front face of the card with the help of css transition we flip the card and now the backside of the card will be visible.

When we move away over mouse from the card it turns back to its original position.This way a 3D flip can be done using CSS3.

Now the latest Firefox also supports the 3D Transform. Previously it was only working on webkit browsers

Jul 25, 2012

AJAX Contact Form With Validation

Today I am going to share a simple tutorial on How to make a AJAX contact form with validation.

JQUERY-AJAX



What is AJAX?
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.


The flow of the form is :


AJAX Process Diagram

So here I am using twitter bootstrap, so files which we need are :-

  • data.php - (here we will write our PHP code)

  • script.js - (here we will write our ajax jquery code)

  • validate.js - (jqueryvalidation plugin)

  • index.php and style.css



So the fields of our form will be Name, Email, Number, City, Area, Message, Submit

Here our city and area will also be using AJAX i.e. on city change area will also be changed.

index.php


[html]
<?php require_once('data.php'); ?>
<div class="hero-unit">
<h2>Contact Us</h2>

<form id="contactUs" name="contactUs" onsubmit="return false;">


<table cellspacing="5" cellpadding="5">
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" value="" name="name" id="name" class="required name"/></td>
</tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="text" value="" name="email" id="email" class="required email"/></td>
</tr>
<tr>
<td><label for="number">Contact Number:</label></td>
<td><input type="text" value="" name="number" id="number" class="required number" minlength="8"/></td>
</tr>
<tr>
<td><label for="city">City:</label></td>
<td>
<select id="city" name="city" onchange="javascript:changeArea('#city', '#area');">
<option value="Any">Any</option>
<?php echo getCities();?>
</select>
</td>
</tr>
<tr>
<td><label for="area">Area:</label></td>
<td><select id="area" name="area" disabled="disabled"></select></td>
</tr>
<tr>
<td><label for="message">Message:</label></td>
<td><textarea id="message" name="message" class="required"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="hidden" name="contactFormSubmit" value="Yes" />
<input type="submit" value="Submit" class="btn" onclick="javascript:formSubmit('#contactUs','#responseText');"/>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<div id="responseText"></div>
</td>
</tr>

</form>
</div>
[/html]



Here we just made a simple html structure of form inside a table.

To make a field mandatory, just add class="required" to input.

If you want to validate it with only email or number then add class="required email" or class="required number"

If I add a attribute minlength="8" to the number field then that field should contain at least 8 digits of number.

data.php


[php]
<?php
$cities = array('1'=>'Mumbai',
'2'=>'Chennai',
'3'=>'Noida',
'4'=>'Bangalore');

$areas = array( 'Airoli' => '1',
'Andheri' => '1',
'Bandra' => '1',
'Bhandup' => '1',
'Bhayandar' => '1',
'Boisar' => '1',
'Borivali' => '1',
'Chembur' => '1',
'Gopalapuram' => '2',
'Mount Road' => '2',
'Noida Expressway' => '3',
'Sector 1' => '3',
' Sector 128' => '3',
'Sector 129' => '3',
'Yamuna Expressway' => '3',
'Anekal ' => '4',
'Banashankari ' => '4',
'Banasvadi ' => '4',
'Banaswadi ' => '4',
'Begur ' => '4',
'Bellary Road ' => '4',
'Dobespet ' => '4',
'Electronics City' => '4');


if(isset($_REQUEST['cityID']) && $_REQUEST['cityID'] != 'Any'){

getAreas($_REQUEST['cityID']);

}

if(isset($_REQUEST['contactFormSubmit'])){
if(!isValidEmail($_REQUEST['email'])){
echo 'Enter a valid email ID';
}elseif(!is_mobileNumber($_REQUEST['number'])){
echo 'Enter a valid number';
}elseif($_REQUEST['name'] == '' || $_REQUEST['message'] == ''){
echo 'Enter valid name or message';
}else{
?>
<p><b>Thank you for contacting us, your given information : </b></p>
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td>Name:</td>
<td><?php echo $_REQUEST['name']?></td>
</tr>
<tr>
<td>Email:</td>
<td><?php echo $_REQUEST['email']?></td>
</tr>
<tr>
<td>Contact Number:</td>
<td><?php echo $_REQUEST['number']?></td>
</tr>
<tr>
<td>City:</td>
<td><?php echo $_REQUEST['city']?></td>
</tr>

<?php if(isset($_REQUEST['area'])) : ?>
<tr>
<td>Area:</td>
<td><?php echo $_REQUEST['area']?></td>
</tr>
<?php endif; ?>

<tr>
<td>Message:</td>
<td><?php echo $_REQUEST['message']?></td>
</tr>
</table>
<?php
}
}



function getCities(){
global $cities;
foreach($cities as $Idx => $city){

echo '<option value="'.$Idx.'">'.$city.'</option>';

}
}

function getAreas($cityID = ''){
global $areas;
foreach($areas as $area => $Idx){

if($Idx == $cityID){

echo '<option value="'.$Idx.'">'.$area.'</option>';

}

}
}

function isValidEmail($email){
return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
}

function is_mobileNumber($mobile) {
$regex1 = '123456789';
$regex2 = '1234567890';
$regex3 = '0123456789';

if(preg_match('/^([0-9])\1*$/', $mobile)){
return false;
}elseif($mobile == $regex1){
return false;
}elseif($mobile == $regex2){
return false;
}elseif($mobile == $regex3){
return false;
}elseif(preg_match("/[^0-9]/", $mobile)){
return false;
}else{
return true;
}
}
?>
[/php]



PHP code is simple, I am making an array of cities and area, made 2 functions to get areas and cities and getting the parameters from URL and passing it to functions.

Now the ajax function :

script.js


[js]
function changeArea(cityBox, areaBox) {
jQuery(function($) {

$(areaBox).attr('disabled','disabled');

$(areaBox).addClass('loading');
$.ajax({ //Starting the AJAX
url : 'data.php', //File to be called or pass the data
data : { //Extra paramters
"cityID" : $(cityBox+' option:selected').attr('value')
},
success : function(data) { // The result from data.php file comes as data
window.setTimeout(function(){
$(areaBox).removeAttr('disabled');

$(areaBox).removeClass('loading');

$(areaBox).html('');

$(areaBox).html(data);

}, 2000);
}
});
});
}
[/js]



The above function is is taking two parameters, the select id of City and area. Then I am saving the value of city in a variable, and inside ajax I am passing the value of city to data.php file.

Inside data.php I wrote a function to return areas according to the city ID. Inside success function I am inserting entire result into the area select box.

Simlarly I am going to make another function which will validate the form and if no error then ajax is called and mail is sent.

script.js


[js]
/* Submission of form */

function formSubmit(formID, displayMssgID) {
jQuery(function($) {

var qstring = $(formID).serialize();

var val = $(formID).validate().form();
if (val) {
$(displayMssgID).html('Registering your Request ... Please Wait ...');
$.ajax( {
url : "data.php",
data : qstring,
success : function(data) {

$(displayMssgID).html('');
$(displayMssgID).html(data);
window.setTimeout(function() {

$(displayMssgID).fadeOut();

}, 6000);

}
});
}
});
}
[/js]



This function takes two parameters, ID of the form and result message div. First I am serializing the form, which will take all the form data and store it in a variable. Then I am validating it, if validation is true then our AJAX is called and entire form data is passed to data.php file.

This is return will give some output which I am showing it in id="responseText"

This is a simple way to make AJAX forms, there might be many other tutorials on other websites but I find this very simple. This way you can make any AJAX form. Try out the demo.



Thanks to Jacob for server validation tip.

Jul 18, 2012

JQuery Allow Only Numbers

For a frontend developer when it is asked to do something unique that person will think of JQuery first. Today a simple jquery code to allow only numbers to a text-box. Below code will allow following key events :


  • Backspace

  • Delete

  • Tab

  • Escape

  • Enter

  • Ctrl+A

  • Home

  • end

  • left

  • right



Just add a class to textbox .onlyNumbers and paste the following jquery code :



[js]
$(document).ready(function() {

$(".onlyNumbers").keydown(function(event) {

if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || (event.keyCode == 65 && event.ctrlKey === true) || (event.keyCode >= 35 && event.keyCode <= 39)) {
return;
}
else {

if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
event.preventDefault();
}
}
});

});
[/js]



You can also apply this to textarea.

Demo: