Quantcast

Years and JavaScript

(No Ratings Yet)
Loading ... Loading ...

If you're new here, you may want to subscribe to my RSS feed. So that you can read the latest updates about Web2.0 tools, Making Money Online, Tips in SEO, Ajax and many more. Thanks for visiting ProgramimiCOM!

One would think that in order to get the current year with JavaScript, you just have to do date_obj.getYear. That’s logical, becuase to get the day it’s getDay, and month is getMonth, but JavaScript likes to be mean. (how rude!) Using getYear will return only a two digit number, for 2006, it’s 16, but we acutally want 2006. To get this, you need to use getFullYear.

I’ve always found this weird, but definitily something good to know so that when you try to get the year with JS and end up with some random number, you don’t pull your hair out. :)

JavaScript password checker

(No Ratings Yet)
Loading ... Loading ...

At your site do you have a registration form? Want to check for password length before the form is submitted? You can do this easily with JavaScript and a little alert box.

First of all here’s a little sample form you might have:

 

<form name=“form_name” method=“post”>
Username:<br /><input type=“text” name=“username” /><br />
Password:<br /><input type=“password” name=“password” /><br />
<input type=“submit” name=“submit” value=“Submit” />
</form>

That’s just a simple form with a username, password, and submit field. Now what we’re going to do is add one more attribute to our password field to make it look something like this:

 

<input type=“password” name=“password” onblur=“javascript:checkPassword()” />

The onblur attribute activates it’s value when you unselect the object in question. So, when we unselect the password field, the javascript function “checkPassword()” will be called. Now we have the HTML, however we have to make checkPassword() actually do something, so we have to define a javascript function in the head of our document.

Anywhere between your and tag, you would add something like this:

 

<script language=“JavaScript” type=“text/javascript”>
<!–//
function checkPassword(){password = document.form_name.password.value; //Gets the value of the form element “password” in the form named “form_name”
if(password.length < 6){ //If the password length is less than 6
alert(“Please enter a password of 6 characters or more”); //Alert that it needs to be 6 or more
}

}
//–>
</script>

You can easily change the number 6 to whatever number you want, and it will always alert when you blur away from the element :) If you have a different name for either your form or your field you have to change the JavaScript accordingly, although I’m pretty sure you could probably figure out how to do that?

And that’s it, pretty simple :) You could also do some more complex things with it such as check for certain characters using Regex.

Toggling Visibility

(No Ratings Yet)
Loading ... Loading ...

Many times for navigation menus you want to have sub-items of a specific category, but don’t want them to be shown all the time. There is a much easier way to do this than to have something server-side handle this and refresh the page, that way is to use JavaScript. :)

Surprisingly, this is easy. The only JavaScript we need is a simple function that takes the id of the element to toggle, than displays or hides it according to the current setting. Doing this involves simply changing the display method to either none or block.

Let’s see some code:

function toggle(id)
{
if(document.getElementById(id).style.display == “none”)
{
document.getElementById(id).style.display = “block”;
}
else
{
document.getElementById(id).style.display = “none”;
}
}

This function takes the specific id of the item we want to toggle, than decides wether to make it visible or hidden using a simple if conditional. Below is a full page using this:

<html>
<head>
<title>Toggle Visibility</title>
<style type=“text/css”>
.subitems
{
margin-left:5px;
}
</style>
<script type=“text/javascript”>
function toggle(id)
{
if(document.getElementById(id).style.display == “none”)
{
document.getElementById(id).style.display = “block”;
}
else
{
document.getElementById(id).style.display = “none”;
}
}
</script>
</head>
<body>
<h2>Categories</h2>
<a href=‘#’ onclick=“toggle(’php’);”>PHP</a>
<ul id=‘php’ style=‘display:none;’ class=’subitems’>
<li>Articles</li>
<li>Tutorials</li>
</ul>
<br /><br />
<a href=‘#’ onclick=“toggle(’css’);”>CSS</a>
<ul id=‘css’ style=‘display:none;’ class=’subitems’>
<li>Articles</li>
<li>Tutorials</li>
</ul>
</body>
</html>

This script implements the toggle function by having two lists, set to display:none at first, toggle their visibility by clicking a link. As you can see, each list has a specific id which is used in the toggle function (php, and css).

Form Labels

(No Ratings Yet)
Loading ... Loading ...

More and more sites are using the label element in their forms, which is always a cool thing. Basically, you enclose the label tag around the text which tells about the current input, which could be for a username, E-mail address, or search term. By clicking the label, you focus that field. It’s pretty basic, but it adds to the user’s experience on your site. To know which input to focus, the label element takes 1 attribute, for, which is the ID of the input. Here’s an example:

<form method=“post” action=“?”>
<label for=“username”>Username:</label> <input type=‘text’ id=‘username’ /><br /><br />
<label for=“password”>Password: </label> <input type=‘password’ id=‘password’ /><br /><br />
<input type=“submit” value=“login” />
</form>

Organizing your scripts

(No Ratings Yet)
Loading ... Loading ...

Quite possibly one of the most important things you need to keep in mind when working on a larger coding project is to stay organized. Organization can either make or break your project, so I’ve decided to share a few tips I use to try and keep organized.

Indentation
Although to many it is an obvious thing to do, there is far too much code out there that doesn’t use indentation at all or correctly. It is very easy to make a long script in notepad with absolutely no indentation, however, one of the most common mistakes you can make while coding is forgetting to close a brace (curly bracket; { }), and this is only made easier by not indenting your code. Indenting allows you to see all the layers in your code much more easily, producing much nicer looking code, not to mention being a lot easier to read.
Here is an example of how you can best use indentation in your code

statement ( condition )
{
//One indentation in
statement ( condition )
{
//Two indentations in
}//Close a layer
statement ( condition )
{
//Into another layer
}//Close it
}//Close the original layer
Commenting
Another very important habit you should have with your coding is always commenting what you’re doing. It helps you find where something occurs in the script, why that might be occurring, as well as telling anyone else reading your script what you were trying to accomplish. This makes it easier to debug things, as well as get help with your scripts. I generally comment to signify new sections of code, what some more confusing functions are doing, what variables are for, etc.

Variable names
It is also very important that your variables are well named. Knowing how to name variables descriptively yet in just a few characters is a very great skill to have in my opinion, and is unfortunately one I’m not the greatest at (ha ha). You want to be able to communicate to whoever is reading the script what that variable does as well as anything else you want associated to it such as the data type (int, txt, etc.), or some other classification you deem useful for your particular script. I also find it very helpful to capitalize separate words or abbreviations in your variable names (or any other names for that matter) to give you results like intYear or txtMessage.

Arrays are your friend!
This is almost a continuation of the variables section, however I thought it was important enough to have it’s own section. Arrays are not only for storing common array data such as rows of a table. They can be used to your advantage for common use variables that you want to be associated in some way. You could use it the same way as variables by storing more information in just the name. Say for example you had some key numerical values that were used throughout your script; you could use the array num[] or whatever you want then store your data in parts of the array: num[’varKey’] = 129837981. It also lets you classify your variables in a little more detail so you could have the same name for more than one value like: my[’name’] and your[’name’].

Follow some sort of protocol
In general your script should all be structured similarly. You should have a set method for most things like where you put your comments, (above, after, before, below, whatever you want), how far you indent (tabs or a number of spaces), how you put your braces for statements (same line or next line usually), and any other little thing that you probably do habitually anyway without noticing it. Whatever you do though, you should keep it all the same so you can keep everything looking neat and tidy!

Multiple CSS Classes

(No Ratings Yet)
Loading ... Loading ...

Elements are not limited to only one class, you can easily declare multiple ones, all you need to do is seperate the classes with a space.

<style type=‘text/css’>
.highlight
{
background-color:yellow;
}.heavy
{
font-weight:bold;
}
</style>
<p>The most important thing to remember is <span class=‘heavy highlight’>my birthday</span>!</p>

That easy!

Centering divs with CSS

(No Ratings Yet)
Loading ... Loading ...

Centering divs isn’t quite the same as centering normal html elements. You cannot use the align attribute, you have to define margins like this:

div#some_id
{
margin-left: auto;
margin-right: auto;
width: 500px;
}

You could then get a horizontally centered div 500px wide!

**Note: using the align attribute will only center the html inside the div.

List-O-Matic

(No Ratings Yet)
Loading ... Loading ...

List-O-Matic has always been my favorite of Accessify’s tools. It takes you through a few simple steps that allow you to quickly and easily make some professional, W3 compliant CSS navigation. I had used it many times back in the months before I understood CSS and how to use it, haha. Check it out! It’s great not only for use but as a learning tool as well!

Problems with the Equal Height Columns method

(No Ratings Yet)
Loading ... Loading ...

Several issues have been discovered since publication which, depending on your requirements, can cause severe problems when using the equal height technique.

  1. Linking to anchors in elements within the containing block
  2. Selecting and scrolling in Gecko-derived browsers
  3. Printing in Internet Explorer

Linking to anchors in elements within the containing block

Linking to an anchor in any of the columns within the element that has been set to overflow: hidden causes the content of that column to shift upwards. In IE and Firefox, that is.

Example of anchors in the equal height method

ie. it’s not the large padding that’s casuing the problem (though obviously it is the trigger of the behaviour)

A fix for IE

Fix for anchor problem in IE

IEs 6 and under are easy. Simply suppress the overflow: hidden on the containing wrapper element.

IE7b thought doesn’t work since overflow:visible makes the overflow of the columns, well, visible. So we use an expression instead, making the columns the height of the column container.

However, there are dragons here…

  1. If we use the exact height of the wrapper, things can explode on first load or, absolutely without fail, when refreshing the page using F5. We can be worked around by taking a pixel off. Then the shorter columns are still shorter requiring the footer to be shifted up a pixel for good measure.
  2. Of course, it will fail utterly if the security level is such that expressions don’t get evaluated or at the very least annoy the hell out of users with a prompt to allow the expressions to be evaluated…

So if you don’t like those dragons, you might prefer to force IE7 into Quirks mode. [1]

No cure for Cancer

…or rather, there appears to be no fix for Gecko-based agents. I had thought shifting the padding and negative margin to the top (like for the Opera 8 fix) would sort things out, but once Gecko knows that the box is larger than what’s displayed the anchor shifting occurs.

Half a cure for Geckos

Half fix for anchor problem in Gecko

Ingo Chao has come up with a solution that works as long as certain conditions are met - the trick is to apply position:absolute to the target.

For anchors of the form <a name="target"></a>, this presents no problems. If the target element can stand being absolutely positioned, everything will be ok. Obviously though, attempts to apply the same technique to an anchor which is actually an id on an element enveloping content will result in dismal failure. And for many off-the-peg blogs and CMSes, that’s probably going to be the case.

Furthermore, the parent element of the target must not have position:relative applied to it, which also somewhat reduces the usefullness of the technique.

What the hell is going on?

Weirdly, just to add spice to the whole over-egged pudding, when used in equal heights mode, Opera 9 doesn’t shift. But with the following reduced test case, it does.

Two distinct behaviours can be seen in the previous reduced testcase.

Behaviour A
the content shifts within the element to reveal the triggered anchor
Mozilla since 1.6a, IEs 5.01 through 6 and Opera 9b
Behaviour B
nothing happens
as seen in Safari, IE Mac 5, Mozilla 1.5 and earlier, and Operas pre v 9

The question is, are current Geckos, IE and Opera 9 correct in their handling of the above example? What do the specs say?

This value indicates that the content is clipped and that no scrolling user interface should be provided to view the content outside the clipping region.

CSS 2.1, 11.1.1 Overflow: the ‘overflow’ property

So does that mean that the content can be scrolled (though no interface should be provided) which is what Firefox and IE are doing, or does it mean that no scrolling should occur? But how would the latter jive with scrolling the content via scripting (which is surely meant to be allowed)?

Sorry. Not fair. It’s a bogus question. In the words of the editor of the CSS specs, Ian Hickson, “The spec doesn’t define what happens with anchors.” So, let’s play detective and figure out when (and hopefully why) the behaviour changed in Mozilla and Opera.

For Opera, the answer is fairly easy to track down thanks to a note in the changes log, under the heading “Acid2 Fixes”…

Elements with overflow:hidden; can scroll to anchors within them.

…which was done presumably (remember the specs say nothing about how an agent should handle anchors) because unless they scrolled to the anchor on the test page, nothing would show at all and so they would fail the test at the first hurdle.

Safari has taken a different route to passing the test - by making the html element scrollable when overflow property is set to hidden, but not doing so for any other element.

Of course there’s nothing to say which of these paths (if either) is correct. There’s nothing in the Acid2 guide reference that mentions testing for such behaviour and the only comment about the use of overflow:hidden; on the html element is:

/* page setup */
  html { font: 12px sans-serif;
  	margin: 0; padding: 0; overflow: hidden;
  /* hides scrollbars on viewport, see 11.1.1:3 */

The Second Acid Test

…which leads us back to that section of the CSS specs which, er, has nothing to say about the treatment of anchors.

So how did the test get into Acid 2? What is its purpose? Fortunately a little bird was able to tell me that Ian Hickson was the lead in constructing the Acid2 test. So I asked him why it was set up that way, with the content hidden and being scrolled to, and whether this was an intentional part of the test, or it just happened that way because that’s how Mozilla and IE handled it

Hmm. I didn’t think about how anchors interacted with the overflow:hidden text and just assumed it would work. :-)

The reason I used overflow:hidden at all was to test make one of the browsers implement overflow:hidden on the root element, because authors were complaining it wasn’t supported (I don’t remember which one any more, probably Opera). Also, I needed to have scrolling to test fixed positioning, but I didn’t want to show the scrollbar.

via personal correspondence

Incredibly dull downloading of many many copies of old versions, followed up by combing through the bug tracking system eventually gave up the point where Mozilla had begun to scroll overflow:hidden, which in turn pointed to bug 221140 which gets us towards the heart of the matter.

The basic problem here is that ’scroll’ and ‘auto’ have never worked on table cells, and the working group decided to make ‘hidden’ work like ’scroll’ and ‘auto’, so now ‘hidden’ doesn’t work either.

Bug 221140 - ‘overflow: hidden’ on table cells broken, comment #4

Of course, the question of exactly what and where the working group had decided is moot. Let’s have another look at our old friend 11.1.1, the overflow:hidden definition (remembering that it says nothing about how user agents should deal with anchors):

This value indicates that the content is clipped and that no scrolling user interface should be provided to view the content outside the clipping region.

CSS 2.1, 11.1.1 Overflow: the ‘overflow’ property

Previously the same section had been:

This value indicates that the content is clipped and that no scrolling mechanism should be provided to view the content outside the clipping region; users will not have access to clipped content. The size and shape of the clipping region is specified by the ‘clip’ property.

CSS 2, 11.1.1 Overflow: the ‘overflow’ property

Do these changes to 2.1 mean that Behaviour A is correct and were they introduced for exactly such a situation?

Prodding Ian Hickson again, I got the following explanation:

It was changed in issue 1-16, around July-September 2003. But it was made in response to an W3c-internal-only comment, so that won’t help you…

… I imagine the reasoning was “to make CSS compatible with the Web”, which already behaved that way.

… It was probably more “browsers won’t change their behaviour to match the spec because doing so would break Web pages, so we’ll change the spec to match the browsers instead”. (This reasoning is the thinking behind much of the changes to CSS2.1. Pragmatism is an important factor in the development of the CSS2.1 and HTML5 specifications.)

via personal correspondence

A bit of a mess…

So to sum up, the situation is happenstance yet quasi-official. That’s how IE did it, so the W3 working group and Mozilla followed suit. And Opera followed along later to pass a test that reflected that status quo.

Consequently there’s nothing to say that Safari’s divergent behaviour (scroll on html element, no scroll on any other) isn’t correct. Or what the behaviour should be if a box that overflow: hidden is applied to is tall enough to show all the content within it, but there is additional padding-bottom beneath it…

La Chatte Noire example 1

La Chatte Noire example 2

And Bug 259615 - ‘overflow: hidden’ elements shouldn’t be scrollable by the user probably shouldn’t really be a bug. But Bug 325942 shows that some of the Mozilla team think it should.

Recommendations

Sorry, I don’t have any recommendations. Really. It’s up to you to decide what works for you, just like you should decide what browsers you should support. That said:

  • Use of the method in situations like the Tucows example where the technique is used just for a component of the page will be solid. (ie. just place any anchors you might need before or after the columns)
  • Use for whole page layouts will be solid if you can guarantee that you won’t need to use named anchors within the columns.[2]

If you can’t guarantee the absence of anchors, then you’re probably going to be better off going with faux columns or a javascript-based solution.

Of course, if Mozilla supported multiple background images this would all be irrelevant… Or if Mozilla could apply position: absolute to generated content properly…

Selecting and scrolling in Gecko-derived browsers

Drag to select content within the longest column and keep dragging downwards - if the bottom of column is above the bottom of the viewport there is no problem. If it’s below the bottom of the viewport then it keeps scrolling, shunting the content of all the columns upwards and very rapidly at that so that in all likelihood it just vanishes. (It is possible to scroll it back if some of the content is still visible and selectable - but that’s an academic point since in reality the average user is going to be just as foobarred as if all the content had dissapeared)

Fixed as of Firefox 1.5 and Camino 1.0, so this is basically a non-issue.

Printing in Internet Explorer

A less serious problem (unless you’re being bitten by it) is that it can cause printing problems for IE. Depending on the exact values used for padding-bottom and margin-bottom, the content in the columns can shift upwards and even disappear entirely. The answer to this problem is to suppress the negative margin-bottom (and consequently the padding-bottom too) in a print style sheet. You shouldn’t be printing the backgrounds in any case ;)

Do not ask for whom the bell tolls

So, the end result may be that the actual usefulness of the equal heights technique is in exposing flaws in certain rendering engines (whether it’s Safari and Opera or Explorer and Gecko that get it wrong I leave for others to decide).

Fortunately for me, it’s the technique that I’m least concerned about since there’s always Faux Columns to fall back on. And even more fortunately I covered myself in the article by saying that Faux Columns would probably remain the weapon of choice ;)

Browser Shifts on anchor trigger Scrolls on select drag
Firefox 1.5 Yes No
Firefox 1.07
NS 7.2
Yes Yes
IE 6 Yes No
IE 5.01 (+ 5.5 ?) Yes No
Opera 9b Yes No
Opera 8.5, 8.0, 7.54, 7.23, 7.1, 6.06, 5.11 No No
Safari 2.0, 1.03 No No
iCab 3.01 No No
IE 5.23 (Mac) No No
NS 7.1, 6.23, 6.1 No No

 

  1. Alternatively there’s an equally trivial fix for IE 5.01 and 5.5. Give the column wrapper a height and then set the columns to be 100% high. IE 6 would obviously be the same in Quirks mode, but in Standards mode that doesn’t work. So we’d need to use the same type of expression as for IE7 instead, making the columns the height of the column container, with all the same caveats mentioned above. along with an additonal one that changing the font size can cause IE6 to go screwy. Of course, I don’t recommend this over the above-mentioned method, but just so you know. There might be a situation where you can’t rely on expressions and don’t mind being in Quirks mode…?
  2. Incidentally, a certain celebrated ascetic mad monk, er, usability expert, has decreed use of anchors considered harmful.?

 

 

(Position is Everything)

Avoid Within-Page Links

(No Ratings Yet)
Loading ... Loading ...

Within-Page Links Violate Users’ Mental Model

On websites, within-page links are bad for the same reason that PDF files are bad entered without warning in the top-ten design mistakes. Users have developed a strong mental model for link following, which has several elements:

  1. Clicking a link navigates you to a new place.
  2. After you click, the old page goes away.
  3. A new page loads into the window, replacing the old page.
  4. You first see the top of the new page.
  5. The Back button returns you to the old page.

Because almost all clicks work this way, users have very strong expectations that the Web will work this way. It’s a simple model that makes sense. Within-page links violate all five points in users’ mental model of links:

  1. A within-page link scrolls the window rather than navigating you to a new location. This confuses users: they assume they’ll get new information, but if they’ve scrolled through the page before clicking, they’ll get stuff they’ve already seen.
  2. The old page doesn’t go away; it’s still in the window. However, because users think they’re on a new page, they’ll try to figure out how the “new” information differs from what they’ve seen — obviously, a futile task.
  3. No new page is loaded into the browser window: it displays the same data, just scrolled differently.
  4. Rather than land at the top of the page, you typically find yourself somewhere in the middle with no navbar or other expected top-of-page design elements.
  5. Clicking Back doesn’t take you to the previous page; it takes you to the previous scroll state of the same page. This can doubly confuse users who’ve scrolled to the top of the page before clicking Back.

After experiencing a few within-page links and Back button clicks, most users are completely confused about where they are on a site. Our studies also show that such links typically waste far more time than they save because users click back and forth multiple times and repeatedly review the same material.

When Within-Page Links Are OK

To avoid confusing users, you must communicate exceptions to their expectations in advance. It’s okay, for example, to use mailto links, as long as you clearly indicate that the links will activate an email program rather than navigate users to a new page. You can signal this through link format (”donald@duck.com“) or wording (”send an email to customer support“). Similarly, if you absolutely must use within-page links, say so. For example, add a short statement that says something like: “Clicking a link will scroll the page to the relevant section.”

Assuming you warn users, within-page links have three acceptable uses. First, with long alphabetized lists, you can show the letters of the alphabet across the top of the page and have each letter link to the appropriate place in the list. Second, in frequently asked questions lists (FAQs), you can list the questions at the top of the page and make each question a link that scrolls the page to the associated answer. Third, there are a few other cases where you can start a page with a table of contents that links to the appropriate sections further down the page.

All three exceptions share a common format: a long list of items summarized at the top of the page, with links taking users directly to the desired items.

Even with this scenario, it’s best to avoid within-page links if possible. You might, for example, make the lists short enough that users can easily scroll them. Only for very long pages will the time saved be worth the confusion that within-page links can cause.

For example, we recently tested a website that listed information for each of the fifty US states on a single page. Above the fold, the page displayed a map of the US with instructions that told users to click on their state.

First off, it’s usually a bad idea to ask users to select their state or country by clicking on a map. While it works well for those of us in big states like California, take pity on folks from Rhode Island or Connecticut. (The same argument applies, for example, when asking users to pick their country from a map of Europe: fine for German users, less ideal for Belgians.)

Assuming users have sufficiently steady mouse hands to click their particular state, our example page scrolls accordingly. If users click a state in the middle of the alphabet (say, New York), the state appears at the top of the window and users can easily find their information. Unfortunately, if they click, say, Wisconsin, they’ll typically find Tennessee on top of the screen, because that’s as far down as the page will scroll. This causes confusion: “I clicked Wisconsin, but it says Tennessee?”

In this case, because each state has only a few data items, it would be better to simply let users scroll through the page to find their state. Sure, that’s annoying if you’re from Wyoming, but it actually requires less time to simply scroll than to read and understand the non-standard instructions for clicking the map. After all, people arrived at such pages by clicking links like “Information about foo by state“; they expect to see a list of states, and know where to find their own state in the list.

Linking to Named Anchors Across Pages

Using named anchors to link to a specific place on a different page is not as bad as using within-page links on a single page. When you link to a named anchor on a different page, you retain four of the five expectations in users’ mental model: they navigate, the old page disappears, a new page loads, and they click Back to return to the old page. The remaining expectation is the only problem: instead of going to the top of the new page, users are typically dumped into the middle.

While it’s certainly better to violate only 20% of the mental model, violating user expectations is still a bad idea. Dumping users in the middle of a page causes usability problems because users need to situate themselves when they land on a new page. A page’s headline, introduction, and navigational apparatus provide essential context to that end.

Nonetheless, named anchors are tempting. At the top of this page, for example, I have links to various articles because I refer to points made within them. I refer to those mistakes in the Top Ten Web-Design Mistakes article. While it could be advantageous to directly link to these two sections, direct links also have disadvantages.

Say, for example, I linked to a named anchor for #6, which is about JavaScript in links. Sure, you’d see this point first, but further down your screen you’d see #7, which is about adding infrequently asked questions to a FAQ. That’s an odd continuation of a JavaScript discussion, don’t you think? That’s the penalty of starting users in the middle of a page when they don’t understand what the page is about.

The best solution in such cases is to create separate pages for everything that serves as a link destination.

So: you should avoid named anchors and within-page links because they violate users’ expectations for hypertext linking on the Web. A link should bring up a new page. Deviating from this model requires an explanation; you should only deviate if it will save users significantly more time than they’ll waste pondering the non-standard interaction technique.