Inerd Hussein - tagged with web-development http://www.ooopx.net/feed en-us http://blogs.law.harvard.edu/tech/rss Sweetcron husseinad@gmail.com Regular Expressions for Dummies http://www.ooopx.net/items/view/2680/regular-expressions-for-dummies

In the first entry of this new series, we'll review the abilities of each symbol.

]]>
Wed, 25 Mar 2009 12:34:00 -0600 http://www.ooopx.net/items/view/2680/regular-expressions-for-dummies
10 Advanced PHP Tips Revisited http://www.ooopx.net/items/view/2615/10-advanced-php-tips-revisited

Here, on the Smashing Editorial team, we always try to meet the expectations of our readers. We do our best to avoid misunderstandings, and we try to spread knowedge and present only the best design practices and development techniques. However, sometimes we do make mistakes. And when we do, we apologize and do our best to correct what we’ve done. In November 2008 we published the article 10 Advanced PHP Tips To Improve Your Programming. Apparently, according to negative comments to the post, it contained some errors and some statements that are just wrong. We sincerely apologize for our mistake, and we are truly sorry for any inconvenience we caused by it. However, this simple apology is not good enough. To solve the problem, we asked Chris Shiflett and Sean Coates, two PHP gurus, to take a closer look at the article, explain its errors and make it perfectly clear what is actually right and wrong in the theory and practice. This article is a professional response to our article published a couple of months ago. 10 Useful PHP Tips Revisited by Chris Shiflett and Sean Coates This article is a rebuttal to 10 Advanced PHP Tips To Improve Your Programming — henceforth referred to as the previous article — published last November here on Smashing Magazine. The introduction sounds intriguing: Listed below are 10 excellent techniques that PHP developers should learn and use every time they program. Unfortunately, the intrigue devolves into disappointment. We disagree with many of the tips, and even when we don’t, the accompanying explanation is weak or misleading. In this article, we go through each and every tip from the previous article and provide our own commentary and evidence, either to validate and clarify the tip, or to refute it. Our hope is that you don’t just accept our opinion, but rather learn enough to form your own. 1. Use an SQL Injection Cheat Sheet This particular tip is just a link to a useful resource with no discussion on how to use it. Studying various permutations of one specific attack can be useful, but your time is better spent learning how to safeguard against it. Additionally, there is much more to Web app security than SQL injection. XSS (Cross-Site Scripting) and CSRF (Cross-Site Request Forgeries), for example, are at least as common and at least as dangerous. We can provide some much-needed context, but because we don’t want to focus too much on one attack, we’ll first take a step back. Every developer should be familiar with good security practices, and apps should be designed with these practices in mind. A fundamental rule is to never trust data you receive from somewhere else. Another rule is to escape data before you send it somewhere else. Combined, these rules can be simplified to make up a basic tenet of security: filter input, escape output (FIEO). The root cause of SQL injection is a failure to escape output. More specifically, it is when the distinction between the format of an SQL query and the data used by the SQL query is not carefully maintained. This is common in PHP apps that construct queries as follows: <?php

$query = "SELECT * FROM users WHERE name = '{$_GET['name']}'";

?> In this case, the value of $_GET['name'] is provided by another source, the user, but it is neither filtered nor escaped. Escaping preserves data in a new context. The emphasis on escaping output is a reminder that data used outside of your Web app needs to be escaped, else it might be misinterpreted. By contrast, filtering ensures that data is valid before it’s used. The emphasis on filtering input is a reminder that data originating outside of your Web app needs to be filtered, because it cannot be trusted. Assuming we’re using MySQL, the SQL injection vulnerability can be mitigated by escaping the name with mysql_real_escape_string(). If the name is also filtered, there is an additional layer of security. (Implementing multiple layers of security is called “defense in depth” and is a very good security practice.) The following example demonstrates filtering input and escaping output, with naming conventions used for code clarity: <?php

// Initialize arrays for filtered and escaped data, respectively. $clean = array(); $sql = array();

// Filter the name. (For simplicity, we require alphabetic names.) if (ctype_alpha($_GET['name'])) { $clean['name'] = $_GET['name']; } else { // The name is invalid. Do something here. }

// Escape the name. $sql['name'] = mysql_real_escape_string($clean['name']);

// Construct the query. $query = "SELECT * FROM users WHERE name = '{$sql['name']}'";

?> Although the use of naming conventions can help you keep up with what has and hasn’t been filtered, as well as what has and hasn’t been escaped, a much better approach is to use prepared statements. Luckily, with PDO, PHP developers have a universal API for data access that supports prepared statements, even if the underlying database does not. Remember, SQL injection vulnerabilities exist when the distinction between the format of an SQL query and the data used by the SQL query is not carefully maintained. With prepared statements, you can push this responsibility to the database by providing the query format and data in distinct steps: <?php

// Provide the query format. $query = $db->prepare('SELECT * FROM users WHERE name = :name');

// Provide the query data and execute the query. $query->execute(array('name' => $clean['name']));

?> The PDO manual page provides more information and examples. Prepared statements offer the strongest protection against SQL injection. 2. Know the Difference Between Comparison Operators This is a good tip, but it is missing a practical example that demonstrates when a non-strict comparison can cause problems. If you use strpos() to determine whether a substring exists within a string (it returns FALSE if the substring is not found), the results can be misleading: <?php

$authors = 'Chris & Sean';

if (strpos($authors, 'Chris')) { echo 'Chris is an author.'; } else { echo 'Chris is not an author.'; }

?> Because the substring Chris occurs at the very beginning of Chris & Sean, strpos() correctly returns 0, indicating the first position in the string. Because the conditional statement treats this as a Boolean, it evaluates to FALSE, and the condition fails. In other words, it looks like Chris is not an author, but he is! This can be corrected with a strict comparison: <?php

if (strpos($authors, 'Chris') !== FALSE) { echo 'Chris is an author.'; } else { echo 'Chris is not an author.'; }

?> 3. Shortcut the else This tip accidentally stumbles upon a useful practice, which is to always initialize variables before you use them. Consider a conditional statement that determines whether a user is an administrator based on the username: <?php

if (auth($username) == 'admin') { $admin = TRUE; } else { $admin = FALSE; }

?> This seems safe enough, because it’s easy to comprehend at a glance. Imagine a slightly more elaborate example that sets variables for name and email as well, for convenience: <?php

if (auth($username) == 'admin') { $name = 'Administrator'; $email = 'admin@example.org'; $admin = TRUE; } else { /* Get the name and email from the database. */ $query = $db->prepare('SELECT name, email FROM users WHERE username = :username'); $query->execute(array('username' => $clean['username'])); $result = $query->fetch(PDO::FETCH_ASSOC); $name = $result['name']; $email = $result['email']; $admin = FALSE; }

?> Because $admin is still always explicitly set to either TRUE or FALSE, all is well, but if a developer later adds an elseif, there’s an opportunity to forget: <?php

if (auth($username) == 'admin') { $name = 'Administrator'; $email = 'admin@example.org'; $admin = TRUE; } elseif (auth($username) == 'mod') { $name = 'Moderator'; $email = 'mod@example.org'; $moderator = TRUE; } else { /* Get the name and email. */ $query = $db->prepare('SELECT name, email FROM users WHERE username = :username'); $query->execute(array('username' => $clean['username'])); $result = $query->fetch(PDO::FETCH_ASSOC); $name = $result['name']; $email = $result['email']; $admin = FALSE; $moderator = FALSE; }

?> If a user provides a username that triggers the elseif condition, $admin is not initialized. This can lead to unwanted behavior, or worse, a security vulnerability. Additionally, a similar situation now exists for $moderator, which is not initialized in the first condition. By first initializing $admin and $moderator, it’s easy to avoid this scenario altogether: <?php

$admin = FALSE; $moderator = FALSE;

if (auth($username) == 'admin') { $name = 'Administrator'; $email = 'admin@example.org'; $admin = TRUE; } elseif (auth($username) == 'mod') { $name = 'Moderator'; $email = 'mod@example.org'; $moderator = TRUE; } else { /* Get the name and email. */ $query = $db->prepare('SELECT name, email FROM users WHERE username = :username'); $query->execute(array('username' => $clean['username'])); $result = $query->fetch(PDO::FETCH_ASSOC); $name = $result['name']; $email = $result['email']; }

?> Regardless of what the rest of the code does, it’s now clear that $admin is FALSE unless it is explicitly set to something else, and the same is true for $moderator. This also hints at another good security practice, which is to fail safely. The worst that can happen as a result of not modifying $admin or $moderator in any of the conditions is that someone who is an administrator or moderator is not treated as one. If you want to shortcut something, and you’re feeling a little disappointed that our example includes an else, we have a bonus tip that might interest you. We’re not certain it can be considered a shortcut, but we hope it’s helpful nonetheless. Consider a function that determines whether a user is authorized to view a particular page: <?php

function authorized($username, $page) { if (!isBlacklisted($username)) { if (isAdmin($username)) { return TRUE; } elseif (isAllowed($username, $page)) { return TRUE; } else { return FALSE; } } else { return FALSE; } }

?> This example is actually pretty simple, because there are only three rules to consider: administrators are always allowed access; those who are blacklisted are never allowed access; and isAllowed() determines whether anyone else has access. (A special case exists when an administrator is blacklisted, but that is an unlikely possibility, so we’re ignoring it here.) We use functions for the rules to keep the code simple and to focus on the logical structure. There are numerous ways this example can be improved. If you want to reduce the number of lines, a compound conditional can help: <?php

function authorized($username, $page) { if (!isBlacklisted($username)) { if (isAdmin($username) || isAllowed($username, $page)) { return TRUE; } else { return FALSE; } } else { return FALSE; } }

?> In fact, you can reduce the entire function to a single compound conditional: <?php

function authorized($username, $page) { if (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username, $page)) { return TRUE; } else { return FALSE; } }

?> Finally, this can be reduced to a single return: <?php

function authorized($username, $page) { return (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username, $page)); }

?> If your goal is to reduce the number of lines, you’re done. However, note that we’re using isBlacklisted(), isAdmin(), and isAllowed() as placeholders. Depending on what’s involved in making these determinations, reducing everything to a compound conditional may not be as attractive. This brings us to our tip. A return immediately exits the function, so if you return as soon as possible, you can express these rules very simply: <?php

function authorized($username, $page) {

if (isBlacklisted($username)) {
    return FALSE;
}

if (isAdmin($username)) {
    return TRUE;
}

return isAllowed($username, $page);

}

?> This uses more lines of code, but it’s very simple and unimpressive (we’re proudest of our code when it’s the least impressive). More importantly, this approach reduces the amount of context you must keep up with. For example, as soon as you’ve determined whether the user is blacklisted, you can safely forget about it. This is particularly helpful when your logic is more complicated. 4. Drop Those Brackets Based on the content of this tip, we believe the author means “braces,” not brackets. “Curly brackets” may mean braces to some, but “brackets” universally means “square brackets.” This tip should be unconditionally ignored. Without braces, readability and maintainability are damaged. Consider a simple example: <?php

if (date('d M') == '21 May') $birthdays = array('Al Franken', 'Chris Shiflett', 'Chris Wallace', 'Lawrence Tureaud');

?> If you’re good enough, smart enough, secure enough, notorious enough, or pitied enough, you might want to party on the 21st of May: <?php

if (date('d M') == '21 May') $birthdays = array('Al Franken', 'Chris Shiflett', 'Chris Wallace', 'Lawrence Tureaud'); party(TRUE);

?> Without braces, this simple addition causes you to party every day. Perhaps you have the stamina for it, so the mistake is a welcome one. Hopefully, the silly example doesn’t detract from the point, which is that the excessive partying is an unintended side effect. In order to promote the practice of dropping braces, the previous article uses short examples such as the following: <?php

if ($gollum == 'halfling') $height --; else $height ++;

?> Because each condition is constrained to a single line, such mistakes might be less likely, but this leads to another problem: inconsistencies are jarring and require more time to read and comprehend. Consistency is such a valued quality that developers often abide by a coding standard even if they dislike the coding standard itself. We recommend always using braces: <?php

if (date('d M') == '21 May') { $birthdays = array('Al Franken', 'Chris Shiflett', 'Chris Wallace', 'Lawrence Tureaud'); party(TRUE); }

?>

You’re welcome to party every day, but make sure it’s deliberate, and please be sure to invite us! 5. Favor str_replace() Over ereg_replace() and preg_replace() We hate to sound disparaging, but this tip demonstrates the sort of misunderstanding that leads to the same misuse it’s trying to prevent. It’s an obvious truth that string functions are faster at string matching than regular expression functions, but the author’s attempt to draw a corollary from this fails miserably: If you’re using regular expressions, then ereg_replace() and preg_replace() will be much faster than str_replace(). Because str_replace() does not support pattern matching, this statement makes no sense. The choice between string functions and regular expression functions comes down to which is fit for purpose, not which is faster. If you need to match a pattern, use a regular expression function. If you need to match a string, use a string function. 6. Use Ternary Operators The benefit of the ternary operator is debatable (there’s only one, by the way). Here is a line of code from an audit we performed recently: <?php

$host = strlen($host) > 0 ? $host : htmlentities($host);

?> Oops! The author actually means to escape $host if the string length is greater than zero, but instead accidentally does the opposite. Easy mistake to make? Maybe. Easy to miss during a code audit? Certainly. Concision doesn’t necessarily make the code any better. The ternary operator may be fine for one-liners, prototypes, and templates, but we strongly believe that an ordinary conditional statement is almost always better. PHP is descriptive and verbose. We think code should be, too. 7. Memcached Disk access is slow. Network access is slow. Databases typically use both. Memory is fast. Using a local cache avoids the overhead of network and disk access. Combine these truths and you get memcached, a “distributed memory object caching system” originally developed for the Perl-based blogging platform LiveJournal. If your application isn’t distributed across multiple servers, you probably don’t need memcached. Simpler caching approaches — serializing data and storing it in a temporary file, for example — can eliminate a lot of redundant work on each request. In fact, this is the sort of low-hanging fruit we consider when helping our clients tune their apps. One of the easiest and most universal ways to cache data in memory is to use the shared memory helpers in APC, a caching system originally developed by our colleague George Schlossnagle. Consider the following example: <?php

$feed = apc_fetch('news');

if ($feed === FALSE) { $feed = file_get_contents('http://example.org/news.xml'); // Store this data in shared memory for five minutes. apc_store('news', $feed, 300); }

// Do something with $feed.

?> With this type of caching, you don’t have to wait on a remote server to send the feed data for every request. Some latency is incurred — up to five minutes in this example — but this can be adjusted to as close to real time as your app requires. 8. Use a Framework All decisions have consequences. We appreciate frameworks — in fact, the main developers behind CakePHP and Solar work with us at OmniTI — but using one doesn’t magically make what you’re doing better. In December, our colleague Paul Jones wrote an article for PHP Advent called The Framework as Franchise, in which he compares frameworks to business franchises. He refers to a suggestion by Michael Gerber from his book “The E-Myth Revisited”: Gerber notes that to run a successful business, the entrepreneur needs to act as if he is going to sell his business as a franchise prototype. It is the only way the business owner can make the business operate without him being personally involved in every decision. This is good advice. Whether you’re using a framework or defining your own standards and conventions, it’s important to consider the value from the perspective of future developers. Although we would love to give you a universal truth, extending this idea to suggest that a framework is always appropriate isn’t something we’re willing to do. If you ask us whether you should use a framework, the best answer we could give is, “It depends.” 9. Use the Suppression Operator Correctly Always try to avoid using the error suppression operator. In the previous article, the author states: The @ operator is rather slow and can be costly if you need to write code with performance in mind. Error suppression is slow. This is because PHP dynamically changes error_reporting to 0 before executing the suppressed statement, then immediately changes it back. This is expensive. Worse, using the error suppression operator makes it difficult to track down the root cause of a problem. The previous article uses the following example to support the practice of assigning a variable by reference when it is unknown if $albus is set: <?php

$albert =& $albus;

?> Although this works — for now — relying on strange, undocumented behavior without a very good understanding of why it works is a good way to introduce bugs. Because $albert is assigned to $albus by reference, future modifications to $albus will also modify $albert. A much better solution is to use isset(), with braces: <?php

if (!isset($albus)) { $albert = NULL; }

?> Assigning $albert to NULL is the same as assigning it to a nonexistent reference, but being explicit greatly improves the clarity of the code and avoids the referential relationship between the two variables. If you inherit code that uses the error suppression operator excessively, we’ve got a bonus tip for you. There is a new PECL extension called Scream that disables error suppression. 10. Use isset() Instead of strlen() This is actually a neat trick, although the previous article completely fails to explain it. Here is the missing example: <?php

if (isset($username[5])) { // The username is at least six characters long. }

?> When you treat strings as arrays, each character in the string is an element in the array. By determining whether a particular element exists, you can determine whether the string is at least that many characters long. (Note that the first character is element 0, so $username[5] is the sixth character in $username.) The reason this is slightly faster than strlen() is complicated. The simple explanation is that strlen() is a function, and isset() is a language construct. Generally speaking, calling a function is more expensive than using a language construct. About the Authors Hi, we’re Chris Shiflett and Sean Coates. We work together at OmniTI (“the most important web company you’ve never heard of”), blog about PHP and other stuff at shiflett.org and seancoates.com, curate PHP Advent, and do the Twitter thing as @shiflett and @coates. (al)

© Smashing Editorial for Smashing Magazine, 2009. | Permalink | 11 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine

Post tags: coding, php, programming, tips, web-development

]]>
Tue, 24 Mar 2009 10:24:00 -0600 http://www.ooopx.net/items/view/2615/10-advanced-php-tips-revisited
The Easiest Way to Use Any Font You Wish http://www.ooopx.net/items/view/2631/the-easiest-way-to-use-any-font-you-wish

CSS 3 is on the horizon, and most developers are getting excited. Thanks to the latest browser updates, developers can begin working with these new font properties - such as @font-face. Unfortunately, these features are limited to a tiny fraction of the overall userbase. At least for the next couple of years, we'll need to continue utilizing the Flash and Javascript alternatives when using fonts. Luckily, a new contender, Cufon, has made the process unbelievably simple. In just a few minutes, I'll demonstrate how to use any font you wish in your web applications. Excited?

]]>
Tue, 24 Mar 2009 09:51:00 -0600 http://www.ooopx.net/items/view/2631/the-easiest-way-to-use-any-font-you-wish
Diving into PHP: 13 http://www.ooopx.net/items/view/2524/diving-into-php-13

At the request of one of our readers, we'll take a look at how to upload files with PHP.

]]>
Wed, 11 Mar 2009 13:46:00 -0600 http://www.ooopx.net/items/view/2524/diving-into-php-13
How I Code Twice As Fast As You http://www.ooopx.net/items/view/2326/how-i-code-twice-as-fast-as-you

In this week's screencast, I'll demonstrate how I utilize text expanding programs to drammatically increase my efficiency.

]]>
Sun, 01 Mar 2009 18:29:00 -0700 http://www.ooopx.net/items/view/2326/how-i-code-twice-as-fast-as-you
6 Interesting online presentations for web developers http://www.ooopx.net/items/view/2277/6-interesting-online-presentations-for-web-developers

If you are looking for free resources to learn Ajax, PHP, CSS and JavaScript take a look at this collection with six interesting online presentations about these topics. The list includes a short introduction to Ajax, how to write modular CSS code, PHP Object Model fundamentals and an overview about the most popular JavaScript libraries.1. Ajax 101 | WorkshopAuthor: Bill Scott | This presentation on SlideShareIntroduction to programming with Ajax. Covers XMLHttpRequest, XML, JSON, JavaScript, HTML, CSS, Dom Scripting, Event Handling with some examples from YUI library.2. Modular CSSAuthor: Russ Weakley | This presentation on Slide ShareA clearly explained modular system that allows you to hide and show CSS rules to specific browsers without the need for extensive hacks or workarounds.3. Understanding the PHP Object ModelAuthor: Sebastian Bergmann | This presentation on SlideShareThis talk will give an overview of PHP's object model, covering both basic OOP concepts such as interfaces, classes, and objects as well as PHP's “magic” interceptor methods.5. jQuery in 15 minutesAuthor: Simon | This presentation on SlideShareA short introduction to jQuery in particular about functions, collections, grabbing values and chaining.6. JavaScript Library OverviewAuthor: Jeresig | This presentation on SlideShareAn interesting Overview about the most popular JavaScript libraries (jquery, prototype, Scriptaculous...) for web designers.

]]>
Sun, 22 Feb 2009 12:59:00 -0700 http://www.ooopx.net/items/view/2277/6-interesting-online-presentations-for-web-developers
Interesting Resources to learn Object Oriented Design http://www.ooopx.net/items/view/2238/interesting-resources-to-learn-object-oriented-design

In this post I want to reply to all my readers which wrote to me in the past weeks asking to me to suggest some interesting resources for beginners to learn Object Oriented Design methodology.This is a small list with some basic references about Object Oriented Design process and it includes an UML guide, some articles about how to write OO javascript, PHP and Perl code. I also included some video tutorials about an useful introduction to OO PHP. If you have some interest link to suggest about this topic, please leave a comment, thanks!UML GuideThe Unified Modeling Language is a standard design specification that is overseen by the Object Management Group (OMG). UML provides a nice framework for designing and analyzing process, structure and their relationships. UML is a collection of the best technical modeling specifications and practices is use today. It is mainly used in developing software requiring Object Oriented Analysis (OOA) and Object Oriented Design (OOD).Design Patterns | Object Oriented DesignDesign Patterns OODesign provides general design principles about Object Oriented Design with some well explained tutorials and examples about this topic.Object Oriented Analysis and DesignOOAD.com provides a lot of interesting link about Object Oriented Analysis and Design resources, forums, links, basic methodology, book and programming roadmap.Object Oriented Design with JavascriptThis is a serie of three article which discuss object-oriented features of JavaScript. Part one provides background on how JavaScript supports the main principles of object-oriented programming. Part two demonstrates how JavaScript constructs can be used to build a class inheritance framework and write scripts supporting a JavaScript class hierarchy. The third and final part shows how to use the JavaScript class framework to build object-oriented client-side abstractions of ASP.NET user controls.- Writing Object-Oriented JavaScript 1/3- Writing Object-Oriented JavaScript 2/3- Writing Object-Oriented JavaScript 3/3Javascript is not a OOP (Object Oriented Programming) Language, but it supports objects, so why don’t use them? It may not be the best thing if you just want to create some small scripts, but as soon as you do a bit more than just reading some data from a form, it can definitely make sense to use objects, because it’s much easier to reuse this code later on. Take a look at this interesting post about this topic from nino.net.- 5 reasons to write object-oriented (oo) javascript- Create Advanced Web Applications With Object-Oriented Techniques- Understanding scope in object oriented JavaScriptObject Oriented Ajax Application DesignGreg Brown explains how to use basic object-oriented techniques to build more robust AJAX applications. The demands on JavaScript as a development platform are growing with the increasing popularity of so-called AJAX applications. The procedural development model commonly used to add basic client-side interactivity to web pages today will not scale to support the level of UI complexity required by these applications. Fortunately, and contrary to popular belief, it is possible to apply object-oriented (OO) design principles in JavaScript, which can help manage this complexity.SUN | The Java TutorialsIf you've never used an object-oriented programming language before, you'll need to learn a few basic concepts before you can begin writing any code. This lesson will introduce you to objects, classes, inheritance, interfaces, and packages. Each discussion focuses on how these concepts relate to the real world, while simultaneously providing an introduction to the syntax of the Java programming language.- What Is an Object?- What Is a Class?- What Is Inheritance?- What Is an Interface?- What Is a Package?- Questions and Exercises: Object-Oriented Programming ConceptsObject Oriented PHP for BeginnersStefan Mischook wrote this practical tutorial to teach total beginners object oriented PHP. So before you begin, get out your favorite PHP code editor and be ready to write and run some object oriented PHP code. You can also download a PDF version of this tutorial or watch the following videos:- Introduction to Object Oriented PHP (4:05)- Why learn Object Oriented PHP (14:46)- Objects and Classes in PHP (5:26)- Build Objects in PHP - Part 1 (9:14)- Build Objects in PHP - Part 2 (9:41)- Build Objects in PHP - Part 3 (6:18)- Calling Functions from Another Class (5:36)Perl Object Oriented ProgrammingMost people are not aware of the fact that Perl has support for object-oriented programming. If you've used another object-oriented programming language such as Java or C++ or been exposed to object-orientation, then object oriented programming in Perl is nothing like that. To do real useful object-oriented programming in Perl take a look at this article.

]]>
Mon, 16 Feb 2009 14:04:00 -0700 http://www.ooopx.net/items/view/2238/interesting-resources-to-learn-object-oriented-design
Building the imgPreview Plugin http://www.ooopx.net/items/view/2194/building-the-imgpreview-plugin

Today, James Padolsey will demonstrate how to build an advanced jQuery plugin.

]]>
Thu, 12 Feb 2009 22:02:00 -0700 http://www.ooopx.net/items/view/2194/building-the-imgpreview-plugin
Interesting html FORM Validators for web developers http://www.ooopx.net/items/view/2195/interesting-html-form-validators-for-web-developers

This post illustrates how to use some interesting HTML Form validators to check FORM fields writing only some lines of HTML and JavaScript code. All these proposal are lightweight, cross-browser and simple to use and customize in your web projects in few minutes.If you have some suggestion about this topic, please leave a comment. Thanks!1. MooTools FormCheckFormCheck is a class that allows you to perform different tests on form to validate them before submission. FormCheck is lightweight, shiny and fast, supports skins (using CSS), 10 different languages, and shows errors as tips. It support basic validation (required, alpha, digit, alpanu, lenght, confirm...), regex validation (phone, email, url) and a lot of options that allow you to customize this class to fit exactly as you want.FormCheck is really simple to implement. In the <head> tag of your page add the folloing lines of code:>Add a link to MooTools Framework:<script type="text/javascript\" src="mootools.js"></script>...choose FormCheck language (in this case english):<script type="text/javascript\" src="formcheck/lang/en.js"></script>...include the FormCheck script:<script type="text/javascript\" src="formcheck/formcheck.js"></script>... and initialize FormCheck using this code:<script type="text/javascript\">window.addEvent('domready', function(){new FormCheck('formular');});</script>You can use default CSS theme for your form using this code:<link media="screen" type="text/css" href="formcheck/theme/classic/formcheck.css" rel="stylesheet" />At this point, create a form in the tag <body> of your page:<form action="#" method="post" id="formular" class="formular"><form>... and add some fields into the form like these:<input type="text" name="user" class="validate['required','length[4,20]','alphanum'] text-input" />How you can see in the previous code, the syntax to use this validator is really simple. You have to add this code into attribute "class" of the input field:class="validate['required','length[6,16]','alphanum'] text-input" />...it means: validate this field; this field is required, min lenght is 6 chars and max lenght is 16 chars; this is an alphanumeric field. When an user submit the form, the result is the following:Simple No? Take a look at the demo.2. Live Validation LiveValidation is a small open source javascript library for making client-side validation quick, easy, and powerful. It comprises of two main parts. Firstly, it provides developers with a rich set of core validation methods, which can also be used outside the context of forms. Secondly, it provides your visitors with real-time validation information as they fill out forms, helping them to get it right first time, making the forms easier, quicker and less daunting to complete. In this example you can see how to match the value contained in two fields.In the <head> tag add a link to the livevalidation script:<script type="text/javascript\" src="livevalidation_standalone.compressed.js"></script>...create two fields:<input type="password" id="password" /><input type="password" id="confirmPassword" />...and than add this script below the second input field:<script type="text/javascript\"> var confirmPassword = new LiveValidation('confirmPassword'); confirmPassword.add(Validate.Confirmation, {match: 'password'}); </script> This is the result if the content in the first field matches the content in the second field:...and this is the result if the content doesen't match:Take a look at this page for a full documentation support about LiveValidation.3. ProtoFormProtoForm is an unltra lightweight, unobtrusive cross-browser and very easy to customize form validation + submit with Ajax based on prototype.js framework. It checks required fields and validate Email, Date, Telephone number and Url, send data and shows response with Ajax, highlight the form field on focus and on error.You can implement this script on your page with only some lines of code. In the <head> tag add a link to the Prototype and ProtoForm script:<script type="text/javascript\" src="prorotype.js"></script><script type="text/javascript\" src="prorotype.js"></script>Then, create a form within a div with ID="box":<div id="box"><form action="#" method="post" id="send" class="validate"></form></div>At this point add some input field into the form like the following:<input type="text" id="email_Req_Email" name="email" title="Required! Enter a valid email address!" />In the propery id I highlighted in bold validation options (_Req, _Email). The ID property of fields you have to validete will be something like: name + _option1 + _option2 +....The "title" attribute is used to display an error message. For a full documentation about this script take a look at the official page.That's all. If you have some suggestions add a comment, thanks!

]]>
Thu, 12 Feb 2009 10:25:00 -0700 http://www.ooopx.net/items/view/2195/interesting-html-form-validators-for-web-developers
Exactly How to Use CSS Sprites http://www.ooopx.net/items/view/2128/exactly-how-to-use-css-sprites

For Day 2, Andres will be teaching us how to use CSS sprites to improve load times and decrease the number of HTTP requests. As always, feel free to ask any questions in the comments area.

]]>
Mon, 09 Feb 2009 13:06:00 -0700 http://www.ooopx.net/items/view/2128/exactly-how-to-use-css-sprites
Simple process to estimate times and costs in a web project http://www.ooopx.net/items/view/2070/simple-process-to-estimate-times-and-costs-in-a-web-project

After my previous article about a structured process to develop a web application I received some requests from my readers which asked to me to dedicate a post about how to estimate times and costs of a web project.In this articles I want to illustrate a simplified top-down process to estimate times and costs of a web process using a simple spreadsheet (in this example I used Google Spreadsheets but if you prefer you can use Microsoft Excel, OpenOffice Spreadsheet or a free online service such as Zoho or EditGrid).Process main phasesIn this simple top-down estimate process you can identify five main phases:1. Define Activities2. Define Task3. Define Human Resources4. Assign Human Resources to Tasks5. Estimate times and costsThe process start with a general definition of macro-activities and with a detailed definition of tasks, human resources used, times and costs related to each task.1. Define ActivitiesIn this first phase you have to define the main activities which compose your project:For example, in a generic web project you can identify the following main activities:1. Requirements definition2. Design3. Implementation4. Test5. ReleaseIn my spreadsheet I created a new sheet called Activityes and I added the following two columns:A: WBS (work breakdown structure), the ID of each activity/task;B: Activity name.Next step is to detail each activity with a certain number of specific tasks.2. Define TasksEach activity is composed from some tasks. Each task is a smaller piece of work which composes a main activity:In the spreadsheet you can add new tasks adding new rows below related main activity. I suggest you to use a different format to highlight tasks from activities how I used in the following example:1. Requirements definition1.1 Define application scope1.2 Define technical requirements2. Design2.1 Application Map2.2 Database Entity relationship model...3. Implementation3.1 SQL code3.2 HTML code3.3 CSS code...3. Define Human ResourcesNext step is defining human resources in terms of category, seniority and hourly cost:Each category has a specific hourly cost related to specific seniority. You can organize these information using a simple category/seniority matrix. For example if you have to estimate a big/medium size project you can identify the following categories:- Analyst- Programmer- Project manager- ...and the following seniorities:- Junior- Senior- ...Now, define hourly cost for each category/seniority combination (in a more complex project you can also define a standard rate and an overtime rate for each combination). In the spreadsheet you can create the table above in a new sheet called Resources in the same spreadsheet. At this point you have two sheets:A first sheet with activities and a second sheet with resources. In this way when you assign resources to tasks you can link the cost of a specific resource with a reference formula (=). This is a good practice because if you have to change the cost related to a specific combination category/seniority, you can do it only once in the sheet "Resources" and automatically all changes will be reported in all instances (task) which use that combination in the sheet "Activities"4. Assign Human Resources to TasksNext step: assigning one or more resources to each task estimating the effort which a task requires. This is a very delicate activity because you have to calibrate the right combination between category and seniority of resources you want to use in your project in order to estimate correctly project times and costs.In the spreadsheet, in the sheet "Activities" create the following three columns:1. Num (number of resources assigned to a task)2. Category3. SeniorityThis is the result:You can add different resources to each task (different category or different seniority) simply adding a row below the task name (for example take a look at "Define application scope" where I added 1 analyst junior in the first row and 1 analyst senior in a new row below the task name).5. Estimate Times and CostsNow, for each resource, estimate the daily effort (Hours/day column), number of days (Days colum), get cost related to category/seniority combination from the sheet "Resources" using a reference formula (Hourly Cost column), and calculate Total costs:For each task (row) Total Cost is equal to:Total Cost = Hours/day * Hourly Cost * DaysTake a mind some task could have specific costs which are indipendent from the number of resources you assign to that task. You can add this costs adding a new column to the left of the column Total Cost called "Additional Costs".In this case Total Cost will be equal to:Total Cost = (Hours/day * Hourly Cost * Days) + Additional CostThat's all. Take a look at the spreadsheet or copy it in your Google Documents account to reuse it.Take also a look at these posts:- Structured process to develop a web application- Google Spreadsheets Gantt Chart (Microsoft Project-like)- Google Spreadsheets: formulas tutorial- Google Spreadsheets Tips: Add custom charts- Project Management: Excel Gantt Chart TemplateI hope you'll find this post useful. If you have some suggestions about this process or if you want to suggest some interesting link related to this topic please add a comment, thanks!

]]>
Thu, 05 Feb 2009 16:59:00 -0700 http://www.ooopx.net/items/view/2070/simple-process-to-estimate-times-and-costs-in-a-web-project
Building A Login App http://www.ooopx.net/items/view/1916/building-a-login-app

For today's massive video tutorial, we'll be working with sessions, classes, prepared statements, and mysqli to build a login system for a small site.

]]>
Thu, 29 Jan 2009 16:14:00 -0700 http://www.ooopx.net/items/view/1916/building-a-login-app
Beautiful datepickers and calendars for web developers http://www.ooopx.net/items/view/1821/beautiful-datepickers-and-calendars-for-web-developers

Datepickers and calendars are elements you need often to implement in web applications with some advanced features. Starting from zero can be a very hard work, expecially if you don't have big familiarity with Javascript.This list include some of my preferred simple to implement and customize datepickers and calendars, for beginner and professional web developers. I suggest you to try in order to simplify your developing process and save a lot of time reusing code already written. The result is really amazing!1. jQuery datepickerThis is a default datepicker implemented using jQuery UI which is tied to a standard form input. The calendar opens in a small overlay onFocus and closes automatically onBlur if a date if selected. You can also use the keyboard to drive the datepicker:- page up/down - previous/next month- ctrl+page up/down - previous/next year- ctrl+home - current month or open when closed- ctrl+left/right - previous/next day- ctrl+up/down - previous/next week- enter - accept the selected date- ctrl+end - close and erase the date- escape - close the datepicker without selection2. jQuery Date Picker pluginThis is an other interesting jquery datepicker with a lot of options and easy to fit in your web application.- Flat mode - as element in page- Multiple calendars in the component- Allows single, multiple or range selection- Mark dates as special, weekends, special days- Easy to customize the look by changing CSS- Localiation for months' and days' names- Custom day to start the week- Fits into the viewport3. Calendar MooToolsCalendar is a Javascript class that adds accessible and unobtrusive date-pickers to your form elements. This class is a compilation of many date-pickers implemented and completely re-written for Mootools.This class include all the features that have been most useful while streamlining the class itself to keep it as small as possible. Take a look about how Calendar might enhance the accessibility, usability and validation of form elements on your website.4. YUI CalendarYUI Calendar uses Yahoo! UI library to implement a default calendar you can use as datepicker. It's very simple to implement, highly customizable and the final result is clean and elegant.This basic example walks you through the steps needed to get a default Calendar up and running. It covers the set of file dependencies which need to be included as well as the basic markup and JS code required to get you started.5. Unobtrusive Date-Picker WidgetThis elegant datePicker is accessible using the keyboard, requires no embedded JavaScript blocks, uses no pop-up windows and is suitable for use within documents served as application/xhtml+xml. Take a look here for the demo.A quick feature list:- Fully keyboard accessible- Multiple date formats and date dividers supported- Unobtrusive and nameSpace friendly- Fully skinnable with CSS- Both upper and lower date limits can be set- Certain days of the week can be disabled- Certain, dates can be disabled/enabled (and wildcards used to stipulate the dates in question)- Includes “smart” localisation (16 languages currently available)- Bespoke days of the week can be highlighted- Works with single text inputs, split text inputs or select lists- It’s free to use, even commercially (Released under a CC share-alike license)6. ScalScal is a simple, javascript calendar/date picker based on the Prototype js library, simple to implement and to customize using default themes or creating custom themes changing CSS some lines of CSS code.7. Ext JS Extension:CalendarExt JS Extension:Calendar is a daily, weekly, monthly, quarterly, yearly calendar extension which you can use to implement very complex applications Google Calendar or Outlook Calendar like.8. jPintjPint is a set of libraries designed by Journyx to allow developers to build web-based applications that look and feel as much like native iPhone apps as possible, while retaining the ability for those apps to be used by people who, for whatever reason, don't actually have an iPhone handy. Take a look at this nice iPhone like calendar.

]]>
Sat, 24 Jan 2009 14:54:00 -0700 http://www.ooopx.net/items/view/1821/beautiful-datepickers-and-calendars-for-web-developers
A Detailed Introduction Into the 960 CSS Framework http://www.ooopx.net/items/view/1694/a-detailed-introduction-into-the-960-css-framework

We'll be taking a look at the benefits of using a CSS framework when building web applications.

]]>
Wed, 14 Jan 2009 15:14:00 -0700 http://www.ooopx.net/items/view/1694/a-detailed-introduction-into-the-960-css-framework
Structured process you must know to develop a web application http://www.ooopx.net/items/view/1620/structured-process-you-must-know-to-develop-a-web-application

Developing a web application it's a hard work which requires much time you have to spend doing a myriad of things. If you don't use a methodic approach, especially in case of a complex project, you run the risk of losing sight of the project, not respecting times of delivery and wast your time for nothing.This post illustrates a structured process which helps you to simplify the approach to develop your web applications saving time and more efficiently.Process main phasesIn a generic web application developing process you can identify five main phases:1. Requirements definition2. Design3. Implementation4. Test5. ReleasePlanning and Monitoring is a "cross phase" which follows developing process defining a project plan composed from a list of activities which you have to monitor during project execution. For each activity you have to define a set of information useful for its monitoring, for example:- owner- duration- costs- ...Take a look at these posts I wrote some time ago about how to implement a project plan with a Gantt chart using Excel or Google Spreadsheets:How to organize a project planExcel Gantt chart templateImplement a project plan and manage activities with Google Spreadsheets1. Requirements DefinitionIn this first phase you have to define the scope and needs of your web application in terms of what your application must do, main features and technical requirements:ScopeIn order to define the scope of your web application is sufficient to compile a detailed list with a clear description of application features. At the moment is not important "how" you'll realize them but "what" you have to realize!NeedsNeeds analysis is a crucial part of developing process. In this step you have to estimate your potential traffic, choose a server-side language (PHP, ASP, Coldfusion...), database, choose an hosting service... Place a big attention on not to overrate/underrate your estimates! Evaluate every thing with a right balance between times, costs and objectives!2. DesignAfter requirements definition phase, you have to "design" your application with a clear project. In this phase you can identify the following steps:Design: Application MapAn application map contains just meaningful and essential information about the structure of your application: pages (represented with some blocks) and main relationships between them. Your application map could be something like this:In this way you have a map with some "locations" (pages) and a "path" (relationships between pages) which you simply have to follow in order to proceed, page-by-page, to implement your application in the next phase. In this way you'll save a lot of time, having clear in mind what you have to implement.Design: DatabaseOk, now it's time to design application database. A simple way to do that it's using a entities-relationships (ER) model. In general you can follow this order: define first tables, than attributes and relationships between tables. Your ER model will be like this:1:1 expresses the cardinality of a relationship (in this case for example 1 user is assigned only to 1 task, 1 user live only in a city). For more information about this topic take a look at my old posts:Define the entities-relationships modelA correct approach to define relationships between database tables10 Useful articles about Database designDesign: Page StructureNext step is to design an approximate structure of the page, identifying all main sections using a name (for example #header, #navbar, #mainContent, #sidebar).Design: Server-side LanguageTaking a mind an object-oriented approach for developing your application, you can defining classes, functions and all server-side features you need. Remember... that's not the "implementation" but a way to have a "guide" for that you'll implement in the next phase.Design: JS FrameworkIn this step choose a JavaScript Framework (jQuery, Scriptaculous, MooTools...), than pass to identify the main features you want to implement (drag and drop, animation effects...) compiling a simple list which associates each specific feature to one or more pages identified in you application map.A this point design phase is completed. Let's start with implementation!3. ImplementationOk.. now starts the real challenge because "implementation" is the realization of your application. You can divide this phase in the following steps:Implementation: DatabaseCreate a new database and write SQL code defining tables, attributes and relationships. In the past I dedicated some posts about this topic. Take a look at the following links for more information:How to use PHP and SQL to create DB tables and relationshipsCreate tables and relationships with SQLImplementation: HTMLUse the page structure you defined in Design phase to implement HTML code:<div id="header"> </div><div id="navbar"> </div><div id="mainContent"> </div><div id="sidebar"> </div><div id="footer"> </div>This is the moment to add all HTML elements you need in sections identified during Design phase. For example if the sections mainContent contains a post with a title, a text body and post tags, add these elements:<div id="header"> </div><div id="navbar"> </div><div id="mainContent"><h1><!-- Post title --></h1><p><!-- Text body --></p><small><!-- Post tags --></small></div><div id="sidebar"> </div><div id="footer"> </div>Implementation: CSSWhen the main structure is ready, start to write CSS code to add styles to your application. If you need some suggestions about how to write a better CSS code take a look at these posts:CSS coding: semantic approach in naming conventionUseful guidelines to improve CSS coding and maintainabilityImplementation: Server-side languageImplement application class, application functions, DB interactions, queries, and every thing requires a server-side interaction.Implementation: JavaScriptImplement Ajax features (drag and drop, animation effects...) using the framework you chose in Design phase (jQuery, Scriptaculous, MooTools...).4. TestDuring this phase you have to "stress" your application executing your code in various conditions (for example using different browser). Your objective is to detect all application bugs and fix them before the final release.Remember, this process must be methodic and require a lot of patience! Test each page and each features (also in this case can help you application map to proceed in a certain order). If you find a bug during test esecution, fix it modifying the code and than proceed with the final validation (an ulterior test) of the code.5. ReleaseFinally you are ready to release your application! Publish it in a test folder and make a final test. If it's all ok proceed to the final release.That's all. I hope this post can halp all of you which asked to me to add a post about this topic.If you have suggestions to improve this process add a comment! Thanks :)

]]>
Fri, 09 Jan 2009 12:12:00 -0700 http://www.ooopx.net/items/view/1620/structured-process-you-must-know-to-develop-a-web-application
10 Promising Free Web Analytics Tools http://www.ooopx.net/items/view/1476/10-promising-free-web-analytics-tools

Web analytics is the process of gathering and analyzing your web content’s data in order to glean meaningful information about how your site is being utilized by your users. There are plenty of Web analytics applications out there, and you probably already know the big guns such as Google Analytics, Crazy Egg, and remote-site services such as Alexa and Compete. We go off the trodden path and explore a few lesser-known Web analytics options. In this article, you’ll find 10 excellent and free tools and applications to help you gather and analyze data about your web content. 1. Piwik Go to Live Demonstration of Piwik. Piwik is an open-source Web analytics application developed using PHP and MySQL. It has a "plugins" system that allows for utmost extensibility and customization. Install only the plugins you need or go overboard and install them all – the choice is up to you. The plugins system, as you can imagine, also opens up possibilities for you to create your own custom extensions. This thing’s lightweight – the download’s only 1.9MB. 2. FireStats Go to Live Demonstration of FireStats. FireStats is a simple and straight-forward Web analytics application written in PHP/MySQL. It supports numerous platforms and set-ups including C# sites, Django sites, Drupal, Joomla!, WordPress, and several others. Are you a resourceful developer who needs moar cowbell? FireStats has an excellent API that will assist you in creating your own custom apps or publishing platform components (imagine: displaying the top 10 most downloaded files in your WordPress site) based on your FireStats data. 3. Snoop

Snoop is a desktop-based application that runs on the Mac OS X and Windows XP/Vista platforms. It sits nicely on your system status bar/system tray, notifying you with audible sounds whenever something happens. Another outstanding Snoop feature is the Name Tags option which allows you to "tag" visitors for easier identification. So when Joe over at the accounting department visits your site, you’ll instantly know. 4. Yahoo! Web Analytics

Yahoo! Web analytics is Yahoo!’s alternative to the dominant Google Analytics. It’s an enterprise-level, robust web-based third-party solution which makes accessing data easy especially for multiple-user groups. It’s got all the things you’d expect from a comprehensive Web analytics tool such as pretty graphs, custom-designed (and printable) reports, and real-time data tracking. 5. BBClone Go to Live Demonstration of BBClone. If you’re looking for a simple, server-side web application that doesn’t rely on third-party services to monitor your data, check out BBClone - a PHP-based server application that gives you a detailed overview of website traffic and visitor data. It supports language localization for 32 languages like English, Chinese, German, and Japanese. It easily integrates with popular publishing platforms like Drupal, WordPress, and Textpattern. Since it’s logfile-based, it doesn’t require you to use a server-side relational database. 6. Woopra

Woopra is a Web analytics application written in Java. It’s split into two parts which includes a desktop application for data analysis/exploration and a web service to monitor website statistics. Woopra has a robust user interface, an intuitive management system that allows you to run it on multiple sites and domains, and even a chat feature so that you can gather non-numerical information by talking to your site users. Woopra is currently in beta and requires you to request for a private beta registration. 7. JAWStats

JAWStats is a server-based Web analytics application that runs with the popular AWStats (in fact, if you’re on a shared hosting plan - AWStats is probably already installed). JAWStats does two things to extend AWStats - it improves performance by reducing server resource usage and improves the user interface a little bit. With that said, you can’t go wrong with just using AWStats either if you’re happy with it. 8. 4Q

A large part of Web analytics deals with number-crunching and numerical data. Raw numbers tells only part of the story and it’s often helpful to perform analytics by way of interacting with actual users. 4Q developer Avinash Kaushik puts it perfectly when he said: "Web analytics is good at the ‘What’. It is not good at the ‘Why’".4Q is a simple surveying application focused on improving your traditional numerical Web analytics by supplementing it with actual user feedback. Check out this YouTube video on how easy it is to set up 4Q. 9. MochiBot

MochiBot is a free Web analytics/tracking tool especially designed for Flash assets. With MochiBot, you can see who’s sharing your Flash content, how many times people view your content, as well as helping you track where your Flash content is to prevent piracy and content theft. Installing MochiBot is a breeze; you simply copy a few lines of ActionScript code in the .FLA files you want to monitor. 10. Grape Web Statistics Go to Live Demonstration of Grape Web Statistics. Grape Web Statistics is a simple, open-source application geared towards web developers. It has a clean and usable interface and has an Extensions API to extend and customize your installation. It uses PHP for the backend and you can run it on any operating system that runs PHP. Let’s talk about it. What Web analytics software do you use, and why? Do you have any extensive experience in using any of the above application? Share it with all of us in the comments! Further reading

Read the definition of Web analytics according to Wikipedia. Interested in the topic of Web analytics? Check out The Web Analytics Association. Learn more about the launch of Woopra from this Mashable post which includes a video interview. Read more about Piwik from this Read Write Web article.

Related content

7 Incredibly Useful Tools for Evaluating a Web Design 15 Tools for Monitoring a Website’s Popularity Graphing/Charting Data on Web Pages: JavaScript Solutions 10 Tools for Evaluating Web Design Accessibility 6 Tools to Help You Analyze a Web Host

]]>
Fri, 02 Jan 2009 08:20:00 -0700 http://www.ooopx.net/items/view/1476/10-promising-free-web-analytics-tools
css tips & tricks for internet explorer http://www.ooopx.net/items/view/1592/css-tips-amp-tricks-for-internet-explorer

Alright, so we’ve all been there.   You’re working on developing a new site, and it’s looking perfect in Mozilla and Safari…then you try it IE and…yeah, it’s a completely different site!  This can be a huge frustration for many designers/developers looking to push the boundaries of web design and functionality, or honestly it can even loom over the simplest of tasks. So I have decided to share a little bit of discovery for some solutions to web sites appearing differently in IE than other popular browsers and they can all be done with CSS and/or JavaScript.  The issues I will cover are as follows:

3px gap issue on images Styling per browser via CSS .png compatibility issue in IE6

  1. 3px gap issue on images Ok, so really this is an easy fix.  In your CSS just add the following:

img { vertical-align: bottom; }

That’s it, this should fix any 3px gap issues with your images in IE. 2. Styling per browser via CSS This little trick has saved my life so many times.  These 2 markups in your CSS will allow to set styles to be applied to only particular browsers.  Take the following for example: Your CSS-

wrapper {

margin: 0px; background: #fff url('../images/bg.jpg') no-repeat; padding: 10px; }

Now lets say that this styling works great for firefox and safari, but not IE. Maybe the padding needs to be adjusted to 15px instead of 10 for it to look right. Well to fix this we will just leave our CSS above as is, but below it we will write the style again but with the markup *html before it, like so: Adjusted CSS, with styling specifically for IE 6-

wrapper {

margin: 0px; background: #fff url('../images/bg.jpg') no-repeat; padding: 10px; }

*html #wrapper { padding: 15px; }

Notice that the only line rewritten is the padding line, that was the only adjustment we needed to make in IE.  Explorer will still read the read of the styling from the string above. Now lets say that we’ve adjusted it and it now looks good in firefox, safari, and IE 6…but now it’s all messed up in IE7. IE7 won’t read the markup of *html, we will need to add another adjustment to the CSS. We will do exactly what we did before, but this time we will use the markup *+html. With this placed in front of our string, on IE7 will read it. So lets say we needed to make the padding 20px for IE7, it would now look like this: Adjusted CSS, with styling specifically for IE 6 and IE7-

wrapper {

margin: 0px; background: #fff url('../images/bg.jpg') no-repeat; padding: 10px; }

*html #wrapper { padding: 15px; }

*+html #wrapper { padding: 20px; }

  1. .png compatibility issue in IE6 This is a frustrating one, with 20% of all visitors to your site still using IE6, you might want to think about making your site compatible with IE6, or you just might want to use tough love and force them to finally upgrade to IE7…I’ll leave that decision up to you.  Either way, IE6 is very limiting when it comes to designing, in that it does not support transparent .png files.  The use of transparent .png’s have opened up a wonderful world of possibilities for creating beautiful websites, but that dang 20% of IE6 users will just see those blasted gray boxes!  Frustrating, but there is light at the end of the tunnel, or at least a little JavaScript to help out, until everyone finally wakes up and decides to upgrade. Just add this JavaScript to your site and say goodbye to those ugly gray boxes and hello to a world of IE6 actually displaying your site properly. So download this file, then upload it to your site and a reference it in the head code like so:

<script type="text/javascript" src="js/png.js"></script>

*There is only minor side note, you still won’t able to use .png files as background images in IE6. For that they will just have to upgrade to IE7. So there you have it, just a few little tips and tricks to make life working in IE a little smoother and hopefully things will progress with browser compatability in the near future but until then…hack away!  Please feel free to let me know your comments or any question you may have.

]]>
Fri, 26 Dec 2008 11:30:00 -0700 http://www.ooopx.net/items/view/1592/css-tips-amp-tricks-for-internet-explorer