Break; and continue; in javascript loops

July 1st, 2008

Break; and continue; statements are essential when working with complex loops. They can be very useful. You can use them to end a loop prematurely, or skip the rest of the loop to start over at the beginning. Here is how you implement it:

<style type="text/javascript">
//build our array
var array1 = new Array();
array1[0] = 0;
array1[1] = 1;
array1[2] = 2;
array1[3] = 3;
array1[4] = 4;

var numArray = array1.length;
for(var i=0; i<numArray; i++){
	if (array1[i] == 2){
		continue; //skip to the end of the for loop, then start over after incrementing by 1
	}else if (array1[i] == 3){
		break; //end the for loop, and execute code after the loop
	}

	alert("still in for loop: " + i);
}
	alert("after for loop: " + i);

</style>

The above code should have created popups for the numbers “0″, “1″, and “3″. This is because the “continue;” statement makes the code skip to the end of the loop, not executing any of the rest of the loop code, then starts over at the beginning of the loop after incrementing i by 1.

The “break;” statement causes the loop to end and the code after the loop to be executed. i is NOT incremented anymore and thus remains at 3.

You can also use “return;” to just end a function prematurely.

Writing a prototype function in JavaScript

June 21st, 2008

This has been tested in FF3, IE7.
Say you wanted to add a function that would be inherent to an element, say you wanted to write an “arrayName.clone()” method (as found in java, but not JavaScript). Here’s how:

<script type="text/javascript">
Array.prototype.clone = function (){
	var newArray = new Array(this.length);

	for(var i=0; i < this.length; i++ ){
		newArray[i] = this[i];
	}

	return newArray;
}

</script>

This would have the same effect as the following code:


<script type="text/javascript">
function cloneArray(oldArray){
	var newArray = new Array(oldArray.length);

	for(var i=0; i < oldArray.length; i++ ){
		newArray[i] = oldArray[i];
	}

	return newArray;
}

</script>

The difference here being that for the prototype function you call it by using “arrayName.clone()” and for the second function you use cloneArray(arrayName). The both functions return the same thing.

Why not just use the following code below, you might ask? Because what you are doing below is just creating a new reference to the same array object. So if you made changes to oldArray, newArray would reflect those same changes. The functions above actually create and return a brand new array.

var oldArray = new Array();
var newArray = oldArray;

Designing with a concept

May 5th, 2008

I recently completed my typography course here at school as I am working on B.S. in Information Systems. The most valuable thing I can remember from my course is the idea of having a concept. Having a concept before you start sketching, before you think the layout, or the colors, or the fonts.

Why a concept?

A concept gives a designer a vision to work with. A theme to follow. A goal to aim towards. It is the subconscious end that will(should) guide all of your decisions. If your concept is “A rainy day”, you will font that expresses that. You might choose blue as your main color. You might choose a layout or certain effects that make you think of sadness and rain. Suddenly you find yourself having ideas based on this concept, and you have a definite direction to go towards. If you have new ideas, you can always compare them to the concept, and see if it fits.

Your concept will guide and inspire the sketching process. You won’t choose blue because you like blue, or a 1 column layout because you like it, but because it fits with your concept. Suddenly, you have a completed piece, with it’s fitting parts that make up that piece. Not just different parts that are trying to fit like puzzle pieces that don’t belong together. The difference is immediately apparent and powerful.

How do you get a concept?

If happen to be designing a page about an artist, you need need to research that artist. Write down words that come to mind. Words like powerful, dressing, provocative, words that are descriptive. I have found time and again, that I will write these words down, until the words cause images to flash in my head. Images of possible designs. I then sketch these images on paper, and explore those options if I like them. If I don’t I keep going on with my concept.

Once I have my concept, I should try to stick with it as much as I can. The finished piece will be better if I do, because each part will have a sense of belonging. It will feel like it is adding to the piece by being there. Not just there as decoration, or as a crutch, but because it helps express the overall theme or emotion of the piece.

document.getElementById().innerHTML + IE7 can cause problems

April 26th, 2008

It seems that Firefox and IE7 can use and replace the innerHTML of a DIV just fine. However when you try it with a table or a tbody tag (among others, I’m sure), it just breaks apart miserably in IE7 (Firefox works just fine). You’ll most likely get a JavaScript error that states “Unknown runtime error” and then point to the line that uses the innerHTML of the element that isn’t a DIV.

The solution? There are 2 possible workarounds. 1) Use a DIV, or 2) use appendChild(). I will show how to use appendChild here. I’ve tested this in IE7, FF, and Safari (Mac) and it should work. Thanks to Jeremy Keith I was able to figure it out after hours of struggling.

The following code should probably be within a function you call.

<script type="text/javascript">
var output = "dynamic output from earlier should go in this variable";

//first, create the table row and the table cell
var newtr = document.createElement("tr");
var newtd = document.createElement("td");

//place the output variable within the table cell, innerHTML here works because it's not on the page yet
//then, append the cell to the row, basically places the "<td>output here</td>" tags within the <tr></tr> tags
newtd.innerHTML = output;
newtr.appendChild(newtd);

//last, append the whole thing to the element, here it'll find the element with the "tbody_one" id, go inside, and make it the last child
document.getElementById("tbody_one").appendChild(newtr);

</script>

How to apply javascript to one specific browser (browser sniffer)

April 11th, 2008

What if you have JavaScript that only works in one browser? What if you’re using IE and Firefox. Well, you need to write one statement that will execute in IE, then another statement to run in the Firefox. This is also called a browser sniffer.
Here’s how you can do it.
First we’ll show you how to write a catch so it’ll run 1 statement if it is IE, and another if it’s any other browser.

<style type="text/javascript">
var browser = navigator.appName; //find the browser name

alert(browser); //popup with the browser name

if(browser == "Microsoft Internet Explorer"){
    alert("You are using IE");
}else{
    alert("you are using a different browser than IE");
}
</style>

Usually the code above suffices, because most JavaScript will either work in IE or the other browsers.

How to getElementsByClassName in JavaScript and manipulating those

November 26th, 2007

What if you wanted all of your elements on the page that have the same class=”" to behave the exact same way. Well, with a little JavaScript, this is possible, thanks to Netlobo.com:

Note: You must add the following onload event to your body tag: < body onload=”loadClassNames()”>

<script language="javascript" type="text/javascript">

//function that allows us to get the elements by a class name,

document.getElementsByClassName = function(clsName){

	var retVal = new Array();
	var elements = document.getElementsByTagName("*");

	for(var i = 0;i < elements.length;i++){
		if(elements[i].className.indexOf(" ") >= 0){
			var classes = elements[i].className.split(" ");

			for(var j = 0;j < classes.length;j++){
				if(classes[j] == clsName){
					retVal.push(elements[i]);
				}
			}

		}else if(elements[i].className == clsName){
			retVal.push(elements[i]);
		}
	}
	return retVal;
}

function loadClassNames(){
	//this method only works for event handlers

	var classNames= document.getElementsByClassName('test2');

	for (var i = 0; i < classNames.length; i++){
		classNames[i].onmouseover = function(){
			alert(this.id);
		}

	}
}

The first function simply adds the capability of getting an element by class name, which is not inherently possible with JavaScript. Now, what the 2nd function does, is the following. If you add loadClassNames() as an “onload” function to the body tag, when the page loads, the function will get all of the elements with a class name of ‘test2′, and assign a new “mouseover” event. In this case, it will create a popup that displays the id of the element.

Find x and y position of an element using JavaScript

November 1st, 2007

Ever needed to find the x or y coordinates of an element on a page? Well, thanks to this script from quirksmode it’s possible.

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

var elemToFind = document.getElementById('div1'); var elemCoords = findPos(elemToFind);

So now, elemCoords holds both the x and the y. Since findPos() returns an array, to access the x or y by itself do the following:

// elemCoords[0] or elemCoords[1] for the x and y values, respectively
alert(elemCoords[0]);

How to write a CSS rule that will affect every element:

October 25th, 2007

Sometimes there’s a need to reset all of the margins on a page, or you simply want something specifically applied to each element without having to count on inheritances to do the job. The solution: “*” or “universal selector”. This seems familiar from other languages right? Well, it should be. It simply means “everything” in a selected area.

The following will apply a gray background to every element on a page.

* {
    background-color: #eee;
}

What if you want to get more specific?
With this code, everything within the div with the id=”wrapper” will have a gray background.

div#wrapper * {
    background-color: #eee;
}

Obviously any properties can be used here. Enjoy.

Give me a voice.

October 17th, 2007

My newest pet peeve: Blogs that don’t allow you to comment.

It’s human nature to need interaction in a time of ever decreasing social abilities.

I enjoy reading blogs. I enjoy reading the comments that go back and forth. I enjoy reading about Design and other teachnical stuff.

Two blogs I have started reading regularly have sparked this: Northtemple and I hereby Decree.

Both are very much worth my time. Oftentimes I have questions. I don’t understand what’s being referred to. Or, I feel strongly on the subject. Let me talk to you. Let me give my opinion. Let me interact with you. Let me be human. So please, give me a voice. Allow commenting, and I promise, I will comment.

People who say “it can’t be done” are usually dead-wrong

October 15th, 2007

As as UI designer I am in a field where I am constantly trying to find new solution to existing problems. These are problems that other people either don’t even think about fixing, or they think it’s too hard, so they don’t bother.

Frequently when I ask somebody if Task A “can be done”, I get the typical ” No, that can’t be done.” or “I would require a LOT of work”. Well, here’s my declaration to the world:” People who say it can’t be done are usually dead wrong“.

I can’t even count the times an “expert” has told me something can’t be done, and (oftentimes) with just a little research I figured a way to do, what “couldn’t be done”. So here’s to you. Don’t take no for an answer. Ask why it can’t be done, and then try to solve that hindrance. You will have amazing results.

Please, leave me a comment and tell me how you feel about this.