7 ways to tell your css has gone mental

I work on big sites almost exclusively so my techniques are all about wrangling tens of thousands of lines of code into a few thousand. When deadlines loom or you work with a staff of various skill levels css begins to loose its organization.

So here are a few things to look for to know its time to reorganize your code.

  1. When !important becomes a way of life. When the only way to get a piece of code to to work is to wrap !important to the end of every line, your css has gone mental.
  2. When you scroll through the style definitions and see !important sprinkled liberally throughout the styles. Your code has definitely gone mental. Seriously if there are so many clashing definitions that only an !important can solve it you need to look into taking a BEM and SMACSS approach and flatten your definitions.
  3. If you need to change a color and have to do a find and replace to get to them all your code has gone mental. It is time to preprocess your css. I prefer Sass just because it has super powers, but Less is almost as good. Preprocessors allow you to use variables so you can keep all your definitions in one place and reference it everywhere.
  4. If additions to classes end up in a jumble at the end of a file it has gone mental. Choose a technique that makes it easy to find the classes that you need to change. Preprocessors allow you to break your styles into as many files you need to keep your css organized. Sass to the rescue again.
  5. When style definitions are nested five levels deep you know your code has gone mental. Use BEM naming conventions and ideas to flatten your styles and give all your elements a class name.
    Distinct modules should be able to live on any page in any location and maintain their styling. Doing this will help break your code down into manageable chunks.
  6. When the the slowest part of your site is how fast it renders the styles you know it has gone mental. When styles get too complex it can slow down the site and leave it hug half broken till it finishing going through all the exceptions from the nested rules. Again flattening your rules and proper naming would go a long way toward resolving that. BEM has helped me organize my code into something a bit more manageable over the long term.
  7. using # over . will drive your site mental. Specifity will ruin your day ,but adding IDs among your definitions will just overpower any classes and make fixes that much harder. Avoid them on anything but page structure. Using IDs on modules may be moved to new pages will just confuse things when duplicate IDs start showing up on the same page. It will render but it may break js and cause conflicts when there is an ID and a class, but you are only working on the class. Consolidate styles into just the classes helps that.

Here is a great talk about organizing CSS using OOCSS, SMACSS and BEM and SASS. OOCSS has been absorbed into SMACSS and BEM principles so it isn’t mentioned as much any more.

Javascript Classes

Despite what you might believe JavaScript does not actually have classes. But you can emulate them using functions, variables, prototypes and closures.

There are many ways of making classes each has advantages and limitations so I will go over each of them in turn.

Let’s start at the beginning with the most basic element. The Variable.

 
var widget = "orange";
A variable can hold many kinds of data and properties but the most important thing to remember about it is that it can hold anonymous objects.  And in javascript everything is an object. Even “orange” is an object with a set of properties and methods that I could use to manipulate it. But that is for another lesson. Just keep in mind that variables are able to point to elements with and without names.

The next most important element is the Function.

function widget(color) {
    return color;
}

The function allows me to store a series of commands, variables and even further functions. The problem with this is that all of it is public. But there is a trick to solve that.

The first way to create a class is with a function.

function widget(color){
    this.color = color;
    this.price = 3.95;
    this.name = "widget";
    this.whatIsThis = function(){
        return 'this is a " + this.name;
    }
}

This is obviously a function. But we can use it like a class to create multiple widgets by instantiating it.

var box - new widget("blue");
box.name = "box";
console.log(widget.whatIsThis());
console.log(box.whatIsThis());

As you can see this doesn’t actually affect the widget. It is still the same. By instantiating it we can use it like a class to duplicate it into individual objects with all of the same properties and methods of the original function.

One of the problems should be obvious. I was able to change the name. Nothing is private using this version.  Another problem is that class is completely recreated when instantiated.  You may not want to waste the overhead recreating every method and property, especially in larger applications. whatIsThis() is a perfect example. It is always the same and it doesn’t store any values. There is a way to optimize this class using prototype.

function widget(color){
    this.color = color;
    this.price = 3.95;
    this.name = "widget";
}

widget.prototype.whatIsThis = function(){
    return 'this is a " + this.name;
}

By adding whatIsThis() using prototype it uses less overhead.  The method only exists on the original class, in this case widget. But all the objects created from it can still call whatIsThis() since it is inherited through prototype. Otherwise it is used the same as the previous version.

You can also add multiple properties using prototype with curly brackets.

widget.prototype = {
    whatIsThis: function(){
        return "this is a " + this.name;
    },
    weight: "1 unit",
    size: "1 Square meter"
}

 

var box - new widget("red");
box.name = "box";
console.log(widget.whatIsThis());
console.log(box.whatIsThis());

The second way to make a class is to use an object literal.

var widget = {
    color:"red",
    price: 3.95,
    name: "widget',
    whatIsThis: function(){
        return "This is a " + this.name;
    }
}

An object literal unlike a function cannot be instantiated since it effectively builds the object at the instance.

Now I had mentioned being able to make the methods and properties of a object private. To do that we have to use another design pattern, called a Module.

var widget = (function(){
  var price = 3.95;
  var name = 'widget';
  var color = 'blue';
  return {
      name: name,
      color: color,
      whatIsThis: function () {
        return 'This is a ' + this.name;
      }
   };
})();

This uses what is called a closure. The parenthesis enclosing the function cause it to be evaluated as an expression. That is it runs the function and looks for the result. Usually once it runs all the properties and methods inside of it would be lost instead it is passed on to the following parenthesis. This keeps the variables alive but they are  unreachable. The properties and methods returned get attached to the variable name and can be called normally. This means that I can call whatIsThis() or change the color. The name property, since it wasn’t returned, is unreachable since it is out of scope.

There is also ways to create empty objects that you can then attach properties and methods to.

These are collectively known as Constructor Patterns.

var widget = {};

This is the first one. We used this before to create a object literal. Since it is built into a variable it is instantiated at the time of creation.

 

var widget = Object.create(Object.prototype);

var widget = new Object();

These are new but work the same way as the pervious way. All three of these work like singletons since they are all instantiated at creation.

To add properties and methods you can use dot syntax or square bracket syntax.

widget.color = "yellow";

This will create a property color in widget and assign it the color  yellow.

 

widget[name] = "widget";

This works the same as the previous one and will assign a value to the property name.

 

widget.whatIsThis = function(){
    return "I am a " + this.name;
}

The method created this way works the same as the standard function.

This is the first of many articles on classes and design patterns. If you are interested in learning more about object literals check out Rebecca Murphey’s article. It is a great read. If you want to learn some more on Singletons check out this IBM article on their usage here.

MySQL Cheat Sheet

LOGIN

mysql -u root -p

CREATE USER

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

CHANGE USER PASSWORD

SET PASSWORD FOR 'bob'@'%.example.org' = PASSWORD('cleartextPassword');

 

Query

SELECT * FROM table
SELECT * FROM table1, table2, ...
SELECT field1, field2, ... FROM table1, table2, ...
SELECT ... FROM ... WHERE condition
SELECT ... FROM ... WHERE condition GROUP BY field
SELECT ... FROM ... WHERE condition GROUP BY field HAVING condition2
SELECT ... FROM ... WHERE condition ORDER BY field1, field2
SELECT ... FROM ... WHERE condition ORDER BY field1, field2 DESC
SELECT ... FROM ... WHERE condition LIMIT 10
SELECT DISTINCT field1 FROM ...
SELECT DISTINCT field1, field2 FROM ...

SELECT ... FROM t1 JOIN t2 ON t1.id1 = t2.id2 WHERE condition
SELECT ... FROM t1 LEFT JOIN t2 ON t1.id1 = t2.id2 WHERE condition
SELECT ... FROM t1 JOIN (t2 JOIN t3 ON ...) ON ...
SELECT ... FROM t1 JOIN t2 USING(id) WHERE condition

 

Conditionals

field1 = value1
field1 <> value1
field1 LIKE 'value _ %'
field1 IS NULL
field1 IS NOT NULL
field1 IN (value1, value2)
field1 NOT IN (value1, value2)
condition1 AND condition2
condition1 OR condition2

 

Data Manipulation

INSERT INTO table1 (field1, field2, ...) VALUES (value1, value2, ...)
INSERT table1 SET field1=value_1, field2=value_2 ...

DELETE FROM table1 / TRUNCATE table1
DELETE FROM table1 WHERE condition

— join:

DELETE FROM table1, table2 WHERE table1.id1 = table2.id2 AND condition

UPDATE table1 SET field1=new_value1 WHERE condition

— join:

UPDATE table1, table2 SET field1=new_value1, field2=new_value2, ...
WHERE table1.id1 = table2.id2 AND condition

 

Browsing

SHOW DATABASES
SHOW TABLES
SHOW FIELDS FROM table / SHOW COLUMNS FROM table / DESCRIBE table / DESC table / EXPLAIN table
SHOW CREATE TABLE table
SHOW CREATE TRIGGER trigger
SHOW TRIGGERS LIKE '%update%'
SHOW PROCESSLIST
KILL process_number
SELECT table_name, table_rows FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '**yourdbname**';
$ mysqlshow
$ mysqlshow database

 

Create / delete / select / alter database

CREATE DATABASE [IF NOT EXIST] mabase [CHARACTER SET charset] [COLLATE collation]
CREATE DATABASE mabase CHARACTER SET utf8
DROP DATABASE mabase
USE mabase

ALTER DATABASE mabase CHARACTER SET utf8

 

Create/delete/modify table

CREATE TABLE table (field1 type1, field2 type2, ...)
CREATE TABLE table (field1 type1, field2 type2, ..., INDEX (field))
CREATE TABLE table (field1 type1, field2 type2, ..., PRIMARY KEY (field1))
CREATE TABLE table (field1 type1, field2 type2, ..., PRIMARY KEY (field1, field2))
CREATE TABLE table1 (fk_field1 type1, field2 type2, ...,
FOREIGN KEY (fk_field1) REFERENCES table2 (t2_fieldA)
[ON UPDATE] [CASCADE|SET NULL|RESTRICT]
[ON DELETE] [CASCADE|SET NULL|RESTRICT])
CREATE TABLE table1 (fk_field1 type1, fk_field2 type2, ...,
FOREIGN KEY (fk_field1, fk_field2) REFERENCES table2 (t2_fieldA, t2_fieldB))
CREATE TABLE table IF NOT EXISTS (...)

CREATE TABLE new_tbl_name LIKE tbl_name
[SELECT ... FROM tbl_name ...]

CREATE TEMPORARY TABLE table (...)

CREATE table new_table_name as SELECT [ *|column1, column2 ] FROM table_name

DROP TABLE table
DROP TABLE IF EXISTS table
DROP TABLE table1, table2, ...
DROP TEMPORARY TABLE table

ALTER TABLE table MODIFY field1 type1
ALTER TABLE table MODIFY field1 type1 NOT NULL ...
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1 NOT NULL ...
ALTER TABLE table ALTER field1 SET DEFAULT ...
ALTER TABLE table ALTER field1 DROP DEFAULT
ALTER TABLE table ADD new_name_field1 type1
ALTER TABLE table ADD new_name_field1 type1 FIRST
ALTER TABLE table ADD new_name_field1 type1 AFTER another_field
ALTER TABLE table DROP field1
ALTER TABLE table ADD INDEX (field);
ALTER TABLE table ADD PRIMARY KEY (field);

 

— Change field order:

ALTER TABLE table MODIFY field1 type1 FIRST
ALTER TABLE table MODIFY field1 type1 AFTER another_field
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1 FIRST
ALTER TABLE table CHANGE old_name_field1 new_name_field1 type1 AFTER another_field

ALTER TABLE old_name RENAME new_name;

 

Keys

CREATE TABLE table (..., PRIMARY KEY (field1, field2))
CREATE TABLE table (..., FOREIGN KEY (field1, field2) REFERENCES table2 (t2_field1, t2_field2))
ALTER TABLE table ADD PRIMARY KEY (field);
ALTER TABLE table ADD CONSTRAINT constraint_name PRIMARY KEY (field, field2);

 

Privileges

CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';

GRANT ALL PRIVILEGES ON base.* TO 'user'@'localhost' IDENTIFIED BY 'password';
GRANT SELECT, INSERT, DELETE ON base.* TO 'user'@'localhost' IDENTIFIED BY 'password';
REVOKE ALL PRIVILEGES ON base.* FROM 'user'@'host';

 

 

— one permission only

REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'user'@'host';

 

— all permissions

SET PASSWORD = PASSWORD('new_pass')
SET PASSWORD FOR 'user'@'host' = PASSWORD('new_pass')
SET PASSWORD = OLD_PASSWORD('new_pass')

DROP USER 'user'@'host'

 

 

Main data types

TINYINT (1o: -127+128) SMALLINT (2o: +-65 000)
MEDIUMINT (3o: +-16 000 000) INT (4o: +- 2 000 000 000)
BIGINT (8o: +-9.10^18)
Precise interval: -(2^(8*N-1)) -> (2^8*N)-1
/!\ INT(2) = "2 digits displayed" -- NOT "number with 2 digits max"

INT NOT NULL auto_increment PRIMARY KEY -- auto-counter for PK

FLOAT(M,D) DOUBLE(M,D) FLOAT(D=0->53)
/!\ 8,3 -> 12345,678 -- NOT 12345678,123!

TIME (HH:MM) YEAR (AAAA) DATE (AAAA-MM-JJ) DATETIME (AAAA-MM-JJ HH:MM; années 1000->9999)
TIMESTAMP (like DATETIME, but 1970->2038, compatible with Unix)

VARCHAR (single-line; explicit size) TEXT (multi-lines; max size=65535) BLOB (binary; max size=65535)
Variants for TEXT&BLOB: TINY (max=255) MEDIUM (max=~16000) LONG (max=4Go)
Ex: VARCHAR(32), TINYTEXT, LONGBLOB, MEDIUMTEXT

ENUM ('value1', 'value2', ...) -- (default NULL, or '' if NOT NULL)

 

 

Forgot root password?

$ /etc/init.d/mysql stop
$ mysqld_safe --skip-grant-tables &
$ mysql # on another terminal
mysql> UPDATE mysql.user SET password=PASSWORD('nouveau') WHERE user='root';
## Kill mysqld_safe from the terminal, using Control + \
$ /etc/init.d/mysql start

 

Repair tables after unclean shutdown

mysqlcheck --all-databases
mysqlcheck --all-databases --fast

 

Create a facebook feed for your website

In order to get your facebook feed follow these steps.

first go to:

https://developers.facebook.com/apps

Click +Create New App
fill in an app name. ignore the rest. Click Continue.

fill in the security word to get to the next screen.

On this screen you will see a form for creating your app.

fill in App Domains with the URl of the site that will show the feed.
Click the Website with Facebook Login.
fill in the url including the http:// before the site.

Click Save Changes

Once this is done you will need to copy your APP_ID and APP_SECRET codes

Go to this link replacing APP_ID and APP_SECRET with the actual codes.

https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=APP_ID&client_secret=APP_SECRET

when you go there you will get a page looking like this:
access_token=46362638219919|Xmd7dfdfd8003kmsdksaoWWff0MX

your access code is everything after the equal sign. save this code.

next you will need the page name.

go to facebook and go to the page you want the feed for.

for instance to use the feed from this page:

www.facebook.com/jasonmcalpin

you will use the page name: jasonmcalpin

go to the following URL replacing PAGE_NAME with the actual page name. Add the access_token to the end after the equal sign.

https://graph.facebook.com/PAGE_NAME/feed?access_token=ACCESS_TOKEN

congratulations you now have the JSON feed for your page.

In the next post I will take you through styling it.

Fonts and the internet

There are now two kinds of fonts available for use. The first kind are the ones universal fonts installed on every system, desktop and mobile. The other are custom fonts that are generated and uploaded along with the site. The difference in the fonts is that universally available fonts are available immediately and don’t have to be downloaded. The trade off is that although universally available they are not perfect copies of each other despite the name. Custom fonts on the other hand are exactly the same on every system but the trade off is that every browser has a different format they want so you’ll need to offer up to 4 different formats to allow the widest range of viewers to see them. This can result in up to 200k or more of files that will be downloaded along with the page when viewed. This can also cause a lag in when they see the site and when the font changes. It is usually a good idea to avoid using to many fonts as they can cause a dramatic increase in download time for a webpage.

Below you will find resources and information on the best way to use these fonts and which to services provide the best bang for your bytes.

This first group are the core fonts found on most devices. These are the safest to use in most site designs.

Universally available fonts, for desktop and mobile:

Arial/Helvetica
Courier/Courier New
Georgia
Times/Times New Roman
Trebuchet MS
Verdana

Available for desktop:

Impact
Arial Black
Comic Sans MS

The custom fonts fall into two broad groups. @font-face fonts and javascript rendered fonts. The @font-face fonts require a file for each browser:
.EOT: Internet Explorer
.TTF/OTF: Safari and Opera
.WOFF: Firefox
.SVG: Mobile Safari

This can make supporting multiple browsers costly in terms of weight, kilobytes, of a web page. One of the benefits of @font-face fonts is that they are easily rendered and can be used on large amounts of text.

Javascript rendered fonts tend to be about the same size as all the various font formats of @font-face fonts combined so you won’t save much, if anything, in weight. But they render in every browser. The downside is that they can hit the processor pretty hard so large amounts of text can take a long time to render or even crash the browser in some cases. Javascript rendered fonts are best used for titles or other limited uses.

 

The best way to use custom fonts is to optimize the number of characters in the font set. If you know you are just using it for titles then you can limit it to uppercase, lowercase and numbers which will allow for a very small files. In most cases you will upload a font to one of the font sites that will create the various file formats needed.

Another way to lighten the webpage is to remove some of the formats. If you are making a website for just android and mobiel safari you can stick to .svg and .ttf.

In order to get the widest range of fonts you will need to use a font service site.

@font-face service sites

https://developers.google.com/webfonts/
https://typekit.com/
http://www.fontsquirrel.com/

javascript rendered service sites

http://cufon.shoqolate.com/generate/