Follow the standards, dude!
- Published December 5th, 2005 in Web/W3C
Here’s an advice for your own sake: follow the standards. The W3C standards!
While I was coding a website for a client of mine I was writing some code to handle a javascript event raised when a mouse button was clicked. I wanted to access the value of the object that raised the event. On this case, it was an anchor.
So, the code that was generating the event looked like this
<a href="#" name="29" value="29-10-2005" onclick="javascript:setDay();"></a>
And the js code was something like this
function setDay(e)
{
var targ;
if(!e)
var e = window.event;
if(e.target)
targ = e.target;
else if (e.srcElement)
targ = e.srcElement;
// Safari bug
if (targ.nodeType == 3)
targ = targ.parentNode;
alert(targ.value);
}
I put that alert just for debugging. Now, everything was working fine on Safari (KHTML) and IE (didn’t try on Opera). But on Mozilla/Firefox or any other Gecko-powered browser (like Epiphany) it was broken, returning undefined. This seemed quite awkward to me and I was kind of starting to blame Firefox. Afterall, the Javascript code is pretty standard compliant.
After some hours I decided to have a look at the HTML DOM, specifically the Anchor tag. Guess what? According to W3C, the attribute value didn’t exist for this element. What took me so long to catch this bug? The fact that Safari and IE implement carelessly an attribute that shouldn’t exist so everything worked fine on these two browsers.
Rule number one: follow standards. Rule number two: avoid browsers that do not follow standards.
P.S. - By the way, Firefox 1.5 seems quite faster than 1.0.7




Yeah, that’s a good tip. I find that firefox tends to be the best browser to develop javascript stuff, mainly because of the very handy DOM inspector and how it tends to stick to w3c specs. Another good tip is: validate, validate, validate! It won’t make your layout pretty, but will help you finding bugs like this one. ;)
One tip i can give you, is this.. you can pass the object calling the function like:
<a href="javascript:void(0)" name="29" value="29-10-2005" onclick="javascript:setDay(this);”></a>and receive it in the function as:
function setDay(obj) {alert(obj.innerHTML);
}
You would then be able to manipulate the link however you want. Also, if you wanted to specify a “value” of a link, you can put it in the title attribute or as the value of the element, like this:
<a href="#">29-10-2005</a>and access it with .innerHTML or .innerTextAnyway, i’m rambling. Nevermind me. ;)
Yes, 1.5 seems faster than 1.0.7 :D \m/
yesterday i had a similar problem.
on a onclick i wanted to pass as argument an id (database id) Since i was using behaviour, i couldn’t do something like dosomething(123)
a solution was:
put an id as an array
with a regexp extract the id
a href=”#” id=”something[123]” onclick=”dosomething(this)”
function dosomething(obj)
{
database_id = /\[(\d+)\]/.exec(obj.id)[1];
//now you now the id
}