Hi! Welcome...

Protech Mate Sdn Bhd hi, my name is ilyas. i am a web developer. i found myself spend too much time in front of computer & couldn\'t get home when my code still producing errors. here is my collection, thoughts & findings on the internet.

26 July 2010 ~ 0 Comments

Top 3 jQuery Tips for Beginners

a very useful tips, taken from: http://www.bloggingdeveloper.com/post/Top-3-jQuery-Tips-for-Beginners.aspx

Hot Tip #1: Access Elements by Javascript Array Indexing

Application of a selector creates a Javascript array which can be used for accessing DOM elements with array index easily.

For Example:

var element = $("img")[2];

will set the variable element to the second img element in the matched set of document’s all img elements.

Hot Tip #2: Create Union of Elements with Multiple Selectors

Union of multiple selectors can be created by listing selectors separated by commas ‘n a s’ngle call to $()

For Example:

$("img,p")

will match all IMG and P elements, while the following matches all DIV elements with a title attribute and all IMG elements with alt attributes.

$("div[title],img[alt]")

Hot Tip #3: Be Careful with not() and remove() methods!

.not() method removes elements from the matched set while the .remove() method removes the elements in the matched set from the HTML DOM.

07 June 2010 ~ 0 Comments

Improve your jQuery – 25 excellent tips

this is a nice collection taken from http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx

Introduction

jQuery is awesome. I’ve been using it for about a year now and although I was impressed to begin with I’m liking it more and more the longer I use it and the more I find out about it’s inner workings.

I’m no jQuery expert. I don’t claim to be, so if there are mistakes in this article then feel free to correct me or make suggestions for improvements.

I’d call myself an “intermediate” jQuery user and I thought some others out there could benefit from all the little tips, tricks and techniques I’ve learned over the past year. The article also ended up being a lot longer than I thought it was going to be so I’ll start with a table of contents so you can skip to the bits you’re interested in.

Table of Contents

1. Load the framework from Google Code

Google have been hosting several JavaScript libraries for a while now on Google Code and there are several advantages to loading it from them instead of from your server. It saves on bandwidth, it’ll load very quickly from Google’s CDN and most importantly it’ll already be cached if the user has visited a site which delivers it from Google Code.

This makes a lot of sense. How many sites out there are serving up identical copies of jQuery that aren’t getting cached? It’s easy to do too…

<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">

    // Load jQuery
    google.load("jquery", "1.2.6");

    google.setOnLoadCallback(function() {
        // Your code goes here.
    });

</script>

Or, you can just include a direct reference like this…

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>

Full instructions here

2. Use a cheat sheet

Not just a jQuery tip, there are some great cheat sheets out there for most languages. It’s handy having every function on a printable A4 sheet for reference and luckily these guys have produced a couple of nice ones..

http://www.gscottolson.com/weblog/2008/01/11/jquery-cheat-sheet/

http://colorcharge.com/jquery/

3. Combine all your scripts and minify them

OK, a general JavaScript tip here. But any big project that uses lots of jQuery probably uses lots of plugins (this site uses easing, localScroll, lightbox and preload) so it’s usually applicable.

Browsers can’t load scripts concurrently (well, most can’t, yet), which means that if you’ve got several scripts downloading one at a time then you’re really slowing down the loading of your page. So, assuming the scrips are being loaded on every page then you should consider combining them into one long script before deploying.

Some of the plugins will already be minified, but you should consider packing your scripts and any that aren’t already. It only takes a few seconds. I’m personally a fan of Packer by Dean Edwards

4. Use Firebug’s excellent console logging facilities

If you haven’t already installed Firebug then you really should. Aside from many other useful features such as allowing you to inspect http traffic and find problems with your CSS it has excellent logging commands that allow you to easily debug your scripts.

Here’s a full explanation of all of it’s features

My favourite features are “console.info”, which you can use to just dump messages and variables to the screen without having to use alert boxes and “console.time” which allows you to easily set up a timer to wrap a bunch of code and see how long it takes. They’re all really easy to use too…

console.time('create list');

for (i = 0; i < 1000; i++) {
    var myList = $('.myList');
    myList.append('This is list item ' + i);
}

console.timeEnd('create list');

In this instance I’ve deliberately written some very inefficient code! In the next few tips I’ll show you how we can use the timer to show some improvements which can be made.

5. Keep selection operations to a minimum by caching

jQuery selectors are awesome. They make selecting any element on the page incredibly simple, but internally they have to do a fair amount of work and if you go mad with them you might find things starting to get pretty slow.

If you’re selecting the same element time and time again (in a loop for example) then you can just select it once and keep it in memory while you manipulate it to your heart’s content. Take the following example where we add items to an unordered list using a loop.

for (i = 0; i < 1000; i++) {
    var myList = $('.myList');
    myList.append('This is list item ' + i);
}

That takes 1066 milliseconds on my PC in Firefox 3 (imagine how long it would IE6!), which is pretty slow in JavaScript terms. Now take a look at the following code where we use the selector just once.

var myList = $('.myList');

for (i = 0; i < 1000; i++) {
    myList.append('This is list item ' + i);
}

That only takes 224 milliseconds, more than 4x faster, just by moving one line of code.

6. Keep DOM manipulation to a minimum

We can make the code from the previous tip even faster by cutting down on the number of times we insert into the DOM. DOM insertion operations like .append() .prepend() .after() and .wrap() are relatively costly and performing lots of them can really slow things down.

All we need to do is use string concatenation to build the list and then use a single function to add them to your unordered list like .html() is much quicker. Take the following example…

var myList = $('#myList');

for (i=0; i<1000; i++){
    myList.append('This is list item ' + i);
}

On my PC that takes 216 milliseconds , just over a 1/5th of a second, but if we build the list items as a string first and use the HTML method to do the insert, like this….

var myList = $('.myList');
var myListItems = '';

for (i = 0; i < 1000; i++) {
    myListItems += '<li>This is list item ' + i + '</li>';
}

myList.html(myListItems);

That takes 185 milliseconds, not much quicker but that’s another 31 milliseconds off the time.

7. Wrap everything in a single element when doing any kind of DOM insertion

OK, don’t ask me why this one works (I’m sure a more experienced coder will explain).

In our last example we inserted 1000 list items into an unordered list using the .html() method. If we had have wrapped them in the UL tag before doing the insert and inserted the completed UL into another tag (a DIV) then we’re effectively only inserting 1 tag, not 1000, which seems to be much quicker. Like this…

var myList = $('.myList');
var myListItems = '<ul>';

for (i = 0; i < 1000; i++) {
    myListItems += '<li>This is list item ' + i + '</li>';
}

myListItems += '</ul>';
myList.html(myListItems);

The time is now only 19 milliseconds, a massive improvement, 50x faster than our first example.

8. Use IDs instead of classes wherever possible

jQuery makes selecting DOM elements using classes as easy as selecting elements by ID used to be, so it’s tempting to use classes much more liberally than before. It’s still much better to select by ID though because jQuery uses the browser’s native method (getElementByID) to do this and doesn’t have to do any of it’s own DOM traversal, which is much faster. How much faster? Let’s find out.

I’ll use the previous example and adapt it so each LI we create has a unique class added to it. Then I’ll loop through and select each one once.

// Create our list
var myList = $('.myList');
var myListItems = '<ul>';

for (i = 0; i < 1000; i++) {
    myListItems += '<li class="listItem' + i + '">This is a list item</li>';
}

myListItems += '</ul>';
myList.html(myListItems);

// Select each item once
for (i = 0; i < 1000; i++) {
    var selectedItem = $('.listItem' + i);
}

Just as I thought my browser had hung, it finished, in 5066 milliseconds (over 5 seconds). So i modified the code to give each item an ID instead of a class and then selected them using the ID.

// Create our list
var myList = $('.myList');
var myListItems = '<ul>';

for (i = 0; i < 1000; i++) {
    myListItems += '<li id="listItem' + i + '">This is a list item</li>';
}

myListItems += '</ul>';
myList.html(myListItems);

// Select each item once
for (i = 0; i < 1000; i++) {
    var selectedItem = $('#listItem' + i);
}

This time it only took 61 milliseconds. Nearly 100x faster.

9. Give your selectors a context

By default, when you use a selector such as $(‘.myDiv’) the whole of the DOM will be traversed, which depending on the page could be expensive.

The jQuery function takes a second parameter when performing a selection.

jQuery( expression, context )

By providing a context to the selector, you give it an element to start searching within so that it doesn’t have to traverse the whole of the DOM.

To demonstrate this, let’s take the first block of code from the tip above. It creates an unordered list with 1000 items, each with an individual class. It then loops through and selects each item once. You’ll remember that when selecting by class it took just over 5 seconds to select all 1000 of them using this selector.

var selectedItem = $('#listItem' + i);

I then added a context so that it was only running the selector inside the unordered list, like this…

var selectedItem = $('#listItem' + i, $('.myList'));

It still took 3818 milliseconds because it’s still horribly inefficient, but that’s more than a 25% speed increase by making a small modification to a selector.

10. Use chaining properly

One of the coolest things about jQuery is it’s ability to chain method calls together. So, for example, if you want to switch the class on an element.

$('myDiv').removeClass('off').addClass('on');

If you’re anything like me then you probably learned that in your first 5 minutes of reading about jQuery but it goes further than that. Firstly, it still works across line breaks (because jQuery = JavaScript), which means you can write neat code like this…

$('#mypanel')
    .find('TABLE .firstCol')
    .removeClass('.firstCol')
    .css('background' : 'red')
    .append('<span>This cell is now red</span>');

Making a habit of using chaining automatically helps you to cut down on your selector use too.

But it goes further than that. Let’s say that you want to perform several functions on an element but one of the first functions changes the element in some way, like this…

$('#myTable').find('.firstColumn').css('background','red');

We’ve selected a table, drilled down to find cells with a class of “firstColumn” and coloured them in red.

Let’s say we now want to colour all the cells with a class of “lastColumn” blue. Because we’ve used the find() funciton we’ve filtered out all the cells that don’t have a class of “firstColumn” so we need to use the selector again to get the table element and we can’t continue chaining, right? Luckily jQuery has an end() function which actually reverts back to the previous unaltered selection so you can carry on chaining, like this…

$('#myTable')
    .find('.firstColumn')
        .css('background','red')
    .end()
    .find('.lastColumn')
        .css('background','blue');

It’s also easier than you might think to write your own jQuery function which can chain. All you have to do is write a function which modifies an element and returns it.

$.fn.makeRed = function() {
    return $(this).css('background', 'red');
}

$('#myTable').find('.firstColumn').makeRed().append('hello');

How easy was that?

11. Learn to use animate properly

When I first started using jQuery I loved the fact that it was easy to use the pre-defined animations like slideDown() and fadeIn() to get some really cool effects incredibly easy. It’s easy to take things further though because jQuery’s animate() method is very easy to use and very powerful. In fact, is you look at the jQuery source code you’ll see that internally those methods are just shortcuts which use the animate() function.

slideDown: function(speed,callback){
    return this.animate({height: "show"}, speed, callback);
},

fadeIn: function(speed, callback){
    return this.animate({opacity: "show"}, speed, callback);
}

The animate() method simply takes any CSS style and smoothly transitions it from one value to another. So, you can change the width, height, opacity, background-color, top, left, margin, color, font-size, anything you want.

This is how easy it is to animate all your menu items grow to 100 pixels high when you roll over them.

$('#myList li').mouseover(function() {
    $(this).animate({"height": 100}, "slow");
});

Unlike other jQuery functions, animations are automatically queued, so if you want to run a second animation once the first is finished then just call the animate method twice, no callback necessary.

$('#myBox').mouseover(function() {
    $(this).animate({ "width": 200 }, "slow");
    $(this).animate({"height": 200}, "slow");
});

If you want the animations to happen concurrently then just put both styles in the params object of a single call, like this…

$('#myBox').mouseover(function() {
    $(this).animate({ "width": 200, "height": 200 }, "slow");
});

You can animate any property that’s numeric. You can also download plugins to help you animate properties that aren’t, like colors and background colors

12. Learn about event delegation

jQuery makes it easier than ever to attach events to elements in the DOM unobtrusively, which is great, but adding too many events is inefficient. Event delegation allows you to add less events to achieve the same result in many situations. The best way to illustrate this is with an example…

$('#myTable TD').click(function(){
    $(this).css('background', 'red');
});

A simple function which turns cells in a table red when you click on them. Let’s say that you’ve got a grid with 10 columns and 50 rows though, that’s 500 events bound. Wouldn’t it be neater if we could just attach a single event to the table and when the table is clicked have the event handler work out which cell was clicked before turning it red?

Well that’s exactly what event delegation is and it’s easy to implement…

$('#myTable').click(function(e) {
    var clicked = $(e.target);
    clicked.css('background', 'red');
});

‘e’ contains information about the event, including the target element that actually received the click. All we have to do is inspect it to see which cell was actually clicked. Much neater.

Event delegation has another benefit. Normally, When you bind a handler to a collection of elements it gets attached to those elements and those elements only. If you add new elements to the DOM which would have been matched by the selector then they don’t have the event handler bound to them (are you following me?) then nothing will happen.

When using event delegation you can add as many matching elements to the DOM as you like after the event is bound and they work too.

13. Use classes to store state

This is the most basic way of storing information about a block of html. jQuery is great at manipulating elements based upon their classes, so if you need to store information about the state of an element then why not add an extra class to store it?

Here’s an example. We want to create an expanding menu. When you click the button we want the panel to slideDown() if it’s currently closed, or slideUp() if it’s currently open. We’ll start with the HTML

<div class="menuItem expanded">
    <div class="button">
        click me
    </div>
    <div class="panel">

        <ul>
            <li>Menu item 1</li>
            <li>Menu item 2</li>
            <li>Menu item 3</li>

        </ul>
    </div>
</div>

Very simple! We’ve just added an extra class to the wrapper div which serves no other purpose other than to tell us the state of the item. So all we need is a click event handler which performs slideUp() or slideDown() on the corresponding panel when the button is clicked.

$('.button').click(function() {

    var menuItem = $(this).parent();
    var panel = menuItem.find('.panel');

    if (menuItem.hasClass("expanded")) {
        menuItem.removeClass('expanded').addClass('collapsed');
        panel.slideUp();
    }
    else if (menuItem.hasClass("collapsed")) {
        menuItem.removeClass('collapsed').addClass('expanded');
        panel.slideDown();
    }
});

That’s a very simple example, but you can add extra classes for storing all sorts of information about an element or HTML fragment.

However, in all but simple cases it’s probably better to use the next tip.

14. Even better, use jQuery’s internal data() method to store state

It’s not very well documented for some reason but jQuery has an internal data() method which can be used to store information in key/value pairs against any DOM element. Storing a piece of data is as simple as this…

$('#myDiv').data('currentState', 'off');

We can amend the example from the previous tip. We’ll use the same HTML (with the “expanded” class removed) and use the data() function instead.

$('.button').click(function() {

    var menuItem = $(this).parent();
    var panel = menuItem.find('.panel');

    if (menuItem.data('collapsed')) {
        menuItem.data('collapsed', false);
        panel.slideDown();
    }
    else {
        menuItem.data('collapsed', true);
        panel.slideUp();
    }
});

I’m sure you’ll agree this is much neater. For more information about data() and removeData(), see this page…

jQuery internals

15. Write your own selectors

jQuery has loads of built-in selectors for selecting elements by ID, class, tag, attribute and many more. But what do you do when you need to select elements based upon something else and jQuery doesn’t have a selector?

Well, one answer would be to add classes to the elements from the start and use those to select them, but it turns out that it’s not hard to extend jQuery to add new selectors.

The best way to demonstrate is with an example.

$.extend($.expr[':'], {
    over100pixels: function(a) {
        return $(a).height() > 100;
    }
});

$('.box:over100pixels').click(function() {
    alert('The element you clicked is over 100 pixels high');
});

The first block of code creates a custom selector which finds any element that is more than 100 pixels tall. The second block just uses it to add a click handler to all those elements.

I won’t go into any more detail here but you can imagine how powerful this is and if you search google for “custom jquery selector” you’ll find loads of great examples.

16. Streamline your HTML and modify it once the page has loaded

The title might not make a lot of sense but this tip can potentially neaten up your code, reduce the weight and download time of your page and help your SEO. Take the following HTML for example…


<div class="fieldOuter">
    <div class="inner">
        <div class="field">This is field number 1</div>
    </div>
    <div class="errorBar">

        <div class="icon"><img src="icon.png" alt="icon" /></div>
        <div class="message"><span>This is an error message</span></div>

    </div>
</div>
<div class="fieldOuter">
    <div class="inner">
        <div class="field">This is field number 2</div>

    </div>
    <div class="errorBar">
        <div class="icon"><img src="icon.png" alt="icon" /></div>

        <div class="message"><span>This is an error message</span></div>
    </div>
</div>

That’s an example of how a form might be marked up, modified slightly for illustrative purposes. I’m sure you’ll agree it’s pretty ugly and if you had a long form you’d end up with a fairly long ugly page. It’s be nicer if you could just put this in your HTML.

<div class="field">This is field 1</div>

<div class="field">This is field 2</div>
<div class="field">This is field 3</div>
<div class="field">This is field 4</div>
<div class="field">This is field 5</div>

All you have to do is a bit of jQuery manipulation to add all the ugly HTML back in. Like this…

$(document).ready(function() {
    $('.field').before('<div class="fieldOuter"><div class="inner">');
    $('.field').after('</div><div class="errorBar"><div class="icon">
        <img src="icon.png" alt="icon" /></div><div class="message">

        <span>This is an error message</span></div></div></div>');
});

It’s not always advisable to do this, you’ll get a bit of a flash as the page loads, but in certain situations where you’ve got a lot of repeated HTML it can really reduce your page weight and the SEO benefits of reducing all your repeated extraneous markup should be obvious.

17. Lazy load content for speed and SEO benefits

Another way to speed up your page loads and neaten up the HTML that search spiders see is to lazy load whole chunks of it using an AJAX request after the rest of the page has loaded. The user can get browsing right away and spiders only see the content you want them to index.

We’ve used this technique on our own site. Those purple buttons at the top of the page drop down 3 forms, directions and a google map, which was doubling the size of our pages. So, we just put all that HTML in a static page and use the load() function to load it in once the DOM was ready. Like this…

$('#forms').load('content/headerForms.html', function() {
    // Code here runs once the content has loaded
    // Put all your event handlers etc. here.
});

I wouldn’t use this everywhere. You have to consider the trade offs here. You’re making extra requests to the server and portions of your page might not be available to the user right away, but used correctly it can be a great optimization technique.

18. Use jQuery’s utility functions

jQuery isn’t just about flash effects. The creator has exposed some really useful methods which fill a few gaps in JavaScript’s repertoire.

http://docs.jquery.com/Utilities

In particular, browser support for certain common array functions is patchy (IE7 doesn’t even have an indexOf() method!). Jquery has methods for iterating, filtering, cloning, merging and removing duplicates from Arrays.

Other common functions that are difficult in Javascript include getting the selected item in a drop down list. In plain old JavaScript you’d have to get the <select> element using getElementByID, get the child elements as an array and iterate through them checking whether each one was selected or not. jQuery makes it easy…

$('#selectList').val();

It’s worth spending some time looking through the jQuery documentation on the main site and having a nose around some of the lesser known functions.

19. Use noconflict to rename the jquery object when using other frameworks

Most javascript frameworks make use of the $ symbol as a shorthand and this can cause clashes when trying to use more than one framework on the same page. Luckily there’s a simple solution. The .noconflict() function gives control of the $ back and allows you to set your own variable name, like this…

var $j = jQuery.noConflict();
$j('#myDiv').hide();

20. How to tell when images have loaded

This is another one of those problems that doesn’t seem to be as well documented as it should be (not when I went looking anyway) and it’s a fairly common requirement when building photo galleries, carousels etc, but it’s fairly easy.

All you have to do is use the .load() method on an IMG element and put a callback function in it. The following example changes the “src” attribute of an image tag to load a new image and attaches a simple load function.

$('#myImage').attr('src', 'image.jpg').load(function() {
    alert('Image Loaded');
});

You should find that the alert is called as soon as the image is loaded.

21. Always use the latest version

jQuery is constantly improving and John Resig, it’s creator, always seems to be in search of ways to improve performance.

jQuery is currently on version 1.2.6 but John has already revealed that he’s working on a new selector engine called Sizzle, which may apparently improve selector speeds in Firefox by up to 4x. So, it pays to keep up to date.

22. How to check if an element exists

You don’t need to check if an element exists on the page before you manipulate it because jQuery will will simply do nothing if you try to select something and it isn’t in the DOM. But when you do need to check if anything has been selected, or how many items have been selected you can use the length property.

if ($('#myDiv).length) {
    // your code
}

Simple, but not obvious.

23. Add a JS class to your HTML attribute

I learned this tip from Karl Swedberg whose excellent books I used to learn jQuery.

He recently left a comment on one of my previous articles about this technique and the basics are as follows…

Firstly, as soon as jQuery has loaded you use it to add a “JS” class to your HTML tag.


$('HTML').addClass('JS');

Because that only happens when javascript is enabled you can use it to add CSS styles which only work if the user has JavaScript switched on, like this…

.JS #myDiv{display:none;}

So, what this means is that we can hide content when JavaScript is switched on and then use jQuery to show it when necessary (e.g. by collapsing some panels and expanding them when the user clicks on them), while those with JavaScript off (and search engine spiders) see all of the content as it’s not hidden. I’ll be using this one a lot in the future.

To read his full article click here.

24. Return ‘false’ to prevent default behaviour

This should be an obvious one but maybe not. if you have a habit of doing this…

<a href="#" class="popup">Click me!</a>

… and then attaching an event handler like this…

$('popup').click(function(){
    // Launch popup code
});

… it’ll probably work fine until you use it on a long page, at which point you’ll notice that the # is causing it to jump to the top of the page when your click event is triggered.

All you have to do to prevent this default behaviour, or indeed any default behaviour on any event handler is to add “return false;” to your handler, like this…

$('popup').click(function(){
    // Launch popup code
    return false;
});



25. Shorthand for the ready event

A small tip this one but you can save a few characters by using shorthand for the $(document).ready function.

Instead of this…

$(document).ready(function (){
    // your code
});

You can do this…

$(function (){
    // your code
});

25 March 2010 ~ 0 Comments

Best practices in web development

this post is taken from http://blog.apps.chicagotribune.com/2010/02/26/best-practices/

Javascript

  • Don’t use jQuery in widgets that will end up on other sites.
  • Otherwise, use jQuery.
  • Whenever possible, put Javascript at the bottom of the page.
  • Don’t use inline Javascript.

HTML/CSS

  • Add a top level ID to every kind of page (#race-page, #candidate-page)
  • Use IDs for elements that are unique to every page in the site. Use classes for everything else.
  • Use hyphens for IDs and classes, no camelCase or underscores.
  • Use descriptive and unique names for IDs. Use simple generic names for classes.
  • Always define classes with nested rules: #candidate-page .box-column .box .bar-chart. Use your best judgment, don’t go overboard with the nested rules, just enough to make sure your not going to style the wrong things. IDs rarely need to be nested
  • Each CSS selector gets its own line. The block of rules has to share. It makes big CSS scannable:
    a:link {color:#336699;}
    a:hover,
    a:active {color:#6d9fd2;}
    a:visited {color:#336699;}
    a:visited:hover {color:#6d9fd2;}
    
  • Don’t rely on (because of IE6):
    • min-width, max-width, min-height, max-height
    • overflow:hidden
    • css tables
    • attribute selectors
    • psudo-classes (other than for a tags)
    • > (child selector)
    • position:fixed
  • If you are positioning one block absolutely inside another, make sure the parent has a specified size.
  • Don’t use inline styles.

Images

  • Don’t use them.
  • If you use them, make sure you use photoshop’s “Save for web…” or figure out another way to optimize them.
  • Use jpeg for images with lots of different colors and gradients, png/gif for images with few colors.
  • PNG rules (if you’re relying on PNG fix)
    • Don’t use PNGs. If it hurts, blame Microsoft.
    • If you use PNGs, don’t use PNGs with alpha
    • If you use PNGs with alpha, use them in img tags only.
    • If you use PNGs with alpha as background images: http://24ways.org/2007/supersleight-transparent-png-in-ie6

20 March 2010 ~ 0 Comments

10 sql tips to speed up your database

this post were taken from catswhocode

Design your database with caution

This first tip may seems obvious, but the fact is that most database problems come from badly-designed table structure.
For example, I have seen people storing information such as client info and payment info in the same database column. For both the database system and developers who will have to work on it, this is not a good thing.
When creating a database, always put information on various tables, use clear naming standards and make use of primary keys.
Source: http://www.simple-talk.com/sql/database-administration/ten-common-database-design-mistakes/

Know what you should optimize

If you want to optimize a specific query, it is extremely useful to be able to get an in-depth look at the result of a query. Using the EXPLAIN statement, you will get lots of useful info on the result produced by a specific query, as shown in the example below:

EXPLAIN SELECT * FROM ref_table,other_table WHERE ref_table.key_column=other_table.column;

Source: http://dev.mysql.com/doc/refman/5.0/en/using-explain.html

The fastest query… Is the one you don’t send

Each time you’re sending a query to the database, you’re using a bit of your server resources. This is why, on high traffic sites, the best thing you can do in order to speed up your database is to cache queries.

There’s lots of solutions to implement a query cache on your server. Here are a few:

  • AdoDB: AdoDB is a database abstraction library for PHP. It allows you to use the database system of your choice (MySQL, PostGreSQL, Interbase, and way much more) and it is designed for speed. AdoDB provides a simple, yet powerful caching system. And last but not least, AdoDB is licenced under the BSD, which means that you can use freely on your projects. A LGPL licence is also available for commercial projects.
  • Memcached: Memcached is a distributed memory caching system which is often used to speed up dynamic database-driven websites by alleviating database load.
  • CSQL Cache: CSQL Cache is an open-source data caching infrastructure. Never tested it personally, but it seems to be a great tool.

Don’t select what you don’t need

A very common way to get the desired data is to use the * symbol, which will get all fields from the desired table:

SELECT * FROM wp_posts;

Instead, you should definitely select only the desired fields as shown in the example below. On a very small site with, let’s say, one visitor per minute, that wouldn’t make a difference. But on a site such as Cats Who Code, it saves a lot of work for the database.

SELECT title, excerpt, author FROM wp_posts;

Use LIMIT

It’s very common that you need to get only a specific number of records from your database. For example, a blog which is showing ten entries per page. In that case, you should definitely use the LIMIT parameter, which only selects the desired number of records.
Without LIMIT, if your table has 100,000 different records, you’ll extract them all, which is unnecessary work for your server.

SELECT title, excerpt, author FROM wp_posts LIMIT 10;

Avoid queries in loops

When using SQL along with a programming language such as PHP, it can be tempting to use SQL queries inside a loop. But doing so is like hammering your database with queries.
This example illustrates the whole “queries in loops” problem:

foreach ($display_order as $id => $ordinal) {
    $sql = "UPDATE categories SET display_order = $ordinal WHERE id = $id";
    mysql_query($sql);
}

Here is what you should do instead:

UPDATE categories
    SET display_order = CASE id
        WHEN 1 THEN 3
        WHEN 2 THEN 4
        WHEN 3 THEN 5
    END
WHERE id IN (1,2,3)

Source: http://www.karlrixon.co.uk/articles/sql/update-multiple-rows-with-different-values-and-a-single-sql-query/

Use join instead of subqueries

As a programmer, subqueries are something that you can be tempted to use and abuse. Subqueries, as show below, can be very useful:

SELECT a.id,
    (SELECT MAX(created)
    FROM posts
    WHERE author_id = a.id)
AS latest_post FROM authors a

Although subqueries are useful, they often can be replaced by a join, which is definitely faster to execute.

SELECT a.id, MAX(p.created) AS latest_post
FROM authors a
INNER JOIN posts p
    ON (a.id = p.author_id)
GROUP BY a.id

Source: http://20bits.com/articles/10-tips-for-optimizing-mysql-queries-that-dont-suck/

Be careful when using wildcards

Wildcards are very useful because they can substitute for one or more characters when searching for data in a database. I’m not saying that you shouldn’t use them, but instead, you should use them with caution and not use the full wildcard when the prefix or postfix wildcard can do the same job.
In fact, doing a full wildcard search on a million records will certainly kill your database.

#Full wildcard
SELECT * FROM TABLE WHERE COLUMN LIKE '%hello%';
#Postfix wildcard
SELECT * FROM TABLE WHERE COLUMN LIKE  'hello%';
#Prefix wildcard
SELECT * FROM TABLE WHERE COLUMN LIKE  '%hello';

Source: http://hungred.com/useful-information/ways-optimize-sql-queries/

Use UNION instead of OR

The following example use the OR statement to get the result:

SELECT * FROM a, b WHERE a.p = b.q or a.x = b.y;

The UNION statement allows you to combine the result sets of 2 or more select queries. The following example will return the same result that the above query gets, but it will be faster:

SELECT * FROM a, b WHERE a.p = b.q
UNION
SELECT * FROM a, b WHERE a.x = b.y

Source: http://www.bcarter.com/optimsql.htm

Use indexes

Database indexes are similar to those you can find in libraries: They allow the database to find the requested information faster, just like a library index will allow a reader to find what they’re looking for without loosing time.
An Index can be created on a single column or a combination of columns in a database table. A table index is a database structure that arranges the values of one or more columns in a database table in specific order.

The following query will create an index on the Model column from the Product table. The index is called idxModel:

CREATE INDEX idxModel ON Product (Model);

Source: http://www.sql-tutorial.com/sql-indexes-sql-tutorial/

20 March 2010 ~ 0 Comments

Top 10 best practices for front-end web developers

this article was taken from catwhoscode.

Explain which div you’re closing

Most of the time when I’m viewing a website source, I see, at the very bottom of the page, an almost endless list of closing </div> tags. In fact, many beginners think they just have to use divs instead of tables to produce quality code. Divs are cleaners than tables, but without proper code organization, it can be as (or even sometimes more) messy as table based code.

Using indentation is a good start. But a tip that can definitely make you save lot of time is to comment every div tag you’re closing, as shown in the example below:

<div id="header">

  <div id="sub" class="first left">
    ...
  </div><!-- #sub.first.left -->
</div><!-- #header -->

Use a CSS reset

Unless you’re a beginner or if you were on vacation on a desert island for the last 6 years, you might already know how useful a CSS reset it. Because by default, browsers don’t apply the same default styling to HTML elements, a CSS reset will ensure that all element have no particular style so you can define your own without the risk of many cross-browser rendering issues.

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
	margin: 0;
	padding: 0;
	border: 0;
	outline: 0;
	font-size: 100%;
	vertical-align: baseline;
	background: transparent;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}

/* remember to define focus styles! */
:focus {
	outline: 0;
}

/* remember to highlight inserts somehow! */
ins {
	text-decoration: none;
}
del {
	text-decoration: line-through;
}

/* tables still need 'cellspacing="0"' in the markup */
table {
	border-collapse: collapse;
	border-spacing: 0;
}

Source: http://meyerweb.com/eric/tools/css/reset/index.html

Don’t use @import

CSS files can be included using the @import directive. This can be useful when, for example, you want to include a stylesheet into another. Another common practice is to include CSS file in html documents using the following:

<style type="text/css>

  @import url('a.css');
  @import url('b.css');
</style>

While it works, the @import directive is much slower than the other way to include stylesheets into a html document:

<link rel='stylesheet' type='text/css' href='a.css'>
<link rel='stylesheet' type='text/css' href='proxy.css'>

It will not make a difference on low traffic websites, but if you have the chance to own a popular website, don’t waste your visitor’s time using @import.
Source: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/

“Smush” your images

Being a developer, I always found that optimizing my images for the web wasn’t easy. I tried the good old “Save for web” Photoshop command, but most of the time, I ended up with images that were either too big or without a sufficient quality.
As a result, I had the bad habit of using unoptimized images on my websites. This isn’t a problem when you don’t have to care about your site’s bandwidth, but after my recent switch on my vps.net virtual private server, I had to be careful with image sizes.

At this time, I found a very cool tool named Smush It: You enter your unoptimized image url, and Smush It will create a perfectly optimized image for you. You can save up to 70% of the file size, while keeping the original quality. As an example, all the images from my list of online code editors have been “smushed”.

Don’t mix CSS with HTML

As a markup language, the right use of HTML is to organize documents by defining a header, a footer, lists, blockquotes, etc. Some time ago, front-end web developers often used now deprecated HTML attributes to style a particular element.
Nowadays, the style attribute allows developers to insert CSS directly into a html document. This is very useful for testing or when you’re in a hurry. But the style attribute is bad practice, that goes completely against the CSS philosophy.

The following example illustrates how dirty and hard to read a simple line of code can become, with the style attribute:

<a href="http://www.catswhocode.com" style="background:#069;padding:3px;font-weight:bold;color:#fff;">Cats Who Code</a>

Don’t mix Javascript with HTML

Just like mixing your html code with css is bad practice, you shouldn’t use any Javascript in your html documents. The following bad practice illustrates an onclick event:

<a id="cwc" href="http://www.catswhocode.com" onclick="alert('I love this site!');">Cats Who Code</a>

The same result can be achieved using unobstructed Javascript. In this example, I’m using the popular jQuery framework:

$(document).ready(function() {
  $('#cwc').click(function() {
    alert('I love this website');
  });
});

This may seems a bit harder at first, especially for beginners; but it is definitely not, and it will keep your html document clean.

Use conditional comments

You know it, IE sucks, and some clients suck even more by requiring you to create webpages which are compatible with this obsolete browser. To target specific versions of IE, you can use the well known IE hacks, as shown below:

height: 200px; /* normal browsers */
_height: 300px; /* IE6 */
.height: 250px; /* IE7 */
*height: 350px; /* All IEs */

Those hacks are extremely useful sometimes, but they are not the best way to target a specific version of IE, and it will cause your CSS validation to fail.

Instead, you should use the conditional comment shown below to target IE6.

<link href="style.css" rel="stylesheet" type="text/css" />

<!--[if lte IE 6]>
  <link href="ie.css" rel="stylesheet" type="text/css" />
<![endif]-->

Place Javascript file at the bottom

A popular practice of the late 90’s/early 2000’s was to place Javascript files within the <head> and </head> tags. The problem is that your javascript files will be loaded first, and consequently your content will be loaded after.

By placing Javascript files at the bottom of your documents, you’ll ensure that JS files will be loaded only when the content has been properly displayed.

    ...
    <script type='text/javascript' src='jquery.js?ver=1.3.2'></script>

  </body>
</html>

Use HTML semantically

HTML is not a programming language. It is a markup language, used to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, and more.
If you started to create websites in the good old 90’s or in the beginning of the century, you know how dirty the markup was at the time. But happilly, it has evolved.
Among other things, it is important to use html element semantically. As an example, a navigation menu should always be an unordered list:

<ul>
  <li><a href="#">Home</a></li>

  <li><a href="#">About</a></li>
  <li><a href="#">Contact</a></li>
  <li><a href="#">Blog</a></li>

</ul>

Test WHILE you build to avoid cross-browser issues

One of the biggest mistake I ever made when developing html, CSS, and javascript, was not to test my pages on multiple browser while I was writing them. Instead, I used to write all my code and just view in Firefox to see how it was rendered.
In theory, this should be good. But as you know, cross-browser issues are a major problem for front-end developers, especially due to IE. If you test your documents on Firefox/IE/Chrome while your writing it, cross-browser rendering problems will be much easier to fix. I have lost hours not doing it, so I hope this final tip will help you saving your precious time. To test on multiple versions of IE, I use this very handy tool. Happy coding

18 March 2010 ~ 0 Comments

CSS 100% Height – maximum window height

artikel ini dipetik dari http://www.tutwow.com/tips/quick-tip-css-100-height/

masalah yg selalu dihadapi ialah bila kita nak buat website yg strech all the way down 100% of the window height. kadang2 sampai tension sebab kenapa layout tak jugak strecth 100% walaupun dah set mcmtu kat CSS. consider the following HTML/CSS code:


Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

the code above akan bagi kita rupabentuk mcmni:

so, kalau tengok balik source code kita, rasa cam dah betul dah CSS rules untuk #content. TAPI, sebenarnya cara browser interpret HTML agak berlainan dari yg kita sangka. bila kita tulis #content {height:100%} kita sebenarnya menyuruh #content supaya meng-set ketinggiannya kepada 100% menyamai IMMEDIATE PARENT-NYA. dalam kes ini, immediate parent bagi #content ialah BODY. sedangkan kita pun tak bgtau kat BODY berapa ketinggian dia, jadi BODY pun render setinggi content element tu sahajalah. kemudian BODY pun sebenarnya mengikut ketinggian parent-nya, dalam kes ini, parent untuk BODY ialah HTML. dan HTML pun kita tak bgtahu berapa ketinggiannya, maka jadilah ketinggian #content tadi hanya setakat mengikut ketinggian contentnya semata-mata.

jadi untuk set supaya #content mempunyai ketinggian maksimum 100% pada window browser tadi, consider the following CSS code:

html {
	min-height: 100%;
}
body {
	margin: 0;
	padding: 0;
	min-height: 100%;
}
#content {
	background: #EEE;
	border-left: 1px solid #000;
	border-right: 1px solid #000;
	padding: 0 20px 0 20px;
	margin: auto;
	font: 1.5em arial, verdana, sans-serif;
	width: 960px;
	min-height: 100%;
}

dan hasilnya nanti adalah seperti berikut. senang je kan :)

16 March 2010 ~ 2 Comments

Website Hacking – Tips & Tricks

This time i would like to share a few tips on website hacking.i read this from http://rodneykeeling.com/blog/.
he has compile a list of useful yet common techniques and methods for attack that span over a variety of web technologies. Fortunately, implementing a few precautions before making your site live can help prevent some of these techniques from being used against you.

1. XSS Vulnerabilities
Cross-Site Scripting (XSS) is an exploit wherein the attacker utilizes unsanitized forms and user inputs to execute/inject client-side scripts onto the web page. There are two main types of XSS attacks; persistent and non-persistent. Non-persistent attacks are static and are not saved by the web page/site; however, they still may be dangerous. A simple, non- harmful example of a non-persistent attack would be inserting this into a vulnerable form:

Non-persistent attacks are still dangerous, however, for an XSS script could lead a user on a website to pass over valuable cookie information which could easily result in a session hijack for that particular website. Although this example may just popup with “This has an XSS vulnerability”, if you know your way around Javascript, I’m sure you can imagine what you can do to vulnerable forms. Persistent XSS attacks are normally much more damaging to the website, for the server actually saves the exploit code and runs/displays it on the website for everyone to fall into. Preventing XSS attacks is normally a case-by-case scenario, but generally you want to disable any sort of scripting input in your forms.

2. SQL Injections
SQL, as you may know, is a database language that is very popular. Popular technologies generally tend to be more tested for vulnerability, and SQL is no exception. SQL injections are where an attacker injects SQL code into particular locations that are then parsed as SQL code rather than sanitized entries for a normal database. The most primitive example of this looks something like this:

someText’ OR ‘1’=’1’ – 

On the database side, this will look like this:

WHERE field = ’someText’ OR ‘1'=’1' — the rest is commented out 

As you can see, the user input creates a logical statement that will always be true, and any unnecessary code for the attacker can be commented out with –. SQL injections can be executed in a number of locations including fields, PHP POST data, and even in URLs in the form of GET data. Protecting against SQL injections can sometimes be tricky; however, proper sanitizing of inputs usually rids from unwanted attacks.

3. Directory Traversal
This method is particularly dangerous not only to the users of a website, but the actual admins of the website. Directory traversal involves improperly sanitized inputs (Unix commands in this case) leading to discovering highly sensitive server information such as server passwords and full root access to user databases or whatever the attacker wants to look at. This attack is shown in this example:

someURL/page.php?variable=/ etc/ passwd 

As you can see, this attack is commonly used in GET data in the URL of a PHP, CGI, ASP, or other type of page. It uses ../ to traverse (hence the name) to a lower level directory (../ etc/ passwd) in this case.

4. Distributed Denial of Service (DDoS)
A Denial of Service attack on a website is actually a pretty simple thing to do – an attacker floods the website’s server with requests, thus crashing the server and leaving the website unusable. This is a pretty easy attack to defend against, for when the requests from a particular IP address increases to an obscure amount, the target web server can just block future requests from the attackers IP adress. The Distributed Denial of Service attack is different; the attacker floods the web server with requests from a variety (or distributed) amount of IP addresses. This makes it much more difficult for the target to block requests. One method to defend against this attack is, when a noticeable amount of requests are beginning to flood the server, to stop the target servers from responding to any requests for the remaining time of the attack(s).

5. Cookie Manipulation
By itself, changing cookies to give the attacker certain access will usually only work on lower-grade websites where there is minimal protection against hacking. Unfortunately, some websites still use unencrypted cookie names and values that will never expire per user session. In this case, changing cookies can be as easy as one, viewing the cookies (via the address bar):

javascript:alert(document.cookie);

This will popup with the cookie information and, if it’s a poorly-secured website as stated earlier, a few indications of what each field represents (e.g. user=rodney). To change these cookie values, the following may be done:

javascript:void(document.cookie=”user=admin”);

I cannot make this any more clear: if cookies are as simple as this on a particular website, the website is more than likely vulnerable to ten thousand other attacks. Heck, you may even find an admin password commented in the source.

6. Brute Force & Dictionary Cracking
I won’t go over these techniques too much, for I have a whole other post about using brute force to crack passwords. The first term, brute force, sounds a lot cooler than it actually is. Using a brute force method is usually the last resort in cracking a password due to the time it takes on passwords greater than four characters. Brute force is iterating through every single character combination until the correct combination is found. As a function, brute force grows exponentially per time unit. Next, a dictionary attack is a method of find a password by searching through a dictionary list (usually a plain text file) and trying each entry as the password. A deviation of the dictionary attack, called a hybrid attack, may test a combination of entries in the dictionary concatenated with other entries. For example, instead of just trying ‘pass’ and ‘1234′, the hybrid attack may also try ‘pass1234′ and/or ‘1234pass’.

7. On-the-fly Javascript Editing with Firebug
This technique is relatively simple and is similar in security level as cookie editing is. Firebug, an add-on for Firefox, can be used to edit webpages XHTML, CSS, Javascript, and more on the fly. Of course, the user may not save the file to be viewed by every visitor thereafter; however, it still is really useful. Before I begin explaining this, I just want to clarify that Firebug is not a hacking tool; it is used by a lot of web developers and designers to make changes to their sites without having to edit, save, then reload. It speeds things up and is an amazing tool. Anyway, if the creator of a particular webpage decided to put any type of potentially valuable information into the Javascript on a webpage (again, not a trait of an experienced security expert/developer), one may use Firebug to change this potentially valuable information and have everything submitted, parsed, and output a desired effect (e.g. changing administrative access) without doing an extreme amount of hacking.

So with a number of examples commonly used (some in combination with others), one may see how much of a variety of tools hackers have to gain access to websites. Of course there are a ton more techniques and weaknesses in web sites and servers, but I think this is enough for a base. More often than not, more than one technique will be employed while gaining restricted access to a website. For example, XSS is commonly used to either change or capture user cookie information to hijack a user’s session, thus gaining access to all of their content. I hope this has clarified some terms and concepts for those wanting to learn more about web security. Happy hacking!

this article is taken from:
http://rodneykeeling.com/blog/hacking-techniques-part-1
http://rodneykeeling.com/blog/hacking-techniques-part-2

06 March 2010 ~ 0 Comments

Disabling Right Click (context menu) with jQuery

using jQuery as follows:


$(document).ready(function()
{
       $(document).bind("contextmenu",function(e){
              return false;
       });
});

06 March 2010 ~ 1 Comment

threadsy


would like to introduce u to use threadsy (http://www.threadsy.com).
website ni bagus, sebab dia boleh combine your gmail, yahoo, hotmail, webmail, twitter & facebook all in one place. and not just that, they make it so easy to digest.

i’ve tried seesmic (http://www.seesmic) before. which suppose to do similar thing, tapi the interface was very cluttered. tengok lama-lama pun boleh jadi confuse+pening.

but threadsy ni sangat2 baguslah. after u linked all your facebook, gmail, yahoo & twitter, dah tak payah waste time to open multiple window to visit those site. just browse them through threadsy. & the experience will never be the same again – truly amazing!

i have posted a free invitation on twitter & facebook. right now they’re alowing new registration as per-invitation only. so quick! :-)

among the oooohh..& aaaah…on threadsy are:
1. simple & easy to use email composing.
2. very clean email inbox listing. choices between simple & detail list just awesome.(dont forget to check on email as favourites.)
3. you can now see the sender profile( if he/she has social network account, facebook & twitter stream)
4. search through email, facebook & twitter like never before.
5. facebook chat, google talk all in one place.
6. for the first time, sending tweets is fun (try type in a full url ie: http://www.azgiftbaskets.com.my – see the magic)
7. soothing tone upon new tweets/email arrival (not like fart sound from facebook)

try it now & i’m sure u like it :-)

02 February 2010 ~ 0 Comments

How to code a PSD layout into valid XHTML/CSS

this tutorial is taken from: http://designbump.com/originals/how-code-psd-layout-valid-xhtmlcss-psd-included

Coding up a simple and clean website from scratch does not need to be a difficult or time consuming task. Today we’re going to be taking a PSD file and turning it into a valid XHTML/CSS template. The files used to create the template are downloadable at the end of the article (PSD included).

There are only nine steps involved in the entire tutorial, so it shouldn’t take you more than 20 minutes to run through and see how each of the steps are done. Let’s get started!

Materials Needed:

  • Background texture from Seamless Textures: Download Here
  • Photo for “Most Recent Work” section from iStockPhoto
  • We’re using Cufon text replacement. Read more about it HERE
  • While I’m not following the codes from it, the website was built using the 960.gs grid system.
What we will be making:
final

Step 1: Build the XHTML/CSS for your main website blocks

The items in this section are going to be the main XHTML blocks which will control the sizes of the sections.

Step 2: Build the inner blocks for the layout

Here, we’re building the inner sections for the layout which will give extra padding and width to areas that require it (ie: the post wrap code and the side boxes).

Step 3: Add in the main content for each section

Below, you’ll see the codes added in for the H1 tag for the logo (which is going to be using an image replacement in the CSS), the navigation wrap codes, the post content sections, ect.

Some cool text goes here

Here is the title of your post

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce scelerisque, elit id vestibulum vestibulum, orci dolor dignissim augue, vitae accumsan tortor lectus id elit. Morbi metus enim, vulputate in, lobortis sed, pulvinar nec, dolor. Nam metus urna, tincidunt vel, dignissim non, rhoncus sed, elit. Integer rhoncus. Maecenas tellus tortor, sagittis et, dictum quis, tristique nec, dui. Curabitur nec arcu. Sed non libero. Curabitur justo. Aenean nisl tellus, porta nec, scelerisque id, euismod tempus, eros. Mauris vestibulum, mi id semper viverra, lorem risus suscipit ipsum, eu luctus augue dui ut libero. Maecenas dignissim erat sodales massa. Duis at erat. Cras porta. Suspendisse nunc tortor, blandit ut, suscipit quis, vehicula nec, nunc. Maecenas facilisis vulputate sapien. Sed ac mi non sem euismod euismod. Maecenas ultrices consequat dolor. Integer ultrices. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce scelerisque, elit id vestibulum vestibulum, orci dolor dignissim augue, vitae accumsan tortor lectus id elit. Morbi metus enim, vulputate in, lobortis sed, pulvinar nec, dolor. Nam metus urna, tincidunt vel, dignissim non, rhoncus sed, elit. Integer rhoncus. Maecenas tellus tortor, sagittis et, dictum quis, tristique nec, dui. Curabitur nec arcu. Sed non libero. Curabitur justo. Aenean nisl tellus, porta nec, scelerisque id, euismod tempus, eros. Mauris vestibulum, mi id semper viverra, lorem risus suscipit ipsum, eu luctus augue dui ut libero. Maecenas dignissim erat sodales massa. Duis at erat. Cras porta. Suspendisse nunc tortor, blandit ut, suscipit quis, vehicula nec, nunc. Maecenas facilisis vulputate sapien. Sed ac mi non sem euismod euismod. Maecenas ultrices consequat dolor. Integer ultrices.
© Copyright 2009. Website Name. All Rights Reserved. made by Guerrilla & released by Design Bump

Step 4: Add in different box styles for sidebar

We’re using different style boxes in the sidebar, so we’re going to go ahead and place them into the sidebar section now.

Some cool text goes here
10

Here is the title of your post

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce scelerisque, elit id vestibulum vestibulum, orci dolor dignissim augue, vitae accumsan tortor lectus id elit. Morbi metus enim, vulputate in, lobortis sed, pulvinar nec, dolor. Nam metus urna, tincidunt vel, dignissim non, rhoncus sed, elit. Integer rhoncus. Maecenas tellus tortor, sagittis et, dictum quis, tristique nec, dui. Curabitur nec arcu. Sed non libero. Curabitur justo. Aenean nisl tellus, porta nec, scelerisque id, euismod tempus, eros. Mauris vestibulum, mi id semper viverra, lorem risus suscipit ipsum, eu luctus augue dui ut libero. Maecenas dignissim erat sodales massa. Duis at erat. Cras porta. Suspendisse nunc tortor, blandit ut, suscipit quis, vehicula nec, nunc. Maecenas facilisis vulputate sapien. Sed ac mi non sem euismod euismod. Maecenas ultrices consequat dolor. Integer ultrices. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce scelerisque, elit id vestibulum vestibulum, orci dolor dignissim augue, vitae accumsan tortor lectus id elit. Morbi metus enim, vulputate in, lobortis sed, pulvinar nec, dolor. Nam metus urna, tincidunt vel, dignissim non, rhoncus sed, elit. Integer rhoncus. Maecenas tellus tortor, sagittis et, dictum quis, tristique nec, dui. Curabitur nec arcu. Sed non libero. Curabitur justo. Aenean nisl tellus, porta nec, scelerisque id, euismod tempus, eros. Mauris vestibulum, mi id semper viverra, lorem risus suscipit ipsum, eu luctus augue dui ut libero. Maecenas dignissim erat sodales massa. Duis at erat. Cras porta. Suspendisse nunc tortor, blandit ut, suscipit quis, vehicula nec, nunc. Maecenas facilisis vulputate sapien. Sed ac mi non sem euismod euismod. Maecenas ultrices consequat dolor. Integer ultrices.

Cool headline goes here

Availability: Currently Open For Work Phone: 333.333.3333 Email: youremailaddress@gmail.com
© Copyright 2009. Website Name. All Rights Reserved. made by Guerrilla & released by Design Bump

Step 5: Add in the main structure for the CSS file

Below is the base of the css which will control the main structure of the site.

body {
background: #252525 url(images/bg_website.jpg) repeat top left;
color: #F8F8F8;
font: normal 13px Verdana, Arial, Helvetica, sans-serif;
line-height: 20px;
margin: 0;
padding: 0;
}

#sitewrapper {
margin: 0 auto;
overflow: auto;
position: relative;
padding: 0;
width: 960px;
}

.headerwrap {
float: left;
margin: 0;
padding: 0;
position: relative;
width: 960px;
}

.featuredwrap {
background: #93C4C2 url(images/bg_featured.jpg) no-repeat top center;
float: left;
height: 200px;
margin: 0;
overflow: hidden;
padding: 0;
position: relative;
width: 960px;
}

.contentwrap {
float: left;
margin: 10px;
padding: 0;
position: relative;
width: 640px;
}

.sidebarwrap {
float: left;
margin: 10px;
padding: 0;
position: relative;
width: 280px;
}

.footerwrap {
border-top: 1px solid #898989;
color: #898989;
float: left;
margin: 0;
padding: 10px;
position: relative;
width: 940px;
text-align: center;
}

Step 6: Add in the inner structure for the CSS file

Now is where we start to line things up in the inner sections. No real styling will be taking place as far as the content of the site, but these are the selectors which put everything in proper places.

.logowrap {
float: left;
margin: 0 10px 0 0;
padding: 0;
position: relative;
width: 460px;
}

.navigationwrap {
float: right;
margin: 0 0 0 10px;
padding: 0;
position: relative;
width: 460px;
}

.postwrap {
float: left;
margin: 0 0 20px 0;
padding: 0;
position: relative;
width: 640px;
}

.sideboxwrap {
float: left;
margin: 0 0 20px 0;
padding: 0;
position: relative;
width: 280px;
}

Step 7: Add in the main content sections for the CSS file

And now we’re getting somewhere! These css codes below are the items that help the site take shape and actually start to show up properly. At this point you will actually see the site 80% complete. The next two steps are the smaller, quicker adjustments to finalize the pieces that aren’t working yet.

a, a:visited { color: #DDF0F8; text-decoration: none; outline: none; }
a:hover { color: #F8F8F8; text-decoration: none; }

.logowrap h1 a {
text-indent: -9999px;
background: url(images/logo.png) no-repeat top left;
display: block;
width: 222px;
height: 74px;
}

.navigationwrap ul { float: right; padding:40px 0; margin:0; list-style: none;}
.navigationwrap ul li {float:left; position:relative; }
.navigationwrap ul li a { font-size: 14px; text-transform: lowercase; color: #FFF; padding: 0 10px; margin: 0; text-decoration: none; }
.navigationwrap ul li a:hover {color:#DDF0F8; text-decoration: none;}

.taglinewrap {
color: #87B2B0;
font-size: 48px;
float: left;
line-height: 60px;
margin: 10px;
padding: 0;
position: relative;
width: 460px;
}

.scrollboxwrap {
float: right;
margin: 10px;
padding: 0 29px;
position: relative;
width: 392px;
}

.scrollboxwrap h3 { margin: 5px 0; padding: 0; text-transform: uppercase; font-size: 18px; }
.scrollboxwrap img { border: 5px solid #87B2B0; }

.bubblewrap {
background: url(images/bg_commentbubble.png) no-repeat top center;
color: #C2C2C2;
float: left;
font-size: 24px;
height: 46px;
line-height: 34px;
margin: 0 10px 0 0;
padding: 0;
position: relative;
text-align: center;
width: 44px;
}

.bubblewrap a, .bubblewrap a:visited { color: #C2C2C2; text-decoration: none; }
.bubblewrap a:hover { color: #93C4C2; text-decoration: none; }

.postwrap h2 { color: #DDF0F8; padding: 0; margin: 0; font-size: 24px; font-weight: bold; line-height: 24px; text-shadow: 1px 1px 1px #252525; }
.postwrap h2 a, .postwrap h2 a:visited { color: #DDF0F8; text-decoration: none; }
.postwrap h2 a:hover { color: #F8F8F8; text-decoration: none; }

.postinfo { margin: 5px 0; padding: 0; width: 100%; color: #898989; font-size: 14px;  }
.postinfo a, .postinfo a:visited { color: #c2c2c2; text-decoration: none; }
.postinfo a:hover { color: #F8F8F8; text-decoration: none; }

.sideboxwrap h3 { font-size: 18px; font-weight: bold; text-transform: uppercase; color: #DDF0F8; text-shadow: 1px 1px 1px #252525; margin: 0 0 5px 0; padding: 0; }

.sideboxwrap ul { list-style-type: none; margin: 0; padding: 0; }
.sideboxwrap ul li { padding: 4px 0; list-style: inline; margin: 0; width: 280px; }
.sideboxwrap ul li a, .sideboxwrap ul li a:visited { background: url(images/bg_sideboxlist.png) no-repeat top left; padding: 0 0 0 12px; color: #898989; }
.sideboxwrap ul li a:hover { color: #FFF; text-decoration: none; }

.footerwrap p { margin: 0; padding: 3px 0; }
.footerwrap a, .footerwrap a:visited { color: #898989; }
.footerwrap a:hover { color: #c2c2c2; }

Step 8: Add different sidebar item styles in the CSS file

So if you notice, the sidebar has blocks for the search, availability and newsletter sign up. These items for the css are what takes care of those.

.sideboxwrap h3 { font-size: 18px; font-weight: bold; text-transform: uppercase; color: #DDF0F8; text-shadow: 1px 1px 1px #252525; margin: 0 0 5px 0; padding: 0; }

.sideboxwrap ul { list-style-type: none; margin: 0; padding: 0; }
.sideboxwrap ul li { padding: 4px 0; list-style: inline; margin: 0; width: 280px; }
.sideboxwrap ul li a, .sideboxwrap ul li a:visited { background: url(images/bg_sideboxlist.png) no-repeat top left; padding: 0 0 0 12px; color: #898989; }
.sideboxwrap ul li a:hover { color: #FFF; text-decoration: none; }

.blockedout { background: #252525; border: 1px solid #000; color: #898989; font-size: 12px; padding: 10px; width: 258px; }
.blockedout h3 { text-transform: none; }
.blockedout p { margin: 3px; padding: 0; }
.blockedout a, .blockedout a:visited { color: #898989; }
.blockedout a:hover { color: #c2c2c2; }

.searchwrap { background: #252525; border: 1px solid #000; color: #898989; font-size: 12px; padding: 5px; width: 268px; }
form { padding: 0; margin: 0; }
.search_input { width: 188px; height: 16px; padding: 5px; background: transparent; border: 0; margin: 0 10px 0 0; color: #414141; float: left; }
.search_submit { width: 60px; padding: 5px; margin: 0; background: #1c1c1c; border: 0; color: #414141; float: right; }

.newsletter_input { width: 248px; height: 16px; padding: 5px; background: #1D1D1D; border: 0; margin: 0 0 5px 0; color: #898989; float: left; }
.newsletter_submit { width: 60px; padding: 5px; margin: 0; background: #1D1D1D; border: 0; color: #898989; float: right; }

Step 9: Add in Cufon codes into your XHTML header

So you’ve come a long way, but there’s still one thing missing – the cufon replacement codes. These are added into the head section of your index.html file.




And you’re done!

And there you have it :) You can take a look at the final product again here and view the source files if you have any questions. Downloading the zip with the PSD, index.html, style.css, cufon files and images can be done by clicking the download button below.

View the live online demo
DOWNLOAD THE FILES HERE (6.09 MB)

Tags: ,