Apr 26
Event Flow

    Javascript Event Handler

  • Event Capturing
  • Netscape maintained that the event on element1 takes place first. This is called event capturing. The event handler of element1 fires first, the event handler of element2 fires last.

     

    Javascript Event Handler

  • Event Bubbling
  • Microsoft maintained that the event on element2 takes precedence. This is called event bubbling. The event handler of element2 fires first, the event handler of element1 fires last.

     

    Javascript Eevent Handler

  • W3C Event Model
  • W3C has very sensibly decided to take a middle position in this struggle. Any event taking place in the W3C event model is first captured until it reaches the target element and then bubbles up again.

The Event Object

Property Name
Description

type
The type of event that occurred. The value of this property is the name of the event type and is the same string value that was used when registering the event handler (e.g., “click” or “mouseover”).

target
The node on which the event occurred, which may not be the same as currentTarget.

currentTarget
The node on which the event is currently being processed. If the event is being processed during the capturing or bubbling phase of propagation, the value of this property is different from the value of the target property.

eventPhase
A number that specifies what phase of event propagation is currently in process. The value of one of the constants Event.CAPTURING_PHASE, EVENT.AT_TARGET, or EVENT_BUBBLING_PHASE.

timeStamp
A Date object that specifies when the event occurred.

bubbles
A boolean that specifies whether this event (and events of this type) bubbles up the document tree.

cancelable
A boolean that specifies whether the event has a default action associated with it that can be canceled with the preventDefault() method.

Method Name
Description

stopPropagation()
Any event handler can call stopPropagation() to prevent the event from being propagated beyond the node at which it is currently being handled.

preventDefault()
Any event handler can call preventDefault() to prevent the browser from performing a default action associated with the event.

W3C Standard
Internet Explorer
Description

type
type
A string that specifies the type of event that occurred.

target
srcElement
The document element on which the event occurred.

currentTarget
none
Not applicable in IE.

eventPhase
none
Not applicable in IE.

timeStamp
none
Not applicable in IE.

stopPropagation()
cancelBubble
A boolean property that, when set to true, prevents the current event from bubbling any further up the element containment hierarchy.

preventDefault()
returnValue
A boolean property that can be set to false to prevent the browser from performing the default action associated with the event.

The IE Event Object as a Global Variable

          			function onMouseDownHandler(event) {
          				var event = event || window.event; // IE stores events in window object.
          			}
          			element.onmousedown = onMouseDownHandler;
          		

currentTarget and relatedTarget/fromElement and toElement

          			var GENERIC = {
          				findCurrentTarget: function(event, node) {
          					var currentTarget;
          					if (window.event) // For IE
          						currentTarget = node;
          					else if (event && event.currentTarget) // For Firefox, Opera
          						currentTarget = event.currentTarget;
          					return currentTarget;
          				},
          				findRelatedTarget: function(event) {
          					var relatedTarget;
          					if (window.event) { // For IE
          						if (window.event.fromElement)
          							relatedTarget = window.event.fromElement;
          						else if (window.event.toElement)
          							relatedTarget = window.event.toElement;
          					} else if (event && event.relatedTarget) { // For Firefox, Opera
          						relatedTarget = event.relatedTarget;
          					}
          					return relatedTarget;
          				}
          			};
          		

Turn all capturing and bubbling off

					var GENERIC = {
						stopPropagation: function(event) {
							if (window.event) // For IE
								window.event.cancelBubble = true;
							if (event && event.stopPropagation) // For Modern Browsers
								event.stopPropagation();
						}
					};
				

Prevent Default Action

					var GENERIC = {
						cancelDefault: function(event) {
							if (window.event) // For IE
								window.event.returnValue = false;
							if (event && event.preventDefault) // For Modern Browsers
								event.preventDefault();
						}
					};
				
Event Handler Registration

  • Example One
  •           				// Add Event Handlers to The Element
              				element.onclick = doSomething;
              			
              				// Remove Event Handlers
              				element.onclick = null;
              			
  • Example Two: attachEvent() and addEventListener()
  •           				// Add Event Handlers to The Element
              				if (element.attachEvent) { // For IE
              					element.attachEvent("onclick", doSomething);
              				} else if (element.addListener) { // For Modern Browsers
              					element.addEventListener("click", doSomething, false);
              				}
              			
              				// Remove Event Handlers
              				if (element.detachEvent) { // For IE
              					element.detachEvent("onclick", doSomething);
              				} else if (element.removeListener) { // For Modern Browsers
              					element.removeEventListener("click", doSomething, false);
              				}
              			

    attachEvent() and the this keyword

    Event handlers registered with attachEvent() are invoked as global functions instead of as methods of the element on which they are registered. This means that the this keyword refers to the global window object. It is compounded, however, by the fact that the IE event object has no equivalent to the DOM currentTarget property. srcElement specifies the element that generated the event, but if the event has bubbled, this may be different from the element that is handling the event.

    Arguments to addEventListener()

    The final argument to addEventListener() is a boolean value. If true, the specified event handler captures events during the capturing phase of event propagation. If the argument is false, the event handler is a normal event handler and is triggered when the event directly on the object or on a descendant of the element and subsequently bubbles up to the element.

    addEventListener() and the this keyword

    When a function is registered as an event handler for a document element, it becomes a method of that document element. When the event handler is invoked, it is invoked as a method of the element, and, within the function, the this keyword refers to the element on which the event occurred.

  • Example Three: Register Objects as Event Handlers
  •           				var GENERIC = {
              					// Fix the bug the "this" keyword refers to the global window object when event handlers registered with attachEvent() are invoked as global functions instead of as methods of the element on which they are registered.
              					addEvent: function(obj, type, fn) {
              						if (!obj) return;
              						if (obj.attachEvent) { // For IE
              							obj["e"+type+fn] = fn;
              							obj[type+fn] = function(){obj["e"+type+fn](window.event);}
              							obj.attachEvent("on"+type, obj[type+fn]);
              						} else if (obj.addEventListener) { // For Modern Browsers
              							obj.addEventListener(type, fn, false);
              						}
              					},
              					removeEvent: function(obj, type, fn) {
              						if (!obj) return;
              						if (obj.detachEvent) { // For IE
              							obj["e"+type+fn] = fn;
              							obj[type+fn] = function(){obj["e"+type+fn](window.event);}
              							obj.detachEvent("on"+type, obj[type+fn]);
              						} else if (obj.removeEventListener) { // For Modern Browsers
              							obj.removeEventListener(type, fn, false);
              						}
              					}
              				};
              			
              				function changeBackground() {
              					this.style.backgroundColor = "#000"; // "this" refers to the element
              				}
              				GENERIC.addEvent(element, "click", changeBackground);
              				GENERIC.removeEvent(element, "click", changeBackground);
              			
Related Posts

Apr 21
Dynamic Style Loading

          			var HTTPUTILITY =  {
						getStyle: function(url, callback) {
							var isLoaded = false;
							var style = document.createElement("link");
							style.setAttribute("rel", "stylesheet");
							style.setAttribute("type", "text/css");
							style.setAttribute("href", url);
							style.onload = style.onreadystatechange = function() {
								if (!isLoaded && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
									isLoaded = true;
									if (typeof callback === "function")
										callback();
									if (this.tagName.toLowerCase() == "link")
										document.getElementsByTagName("head")[0].removeChild(this);
								}
							}
							var head = document.getElementsByTagName("head")[0];
							head.appendChild(style);
						}
          			};
          		
          			function complete() {
          				alert("complete");
          			}
          			HTTPUTILITY.getStyle("myStyle.css", function(){complete();});
          		
Related Posts

Apr 20
Comparison with XMLHttpRequest()

Advantages

  • Can request a file from anywhere on the net, not just the server your page was loaded from.
  • Works in IE even when ActiveX is turned off (though not when Javascript is turned off).
  • Works with a few older browsers that don’t support XMLHttpRequest, like Opera 7 (though not Macintosh versions of IE).

Disadvantages

  • Returned data has to be formatted as Javascript code. XMLHttpRequest() can be used to fetch data in any format, XML, JSON, plain text, or whatever.
  • Can only do GET requests, not POST requests.
  • Whether the request is synchronous or asynchronous is pot luck, depending on the browser. With XMLHttpRequest() you can control this.
  • When fetching JSON data from an untrusted source, there is no possiblity of checking the data before feeding it to the Javascript parser. With XMLHttpRequest() you can parse the data with something like json2.js instead of eval() for secure parsing.
Load Only Once

					var script = document.createElement("script");
					script.setAttribute("language", "javascript");
					script.setAttribute("type", "text/javascript");
					script.setAttribute("src", url);
					var head = document.getElementsByTagName("head")[0];
					head.appendChild(script);
          		
Multiple Loads

  • Cache
  • First, you need to worry about caching. Typically, the url you’re going to be loading is going to be some kind of CGI program. After all, if the output doesn’t vary, why bother loading it more than once? Usually browsers are fairly smart about not caching those, but you might want to take some steps to ensure that the second call doesn’t just get you the cached copy of the result of the first call. So the CGI should probably be outputting headers to suppress caching. You might also put extra arguments on the URL, perhaps by keeping a count of the number of times you’ve called it, and adding a “?count=7″ argument onto the end of the URL (where 7 is the current count). This makes the URL different on each call, and further ensures that you won’t get a cached copy.

  • Delete Script
  • Second, you’ll tend to accumulate a lot of <script> tags in your header. This doesn’t necessarily do a whole lot of harm, but it seems sloppy. So you could probably delete them by doing head.removeChild(script). I think you can actually have the callback function do this immediately after loading. Removing the <script> tag does not undefine functions or variables that were defined by it, so you are done with it the moment it is done loading.

Detect Load Completion

After we have loaded the helper code, we obviously want to call it to start it running. However, we can’t just put a call to complete() after the commands above, because the browser may be loading the “myScript.js” file asynchronously, which means that our call may occur before the function has finished (or even started) loading.

Here we set up two different event handlers on the newly created script tag. Depending on the browser, one or the other of these two handlers is supposed to be called when the script has finished loading. The onreadystatechange handler works on IE only. The onload handler works on Gecko browsers and Opera.

The readyState theoretically goes through a series of states:

0 uninitialized
1 loading
2 loaded
3 interactive
4 complete

          			var HTTPUTILITY =  {
						getScript: function(url, callback) {
							var isLoaded = false;
							var script = document.createElement("script");
							script.setAttribute("language", "javascript");
							script.setAttribute("type", "text/javascript");
							script.setAttribute("src", url);
							script.onload = script.onreadystatechange = function() {
								if (!isLoaded && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
									isLoaded = true;
									if (typeof callback === "function")
										callback();
									if (this.tagName.toLowerCase() == "script")
										document.getElementsByTagName("head")[0].removeChild(this);
								}
							}
							var head = document.getElementsByTagName("head")[0];
							head.appendChild(script);
						}
          			};
          		
          			function complete() {
          				alert("complete");
          			}
          			HTTPUTILITY.getScript("myScript.js", function(){complete();});
          		
document.write

          			document.write('<' + 'script type="text/javascript" src="http://www.lingihuang.com/libraries/library.js"' + '><' + '/script>');
          		
Related Posts

Apr 17

All Important but Often Elusive: Tips on Creating Your Next Color Palette

Color is a subjective experience, it is a mental sensation, a reaction of our brain. We say that an orange is ‘orange’. But is it really orange? How do we know? We cannot get outside of our eyes or brain to find out, but we do know that when the sun or light disappears; color vanishes. We take colors for granted. It’s only when we are actually drawing or painting that we realize how much value color brings to our daily life.

Color Theory in a Wrap

Color Combination

To learn about color, you first need to understand the structure of color. A color wheel shows us how color is structured. We start with the three primary hues: yellow, red and blue. These are the basic building blocks of color. Next we have the three secondary hues: orange, violet and green. Then follows the third generation or third level: yellow-orange, red-orange, red-violet, blue-violet, blue-green, and yellow-green.

The color wheel (See Figure 1) shows us which colors are opposite to each other on the wheel. Blue is the opposite of orange, red is the opposite of green, yellow-green is the opposite of red-violet. These are called complements. Furthermore, we can divide colors into warm or cold colors. The colors on the bottom right, derived from blue are cold colors, those derived from red are warm colors.

Which color is suitable for which purpose?

Sometimes finding the right color combinations can be really hard, especially if you have to start a project from scratch. If your client already has a logo, a house-style or branding guidelines, you have a starting point. But if it’s your job to design that house-style, the first thing you should do is decide which style the logo should reflect. And with style comes typefaces and colors. Color plays a major part in all this. It symbolizes a certain mood. Does your house-style need cold or warm colors?

Colors reflect a certain personality. They also have several meanings, most of which are closely connected to each other. For example, blue stands for sky, heaven and water. It reflects freedom and peace, but it can also mean cold, protective, authoritative or technical. Red is the color of blood, it reflects courage, romance, but it also means hot, dynamic, vital, commanding or alert. All these symbolic connotations are perfectly visualized by Claudia Cortes in her Color in Motion, a real treat for the eye (the eye has its claims too).

You may not be superstitious or believe that colors have actual meanings, but you ought to consider them. Whether consciously or unconsciously, we consider those meanings when we judge an artwork or design. These generally accepted meanings often play a role in determining whether we like or dislike what we are looking at. Darkness will always suggest danger and mystery.

Colors effect us psychologically regardless of any symbolism, because in some cases they don’t apply; it all depends on the circumstances. For example, black may signify mourning, but a tuxedo is also black and it signifies elegance. We all prefer bright vibrant colors over dull grey, but sometimes grey can be stylish too; it all depends on how we apply it in our design, it depends on the circumstances. But we should also be aware of the fact the meanings of color are different depending on the culture. For example, in most Western cultures, white symbolizes purity and elegance, cleanliness. However, in many Asian countries, white is also a color for death and mourning, and used for funerals. As with any design endeavor, make sure that you don’t only understand the psychological effects of colors but that you also know the nuances of the culture and audience you are designing for! This way you’ll have a better chance of success in achieving the emotional impact you want.

A Nice Well-Balanced Color Combination

To define the colors for your project, choose a set of colors that fits with your client’s logo. This color set should be limited. This way, you get a stronger brand or identity. The overall use of too many colors could result in chaotic and unintended effects. It can get your design totally out of balance. In other words, it will loose its style and personality.

Color Combination

When you choose your shades, there are a few things you should keep in mind. First, there should be enough contrast, and secondly, it might be advisable to have one complementary color. For instance, if you have a set of three colors, Color One should be in contrast with the Color Two and Color Three. Alternatively, Color One could be a complement of Color Two or Color Three. Using complements is not exactly necessary but it can help you achieve nice results. (See Figure 2) Using contrasting colors is important to achieve an interesting well-balanced design. For example, try to have two light colors and one darker color. Or you can have a light color, medium light color and a dark color.

Color Combination

Too much contrast can result in a restless or even aggressive design. (See Figure 3) It might of course be your intention to achieve this effect, but if so, make sure that the eye has some resting place in your layout. A rest-point is (I believe) necessary to keep it all in balance. You see, besides using the right color combinations, Color Combinationyou should also think on how you dose these colors. Try using them in the right proportions. For example, use the lighter color for the bigger areas like the background and the most vibrant color on the items where you want to attract the attention to, like the logo or title. The middle colors can be used for the text and other items.

Color Combination

Using one complementary color can even increase the ultimate effect, but there’s a bit of a catch to this method. You have to be sure to apply them in a subtle way. If you excagerate and get it out of proportion things will get too overwhelming (See Figure 5). If colors are wrong applied or don’t go nicely together, they can make your design rather unharmonious. It’s up you to find out what is suitable or not, after all, colors are a subjective experience. One might like the combination while another doesn’t. Color CombinationSo what makes you have ‘good taste’ in colors? Tastes differ, we all have different meanings of what is attractive and what isn’t. Yet still, the world would be unbearable if there wasn’t some general agreement. Luckily, by following these simple guidelines, you’ll have a better chance of achieving the optimal result. If you get stuck, you might find Adam Polselli’s Get The Look a nice source of inspiration on the latest color trends and styles.

Color Inspiration

It’s been said before, but bears repeating: inspiration can come from anywhere. Always keep your eyes open for color combinations that you like. Examine photographs, pay attention to the vibrant colors of nature, and most importantly, keep experimenting!

Related Posts

Apr 16

When discussing the design of a new site, a question that consistently arises is – “How do I select the most effective colors?” Choosing the right color palette for a site is essential to communicate your message, brand your product or service, and, if you are an online business, sell your products. Everyone has favorite colors, but how those colors are interpreted may vary from culture to culture. Color communicates far more than most people realize. Choosing wrong colors can be a disaster for your website.

Before selecting colors, we ask the following questions:

  • Who are your site’s potential visitors?
  • What are your products or services?
  • What are your site’s key objectives?

Your website’s potential visitors might come from a global or regional market, or exclusively from North America. Did you know that the color white symbolizes mourning in China, or that purple is the color of death in many Catholic countries? Yellow is an Imperial color in Chinese countries, but in America it may symbolize cowardliness or urine. More important, shifting colors to another area of the color spectrum can completely change their impact. For example, yellow shifted toward red results in a color that indicates gold or ‘having value.’

Your visitor demographics also can make a difference in how colors are perceived. Young people are drawn more to saturated colors than adults, who may find them garish or offensive. Strong color contrasts can also drive older visitors away. While young people may respond positively to new color trends, these fashionable colors can be overused and go out of style as quickly as they appear. Text and background color choices also affect readability, which can be an issue for older visitors and those with visual impairments.

The following is a list of colors and potential meanings:

Website Effective Color

Red

passion, romance, fire, violence, aggression. Red means stop, or signals warning or forbidden actions in many cultures.

Purple

creativity, mystery, (reddish purple) royalty, mysticism, rarity. Purple is associated with death in Catholic cultures, as mentioned above.

Blue

loyalty, security, conservatism, tranquility, coldness, sadness. Light blues create a feeling of openness, clean air and freshness, while dark blues can convey tradition, trust and solidity.

Green

nature, fertility, growth, envy. In North American cultures, green means ‘go,’ is associated with environmental awareness, and is often linked to fiscal matters. A lighter, somewhat desaturated green is the color of money and indicates wealth or value.

Yellow

brightness, illumination, illness, cowardice. Some yellows can symbolize the precious metal – gold – and are universally valued.

Black

power, sophistication, contemporary style, death, morbidity, evil, night.

White

purity, innocence, cleanliness, truth, peace, coldness, sterility. White is also the color of death in Chinese culture, as mentioned above.

Many websites today clearly reflect the negative effect of bad color choices. People often choose colors to ‘dress-up’ their site without any regard to their site’s objectives. Here are several mistakes commonly made in selecting website colors:

Colors are selected that conflict with your brand, service or products.

If you have a well-known brand like Coke, you can use bold colors like ‘Coca-Cola red’ as much as you want without concern. However, very few companies are in the unique position where the brand name is more powerful than their brand color. Less well-known businesses should carefully consider the colors they choose for their logos and website. Certain colors work well with specific types of businesses. For example, warm colors, such as reds, yellows, and oranges – often called a ‘fiesta palette,’ can work well for food sites and restaurants that offer spicy fare. Colors in the warm range can also be effective in selling products associated with sun, passion or sensuality. Creams, whites and dark brown colors can be used successfully on websites that sell chocolate products. Cool colors, such as blues and greens, complement outdoor products, airlines, medical services, law firms and intellectual content. These colors can reflect trust or a relaxed attitude. As one person has noted, “… the color blue has a relaxing effect on the nervous system, and some studies have shown that it increases productivity when used as a background color. However, don’t use blue in your color scheme if your product is food-related, as blue is a natural appetite suppressant.”

The web site uses saturated background colors that fight with your site’s content and make it difficult to read and navigate.

If your site uses product pictures or headlines with important messages, you should always chose a desatured background so the images will ‘pop’ or ‘stand out’ on the page. A saturated background will dominate your page, causing both the content and images to be lost. Not only will your content be hard to read, your pictures will lose their effectiveness and your site will be difficult to navigate. The colors of your product pictures and key messages should always be more highly saturated than your background colors. Keep in mind that graphics and areas on your site with the most saturated colors will attract the visitor’s eye first. Here’s an example:

Website Effective Color

On the left you can see a product name and picture on saturated backgrounds. Next to the graphic is an example with lighter, less saturated color backgrounds. As you can see, the less saturated colors on the right complement and ’sell’ the product name and picture more effectively.

Website Effective Color

The example shows color saturation reduced by 10% each step. You can see that colors move from garish to modulated to dingy as they progress from left to right. The 4th through 7th colors in each row are the best choices.

Website Effective Color

This example shows the impact of changing colors from saturated to desaturated, moving from dark to light for each color sample. The saturated colors on the left retain their ‘pop’ even when made lighter, while desaturated colors move into the background and become more muted as they become lighter.

Website Effective Color

The example shows how back and white text appears on saturated versus desaturated color backgrounds. White text has more ‘pop’ on a saturated background while black text is more readable on a desaturated background. The white text on the desaturated background ’shouts’ less, as well. Note that the product picture appears more intense on the saturated color box, while the blue box looks less blue on the saturated color box. The picture and blue box are the same color in both examples. The desaturated example is most effective.

Your website uses too many colors.

Color harmony is the most important criteria when selecting colors. We recommend selecting a moderate number of colors. Four or five colors, plus black and white, should be sufficient. Too many colors create discord and will distract the user.

Related Posts

Apr 15
Disable Text Selection

  • With CSS
  •           				<div unselectable="on"></div> /* For IE */
              			
              				.classname {
              					user-select: none;
              					-moz-user-select: none; /* For Firefox */
              					-khtml-user-select: none; /* For Safari */
              					-o-user-select: none; /* For Opera */
              				}
              			
  • With Javascript
  •           				var disableTextSelection = function(element) {
              					element.unselectable = "on"; /* For IE */
              					element.style.UserSelect = "none";
              					element.style.MozUserSelect = "none"; /* For Firefox */
              					element.style.KhtmlUserSelect = "none"; /* For Safari */
              					element.style.OUserSelect = "none"; /* For Opera */
              				};