Ugly quotes… how beautiful they are…

I think I had already filed a bug about this on the WordPress Trac… but it wasn’t until today that I found the solution for placing JavaScript inside a Wordpress post! And I owe it all to Matt Fletcher’s plugin “Strip Smart Quotes“.

His plugin replaces the ‘prettified’ HTML equivalents of single and double ‘ugly’ quotes. These equivalents break all functionality for any javascript code you would like to run in a post.

I’m also going to see if I can use manual breaks (<br />), instead of having the Wordpress engine wrap paragraph elements around everything.

I added the 8243 (another ‘pretty’ double quote) to the array and 8230 (the ‘prettified’, single-character equivalent of ‘…’).

&#8216;, &#8217; and &prime; are the equivalents of ‘.
&#8221;, &#8220;, &#8243;, &Prime; are the equivalents of “.
… is the equivalent of …

Too bad about the automatic placing of breaks… that means I can’t have any manual breaks when writing scripts. Let’s see what I can do. I’ll try placing a Freemind Mindmap… like I explained in this post to the Freemind FAQ about Java Applets in XHTML.

I’ll just create a ‘div’ called ‘placetexthere’… and see if I can append it an paragraph… basic stuff. Here is a transcript of the code, and following the transcript, there should be a line that says ‘If you can read this, you are standing too close.’.

<div id="placetexthere"></div>
<div id="scriptcontainer"><script type="text/javascript">var theparagraph = document.createElement("p"); var bold = document.createElement("strong"); var thetext = document.createTextNode("If you can read this, you are standing too close."); bold.appendChild(thetext); theparagraph.appendChild(bold); var thetarget = document.getElementById("placetexthere"); thetarget.appendChild(theparagraph);</script></div>

This should work fine… if it doesn’t, I guess it should work fine from a script file. Which I’m too lazy to write right now… (more…)

True Dynamic Element Object Creation

After posting about my adaptation of the del.icio.us playtagger, I decided to reduce the code in size a bit… and maybe even do some comparisons. After looking at the previous lines of code, I concluded that the most space was occupied by DOM methods like setAttribute or document.createElement. So the best way of reducing all that space was by creating some sort of ‘element object creator’… surely, I wasn’t the only one to suffer from ‘manually-dynamically’ creating elements… but there were only a couple of initiatives,… nothing compatible that degraded gracefully when using ‘application/xhtml+xml’ or ‘text/html’.

So, after coding for a while, I came up with this:

function crEl() {
  var a = arguments; //arguments
   var nN = a[0].toLowerCase(); //node Name
   var tE = document.createElement(nN); //temporary element
   var aPL = (a.length - 1)/2; //length of attribute and value pairs
   var dM = (aPL%2)-(Math.floor(aPL%2)); //decision maker
   if(dM === 0) { //if there is a value for each attribute name
      if(nN == “param”) { //this applies for the param element
         for(var i = 0; i < aPL; ++i) {
            var j = 1+(i*2);
            tE.setAttribute(”name”, a[j]);
            tE.setAttribute(”value”, a[j+1]);
         }
      } else { //if the element is not a param element…
         for(var k = 0; k < aPL; ++k) {
            var l = 1+(k*2);
            tE.setAttribute(a[l], a[l+1]);
         }
      }
      return tE; //returns the element
   } else {
      return false; //Perhaps an alert(nN); would be better?
   }
}

You can copy and paste the above function, and test it out at the Mini Javascript Editor. Here’s a small test case (copy and paste it in the editor along with the function):

var par = crEl("p");
var div = crEl("div","id","mydiv","style","background-color:#ffffff;");
out(par.nodeName+", "+div.nodeName);
out(typeof(par)+", "+typeof(div));
out(par.hasAttributes()+", "+div.hasAttributes());

(more…)

MSN Spaces, Too Firefox Friendly?

I still remember that on the early days of the MSN Spaces, if you wanted to fully experience your Space, you had to use IE6

Nowadays, Microsoft developers are putting a lot of effort into making their products and webpages more standards compliant. Across the blogosphere, there are many posts about this. Molly H. wrote:

Many readers here also follow the IEBlog (a good practice for contemporary Web developers and designers). Expect significant repairs to most existing bugs, implementation of long-awaited CSS features such as fixed positioning, child selectors, and attribute selectors. Alpha transparency in PNGs? Yes! The XML declaration will now be available without disturbing the DOCTYPE switch, and object handling will be improved with proper fallback.

R. Scoble announced:

Thomas Hawk broke the story this afternoon that Live.com now supports Firefox, but Sanaz Ahari, PM on the Live.com team just told me the news officially minutes ago. She says there’s a minor CSS bug in the search results which will be fixed soon too.

Then again, while I was updating my Space profile in Firefox, I noticed that my contact card didn’t show either my email or my phone numbers… so I opened the page in Internet Explorer, signed in with my Passport account, and was surprised to see that IE was showing 3 JavaScript errors… First one was on line 3, character 18095. As you can see below, my picture and/or contact card isn’t showing:

MSN Spaces have JavaScript Errors in Internet Explorer

I checked on Firefox (using the JavaScript Console) to check out if there were JavaScript errors, and there were none. Though the Console did show a lot of CSS errors (’dropped declarations’). I also decided to check my Space’s source for w3c compliance. There were 424 errors.

Here is a screenshot of the page in Firefox:

Firefox doesn't have JavaScript Errors in MSN Spaces

As a note, I’m using the Flyakite mod for Windows… it shouldn’t have any effect on how pages are rendered in IE, but who knows…

Anyhow, I took the liberty of writing to the IEBlog staff, since trying to locate someone to talk to on MSN Spaces was a bit difficult.

Here’s what I sent them:

Hello IE developers. I’m writing to you since I couldn’t find an easy way to report an error on the MSN Spaces site.

Since I’m from Mexico, my Space is displayed in spanish… unfortunately the templates for spanish language provoque javascript errors… and don’t validate (they are also displayed in quirks mode).

In IE6 this means that some functions aren’t displayed, like my contact card. Ironically, Firefox is able to show the contact card (but doesn’t show more info, like the email and phone).

I just thought you should know. For a screenshot of the errors and a comparison, visit rolandog.com.

I’m thinking it’s the language templates they have, but it really is only up to them to really find out what is going on.

Redesign - Compliance Theme v0.1

Ooook, this one will be a large update. I guess this has been my first official attempt at theming WordPress. I’ve still got some more work to do. Unfortunately, this theme lacks flexibility in that you have to enter your categories manually using get_links(). I’m going to try to make this the least inflexible and release the code, version by version. This first one is version 0.1.

I’m writing this post because I need feedback. I feel that the theme looks nice enough for now, although the feel doesn’t differ much from the default WordPress theme. I need to change the text color a bit, including colors for the links and sidebar links. This theme is mainly about Compliance… hence the name. It validates as XHTML 1.1. It is served as application/xhtml+xml, but will degrade gracefully to HTML 4.01 Strict and text/html if the browser doesn’t support application/xhtml+xml. The JavaScript used also degrades nicely, in that the Sidebar menu starts expanded and is only collapsed by JS.

This was achieved by using the moo.fx javascript library for the effects, and I also adapted the code that is currently used in their homepage (I lintified it a bit, though. I also used Neil Crosby’s PHP script for serving appropriate MIME types. I also followed Dean Edwards article that shows you how to overcome the lack of support for a common ‘onload’ event in all browsers.

I encountered some weird bugs while adapting the moo.fx script. I’m such a JavaScript newbie to have a say in the matter, but I discovered (or learned it the hard way, for that matter) that Firefox’s way of handling the DOM (like a tree diagram of the html in the doc.) is a bit weird… it counts a line break as a node!!111 (sic). I expected it to ignore any useless whitespace and take only elements into account…

Anyhow, I did some research and found out that, indeed… some browsers behave in a different way when it comes to whitespace. Check out these three references.

Using JavaScript and the DOM allows you to write in a page after it has loaded… it can help you write into a specific section like all those AJAXified pages do. But in this case, it is used to accomplish in a dynamic way what CSS Selectors can do in a static way.

Anyhow, I need to know about browser compatibility… so if any passers-by can give me some feedback… I’ll thank you for that. So far I’ve tested it only on two browsers (IE, and FF).

So far here is the ‘test list’:

  • opera logo :|
  • netscape logo :|
  • mozilla logo :|
  • internet explorer logo
    • 6.0 on Windows XP SP2 :roll:
    • 6.0 on Windows XP SP1 :D
    • 6.0 on Windows ME :D
    • 5.? on Windows or Mac :oops:
  • firefox logo :D
  • safari logo :D
  • konqueror logo :|

Legend: :| means ‘not tested’, :D means ‘works ok’, :roll: means ‘works, but is buggy’, :oops: means ‘totally fails, dude’.

According to QuirksMode, the script shouldn’t be much of a problem, since it manipulates nodes. Though I’m not sure about the moo.fx script.

Well, about IE6 on XP. It renders the page in a buggy way… the text shows up as if it were text in a really low quality jpg image:

Pixelated Fonts

A bit off topic, but it needs to be said. While designing the header, I had chosen these set of styles and finally decided upon #3, but I then realised that even though its 2006 now, there isn’t an easy way of distributing fonts needed to render a webpage properly. Bummer.


#header1, #header1 a, .description1{
font-family: Alba Super;
color: #000000;
background-color: #ff6e00;
}

#header2, #header2 a, .description2 {
font-family: Batik Regular;
color: #ffffff;
background-color: #0091ff;
}

#header3, #header3 a, .description3 {
font-family: OldgateLaneOutline;
color: #FFFFFF;
background-color: #000000;
}

#header4, #header4 a, .description4 {
font-family: 'Trebuchet MS', Helvetica, Sans-Serif, Verdana;
background-color: #73a0c5;
color: #ffffff;
}

h1, h1 a, h1 a:hover, h1 a:visited, .description1, .description2, .description3, .description4 {
line-height: 1.2em;
letter-spacing: 0;
text-align: center;
word-spacing: normal;
text-decoration: none;
}

In other news,… I start my final (hopefully) semester as a college undergraduate. By the end of June I will be a Chemical Engineer. Woot!

This means I’ll be once again posting seldomly. Thats too bad, really. I felt like I was getting the hang out of scripting and design. I really wanted to make this theme something and that could be visited even by users in handheld devices. I just finished adapting some tips and styles from CollyLogic about designing for better handheld browsing (also see this for handhelds and CSS). There is still so much more room for improvement, but I’ll leave it like that for now.

After reading a lot to check about good design habits, and the like, I think I can finally say that my blog is not in any sort of HTML Hell for now.

Well, looking back at what I wanted to do during my vacations I can say that I didn’t accomplish the following:

  • Make custom section about music and recent tracks using Cache_Lite and either MiniXML and XSLT or XML_Transformer
  • Learn Python
  • Loose a few kilograms
  • Install a couple of cool WordPress plugins
  • Do the same for my del.icio.us feed, and for other web services as well, like El Oso did (who btw has a great blog design).
  • Finish all those darned drafts I have waiting to be published.

Oh well, enough for now. I guess I’ll just publish this and move on. If I go on a bit more, this might turn into one of my ‘ramblings‘.

Update: I tested the page in Internet Explorer 5.? in a Mac, and also in Safari. Safari passes the test. Unfortunately, Internet Explorer doesn’t. It fails it miserably. Argghh.

Apegándonos a los Estándares

El día de ayer y el de hoy por la madrugada me la pasé entretenido en uno de mis muchos pasatiempos: me dediqué a asegurarme que mi plantilla de WordPress fuera lo más apegada a los estándares. Tengo entendido que HTML 5 y XHTML 2 están a la vuelta, … y cada uno traerá consigo buenas ventajas.

Lo bueno es que en estas fases XHTML 1.1 y HTML 4.0 Estricto son casi lo mismo. Lo que difiere entre ellos es la declaración de tipo de documento y que además que hay ciertos ‘elements’ que en XHTML deben de cerrarse (ejemplo: <br />, <link ... />).

El día de ayer comencé con el rediseño de esta página, y pues lo que me mantuvo entretenido fue el hecho de que en Internet Explorer si funcionaba cierto código de JavaScript que no funcionaba en FireFox (algo nunca antes escuchado).

Había encontrado un artículo que me ayudó a servir apropiadamente mi contenido (servir como XHTML si el browser lo soporta, y si no como HTML). Después intenté poner una sección con un ‘template’ que utilizaba un script para la inclusión de un mapa de Frappr (al cual, por cierto, tienen que añadirse). El script de Frappr utiliza document.write(); para escribir un iframe cuyo código fue concatenado por javascript. Esto en XHTML no es posible…

Básicamente mi afán por apegarme a los estándares me estaba ahogando. En XHTML (servido con MIMEtype apropiado de application/xhtml+xml) no se puede escribir en el documento con JavaScript así como así.

Se necesita tener ciertas consideraciones que afectan a todos los ‘browsers’… pero hay que saber cómo reparar el código descompuesto.

Rápidamente mi ‘dique’ rápido rediseño se tornó en algo un poco más para fumarolos de código, y no tanto para el ‘amateur’ que va de paso (como yo).

Lo bueno es que contaba con utilidades de validación de javascript y de eliminación de errores.

Después de enterarme que tenía que usar la función de createElement, me enteré que hay más consideraciones especiales para no ‘quebrar’ el código.

Esta es la plantilla que se coloca adentro de cada carpeta adentro de /wp-content/themes/. Ya que se subió el archivo a cada carpeta (y se le da CHMOD 666)… jejeje \m/, entonces uno puede proceder a escribir una página en WordPress y le aparecerá en la lista desplegable la plantilla que se subió. En mi caso, es friends.php.

Nota Importante: es necesario no dejar una línea vacía (un ‘enter’ de más) entre el comentario y la función de get_header, o de lo contrario se rompe la validación del documento… y en XHTML simplemente aparecerá un documento color crema, especificando que hay un error.

<?php
/*
Template Name: FrapprFriends
*/
?>
<?php get_header(); ?>

<div id="content" class="narrowcolumn">

<h2>Frappr Map:</h2>
<div id="frappr"><noscript><p>Unfortunately, you do not have a javascript enabled browser.</p></noscript></div>
<script type="text/javascript" src="http://rolandog.com/wp-content/mapwidget.js"></script>
</div>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

El siguiente código es el contenido del archivo mapwidget.js… modificado. El original se encuentra en http://www.frappr.com/ajax/mapwidget.js. El primer ‘párrafo’ de código es proveido por Frappr en la sección de ‘Widgets’ de un grupo.

var frappr_mapheight = 480;
var frappr_mapwidth = 480;
var frappr_maplat = 25.650432;
var frappr_maplon = -100.386059;
var frappr_mapzoom = 15;
var frappr_host = "http://www.frappr.com/";
var gid = 73345;
var frappr_url = frappr_host+"?a=mapwidget";

El siguiente bloque es el script modificado. Lo único que cambia es el código que escribe en el documento. En lugar de utilizar document.write(); se utiliza document.createElement();.

addToUrl('req','map');
if (typeof frappr_mapwidth == "undefined") {frappr_mapwidth = 300;}
if (typeof frappr_mapheight == "undefined") {frappr_mapheight = 300;}
if (typeof frappr_mapzoom == "undefined") {frappr_mapzoom = 7;}
if (typeof frappr_maplat == "undefined") {frappr_maplat = 43;}
if (typeof frappr_maplon == "undefined") {frappr_maplon = -97;}
frappr_mapwidth = frappr_range_check(frappr_mapwidth,50,2000,300);
frappr_mapheight = frappr_range_check(frappr_mapheight,50,2000,300);
frappr_mapzoom = frappr_range_check(frappr_mapzoom,1,15,7);
frappr_maplat = frappr_range_check(frappr_maplat,-90,90,43);
frappr_maplon = frappr_range_check(frappr_maplon,-180,180,-97);

function frappr_range_check(v,min,max,defaultval) {
if (isNaN(v)) { v = defaultval;}
else if (v > max) {v = max;}
else if (v < min) {v = min;}
return v;
}

addToUrl('width',frappr_mapwidth);
addToUrl('height',frappr_mapheight);
addToUrl('zoom',frappr_mapzoom);
addToUrl('lat',frappr_maplat);
addToUrl('lon',frappr_maplon);
if (typeof gid != "undefined") {addToUrl('gid',gid);}
if (typeof gname != "undefined") {addToUrl('gname',gname);}

function quoted(str) {
return (str !== null) ? '"' + str + '"' : '""';
}

function addToUrl(name,val) {
frappr_url+=("&"+name+"="+val);
}

function createElement(element) {
if (typeof document.createElementNS != 'undefined') {
return document.createElementNS('http://www.w3.org/1999/xhtml', element);
}
if (typeof document.createElement != 'undefined') {
return document.createElement(element);
}
return false;
}

if (document.getElementById) {
tff = document.createElement("iframe");
tff.setAttribute("id", "frappr_mapwidget_frame");
tff.setAttribute("height", quoted(frappr_mapheight));
tff.setAttribute("width", quoted(frappr_mapwidth));
tff.setAttribute("frameborder", "0");
tff.setAttribute("src", frappr_url);
tff.setAttribute("marginwidth", "0");
tff.setAttribute("marginheight", "0");
tff.setAttribute("vspace", "0");
tff.setAttribute("hspace", "0");
tff.setAttribute("allowtransparency", "true");
tff.setAttribute("scrolling", "no");
document.getElementById("frappr").appendChild(tff);
}

Los dos bloques de JavaScript los guardé en el documento mapwidget.js. Y con eso quedó lista la infraestructura necesaria para que el mapa de los amigos quedara abierto para el público… además de que sigue validando como XHTML.