July 01, 2008

Centering

This is Part 2 in my Series on the Living Web.

There are many ways of centering things in a webpage. We'll start with the basics: say we've got a div for some reason:

<div id="blob"></div>


The blob is shown as the cirlce in this diagram:

Now, we must place it somewhere. There are two easy ways to do this:

1. We could float it, and use margins to control it's placement. The css could be:

div#blob {
float: left;
width: 151px;
height: 151px;
margin-left: 200px;
margin-top: 200px;
}


2. We could use absolute or relative positioning.

div#blob {
position: absolute;
width: 151px;
height: 151px;
top: 200px;
left: 200px;
}


Here is what that would look like positioned absolutely or floated with margins:


Here is an example page showing this in real life.

Please note that if the window is resized, the offsets stay the same; in other words, when you make your browser window really big, the blobs will stay put:


Centering the Blob

div#blob {
/* we do not float it this time */
width: 151px;
height: 151px;

/* the 0 is for top and bottom
* while the auto gets assigned to either side */
margin: 0 auto;
}



The margin: 0 auto; method only centers within the parent element. One great use for it would be to center a container div in the browser window. Interestingly, another way to do practically the same thing is:

div#blob {
position: relative;
left: 50%;
top: 15px;
margin-left: -75px;
}


The other way is using absolute positioning. If you need to keep something, like an overlay in the middle of the window, then take the code above, and change relative to absolute:

div#blob {
position: absolute;
left: 50%;
top: 15px;
margin-left: -75px;
}



We are telling the blob to align itself to the top left corner of the window; then we make it offset to the left by 50%, halfway across. But then we must do a margin-left of negative half of the width of the blob. In this case our blob is 151px so half is about 75px. Using this method, the blob will always stay in the middle, on top of other elements. Like this:


Remember to account for any padding and borders in the negative margin-left. Now we have a div which is always centered horizontally relative to the browser window.

Here is a real life example.

THE CRUX!

Sometimes you want your overlay to stay relative to the content. An example. Image you have a div with a scrollbar; but instead of a scrollbar, you have a javascript scroller, which controls the scrolling via animations, like the black triangles in this screenshot:



(for the programatical side of these scrollers read my article)

When Javascript places the scroll buttons on the page, it could just position them absolutely where they need to go. This would be fine; however, if the div they need to scroll for is centered to the window, we'll need to figure something else out. If a user stretches the window, this is what happens:



In the above diagram, the scrollers are represented by the little blue rectangle inside of the larger blue rectangle. The faded scroller is the ghost image of where the scroller should end up after a window resize.

So, we must extend the centering method mentioned above which used the absolute positioning and the negative margin. We need to have some logic which will figure out the right margin-left so that our scroller div will always stay relative to the middle of the window or document. Here is a diagram:



Here is the Javascript code I came up with. It's a method called safeCenter; if anyone else has already thought of this, and furthermore named this method something else, too bad.

dw.safeCenter = function(item, region) {
var halfWidth = Dom.getViewportWidth() / 2;
var sWidth = cos.stripPx(Dom.getStyle(item, 'width'));
var sHeight = cos.stripPx(Dom.getStyle(item, 'height'));
var right = region['right'];

/* item on right half of window : or item on left half */
var marginLeft = ((right-sWidth) > halfWidth) ? ((right-sWidth) - halfWidth) : (0 - (halfWidth - (right-sWidth)));

var marginalAdjustments = {
'vert' : dw.stripPx(Dom.getStyle(item, 'marginBottom')),
'horz' : dw.stripPx(Dom.getStyle(item, 'marginRight'))
};

dw.setStyles(item, {
'top' : (region['bottom'] - sHeight - marginalAdjustments['vert']) + 'px',
'marginLeft' : (Math.floor(marginLeft) - marginalAdjustments['horz']) + 'px'
});
};



It has some dependancies (some are obvious):

var dw = {};
var Dom = YAHOO.util.Dom;

dw.stripPx = function(str) {
return parseInt(str.substring(0, str.indexOf('p')));
};


dw.setStyles = function(el, style) {
for(var i in style) {
Dom.setStyle(el, i, style[i]);
}
};


You may not be able to tell by looking, but dw.safeCenter has some odd qualities.
  • It takes an element as a parameter (item)
  • It also takes the region of another element, the 2nd param (region)
  • It checks whether item has margin on bottom or right
  • It will place the item in the lower right hand corner of the region it's given
  • Item will be offset from region by marginalAdjustments


Oddly, my favorite line is

/* item on right half of window : or item on left half */
var marginLeft = ((right-sWidth) > halfWidth) ? ((right-sWidth) - halfWidth) : (0 - (halfWidth - (right-sWidth)));


Number one, this is a ternary operator. But also, it's a pretty cool math operation which determines whether to make the margin-left negative or positive. sWidth is the width of the item which the function was given. The reason the second argument is a region is just in case you need to modify the region first (otherwise I would have made the function get the region for you). The type of region I am talking about is YAHOO.util.Dom.getRegion(), which returns a region object.

Here is a live example of safeCentering.

Make sure to look at the examples. As always, let me know if you have any questions about this stuff (or if you find an error).
Enjoy.

Labels: , , ,

June 04, 2008

XHTML 1.0 Strict

Everyone needs to be denied freedom at some point. Here is your chance, with my new XHTML 1.0 Strict template set.

There is a:

Now, it is a fact; everyone and their mom has their own strict template.

It would be sin to leave you without the corresponding TextMate snippet:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />

<title>${1:Title}</title>

${2:<link rel="stylesheet" href="/css/base/base.css" type="text/css" media="screen" charset="utf-8" />}
<style type="text/css" media="screen">
<!--
body { background-color: #f0f0f0; color: #333; font: 12px 'trebuchet ms', sans-serif; }
h1 { font: 300% 'trebuchet ms', verdana; }
a { color: #3875D7; font-size: 14px; }
a:hover { color: orange; }
pre { width: 100%; }
-->
</style>

${3:<script type="text/javascript" src="/js/base/base.js"></script>}
${4:<script type="text/javascript">
<!--
$0
//-->
</script>}
</head>
<body>
<div id="doc">

<div id="hd">
<h1>$1</h1>
</div>

<div id="bd">

</div>

<div id="ft">${5:
<a href="http://blog.polyesterhat.com">Polyesterhat's Blog</a>
}</div>

</div>
</body>
</html>

I got this idea from a post by Dustin Diaz. The Basic XHTML Strict template is already built into TextMate; that's where I got it.

Labels: , ,

March 11, 2008

CSSStyleRule DOM Object Helpers

"Totally PWN CSS with Javascript"

I found this article after realizing that EXT-JS's CSS class really was not what I wanted. There was some problem in the IE's (of course I forget now what it was). I found this guy Patrick Hunlock who writes some awesome code (I would suggest reading the article I linked to, and not stopping there). I like really clean-looking code, sorry Pat; so I cleaned it a bit and minimized it for you all.

Here is the file.
Here is the class api:


var CSS = {
[CSSStylerule] addCSSRule : function([selector]),
[CSSStylerule] getCSSRule : function([selector]),
[boolean] killCSSRule : function([selector])
};


So, when you say:

var pBold = CSS.addCSSRule('p.bold');

pBold will literally be a CSSStyleRule (as the DOM calls it). Furthermore to modify it:

pBold.style.fontWeight = 'bold';
pBold.style.fontSize = '115%';
Hunlock has even more examples on his original post; I also will urge you to Go Forth In Style!

Labels: , , ,

February 16, 2008

Console dot what?

By now we have all began to use console.log. Today, I want to remind you that there is more to Firebug's console function. Here is a list from the documentation. Joe Hewitt has provided us with a treasure chest of web development goodies; but not everyone has firebug. I like to test my scripts on other browsers in parallel with Firefox, and sometimes my console statements stay in the code. Calling console.log will give a fatal error if console is not found, so put this snippet somewhere in your base javascript file:

/*****************************
*
* window.console fix
*
****************************/
window.console = (typeof console == 'undefined') ? {
log: function(t) { alert(t); },
info: function() { },
debug: function() { }
} : console;
From what I have seen, it is the most reliable way to accomplish this. If you use such methods as console.count, simply add that function into my snippet. I got this idea from dustin diaz in this post in his comment to Felix. He said to use:

window.console = console || {
log: function() { },
info: function() { },
debug: function() { }
};

However, this does not work, as it tries to access console before his custom object, giving fatal errors in browsers such as IE 6.

I encourage you to find new ways to let firebug help you, because to become great, you must build on the work of others.

Labels: , ,

February 13, 2008

Exciting Frontend Form Validation

This is part one in my new series, The Living Web: bringing the boring to life

Here is my idea. When a user enters information into a contact form, or some other form, (like a survey) if they screw up, I want red arrows to fly down and show them what they messed up on. This will happen every time they hit the submit button until they figure out what the crap they are doing wrong.

The design pattern:
  • The form submit button gets hi-jacked by custom validation methods
  • Each input is assigned a new red arrow which is hidden from view
  • User hits submit button
  • The form submit event is stopped with YAHOO.util.Event.stopEvent(e);
  • Each input's value is checked against a unique validation method
  • If they all check out, the form is submitted
  • If even one input's value is invalid, the red arrow flies down
  • The input flashes red
  • A new event is made waiting for focus on the input box
  • When the new event is fired, the arrow disappears, we assume user will fix problem
  • The arrow is reset
  • The new event waiting for focus on that input box must be deleted
  • The user "fixes" the problem
  • The user tries submitting the form again
This must work unlimited times in a row.

Here is the code I came up with:

(function(el) {

/* GLOBAL Variables
* invalid : will be an array of id's of inputs which did not validate
* form: will contain name of form i.e. document.formName */
var invalid, form;

/* these are the properties of our red arrow image */
var arrowImage = {
'url' : 'images/arrow.png',
'width' : 66,
'height' : 28
}

/* inputs is the set of unique validation methods */
var inputs = {
'input_1': {
'message': 'string',
'validates': function(value) {
return (value.length > 0);
}
},

'input_2': {
'message': 'string',
'validates': function(value) {
return (value.length > 0);
}
},

'input_3': {
'message': 'must be an email address',
'validates': function(value) {
/* taken from http://www.quirksmode.org/js/mailcheck.html, thankyou! */
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return filter.test(value);
}
}
};

var validateForm = function(e) {

/* we can't have the form submitting yet */
Event.stopEvent(e);

/* reset this array, because each time the
* user clicks submit, we assume there is
* nothing wrong */
invalid = [];

for(var i in inputs) {
/* save a reference to actual html element */
inputs[i]['el'] = $(i);

/* clearly, this is the value of the curent input */
var value = inputs[i]['el']['value'];

/* this is where we test each input's value with that
* input's specific validation method */
if(!inputs[i]['validates'](value)) {
invalid.push(i);
}
}
/* if invalid is empty
* i.e. it's length is 0,
* there was nothing wrong,
* meaning form can be submitted */
if(invalid.length > 0) {

/* announce is another word meaning
* red arrows will fly down */
announceErrors();
}
else {
/* we got the form name in the
* Event.onAvailable callback earlier (below),
* so submit the form */
document.eval(form).submit();
}
};

var announceErrors = function() {
for(var i = 0; i < invalid.length; i++) {

/* get the id of the input which has the invalid value */
var input = inputs[invalid[i]];
var region = Dom.getRegion(input['el']);

/* begin to show the arrow to the user */
Dom.setStyle(input['arrow'], 'visibility', 'visible');

/* use math to figure out where the arrow should go */
var slideArrow = new Anim(input['arrow'], {
'top' : { 'to' : region['top'] - (arrowImage['height'] * 3/4)},
'left' : { 'to' : region['left'] - arrowImage['width']}
}, 0.25, YAHOO.util.Easing.bounceOut);

/* when the arrow stops sliding, the input box should flash red */
slideArrow.onComplete.subscribe(flashInputs, i);
slideArrow.animate();

/* here is where we make the new
* event to wait for user's focus
* please study what is happening here
* we are saying, when the html element gets focus,
* call fadeArrow, because the arrow should go away not,
* because we assume the user will fix the issue
* Then we say, when you call fadeArrow, give it some stuff
* give it an object with two things,
* 1) the html element itself
* (so we can remove it's focus listener)
* 2) give it the arrow element
* then the true signifies that that object
* with the two things should be the scope of
* fadeArrow, in other words, when fadeArrow gets
* called, this['arrow'] will be same as saying,
* input['arrow'] here, whew */
Event.on(input['el'], 'focus', fadeArrow, {
'obj': input['el'],
'arrow': input['arrow']
}, true);
}
};

var flashInputs = function(e, o, i) {

/* we allow e,o, and i,
* only because we need to use i,
* can you figure out why we did not want
* i to be the scope aka, 'this' ? */
var id = invalid[i];

var red = new ColorAnim(inputs[id]['el'], {
'backgroundColor': { 'to' : '#B91309' },
'color' : {'to' : '#FFF'}
}, 0.2);

red.onComplete.subscribe(function() {
var white = new ColorAnim(inputs[id]['el'], {
'backgroundColor': { 'to' : '#FFF' },
'color' : {'to' : '#000'}
}, 0.2);
white.animate();
});
red.animate();
};

var fadeArrow = function() {

/* input box has recieved focus,
* recall that 'this' refers to
* the object with 'obj' and 'arrow'
* remove that listener */
Event.removeListener(this['obj'], 'focus', fadeArrow);

var fadeOut = new Anim(this['arrow'], {
'opacity' : { 'to' : 0 }
}, 0.5);

fadeOut.onComplete.subscribe(resetArrow, this['arrow'], true);
fadeOut.animate();
};

var resetArrow = function() {
setStyles(this, {
'top' : '0px',
'left': '0px',
'visibility': 'hidden',
'opacity' : 1
});
};

var setStyles = function(el, styles) {
for(var s in styles) {
Dom.setStyle(el, s, styles[s]);
}
};

/* basically the constructor */
Event.onAvailable(el, function() {

for(var i in inputs) {
/* give each input its own arrow element */
var arrow = document.createElement('div');
$('doc').appendChild(arrow);
Dom.addClass(arrow, 'arrow');
setStyles(arrow, {
'width': arrowImage['width'] + 'px',
'height': arrowImage['height'] + 'px',
'backgroundImage' : 'url(\''+ arrowImage['url'] +'\')'
});
inputs[i]['arrow'] = arrow;
}

/* note that el is html element id (a string)
* of the submit button, but we temporarily
* reference it with form, this save a tiny bit
* of processing time */
form = $(el);
Event.on(form, 'click', validateForm);

/* bubble up the dom tree to find the html form element
* starting at the submit button */
while(form.tagName.toUpperCase() != 'FORM') {
form = form.parentNode;
}
/* get name of form */
form = form['name'];
});
/* this anonymous function self-invokes itself, and gives itself a string
* this string becomes el, which is the html element id of the submit button */
}('submit_button'))


A working example. My questions for you:
  1. Why is the whole thing an anonymous function?
  2. If it were not anonymous, what public properties or methods could it offer for interaction with other javascript classes?
  3. What css rules would need to be applied to the arrow, for the class div.arrow?
  4. Do you like the way I got the name of the form in order to call the submit() method, is there a better way?
  5. How could the code be modified to enable multiple forms?
  6. How could the code be modified to allow abstracted validation methods?
  7. What would you have done differently?
Feel free to leave comments answering any or all of my questions for you. Also, if you want, I can explain more of a certain part for you, no matter who you are.

Thank you!

Labels: , , , ,

SetStyles

Among my favorite snippets: setStyles(). Say we have an html div element, and you have the urge to make it fill up the entire width and height of the screen using only YUI's dom class. Meet setStyles(), use it on your html element to modify more than one of its' styles at once.


var setStyles = function(el, styles) {
for(var s in styles) {
YAHOO.util.Dom.setStyle(el, s, styles[s]);
}
};


So, in practice, if we have a loading icon from http://ajaxload.info/:

setStyles('some_id', {
'top' : '0px',
'left': '0px',
'position' : 'absolute',
'zIndex' : 100, /* make sure it is on top of everything */
'width' : YAHOO.util.Dom.getViewportWidth() + 'px',
'height' : YAHOO.util.Dom.getViewportHeight() + 'px',
'backgroundImage' : 'url("images/loader.gif")',
'backgroundPosition' : 'center center',
'backgroundRepeat' : 'no-repeat',
'backgroundColor' : '#000'
});
Here is a working example. There you have it. Wonderful

Labels: , , , , ,

December 08, 2007

Cheating at life!

I found some amazing websites this afternoon, via stumble upon.

The first is the one which prompted me to post,

cheat sheets

list of helpful web 2 stuff

design patterns