CSS, JavaScript and XHTML Explained

Quirks, random thoughts and funky finds discovered in day-to-day coding.

 

CSS & Javascript Character Entity Calculator August 25, 2007

Filed under: CSS (including hacks), Character Entities, JavaScript, Web Development — Estelle @ 10:38 am

Javascript and CSS Entity Conversion Calculator

Enter your HTML Entity Character number (such as &#2335 or just 2335 - ट) to get the CSS and JS values for that entity. Explanations on how to use the results are below.







(open in new window). named entities | numeric entities | 2,636 entities

Example of JavaScript Charater Entities and the DOM

Example Code (This is the code for the dynamically generated content in the button above).
var calc = document.getElementById("calculator");
var theButton = calc.getElementsByTagName(’button’)[0];
var buttonOptions = [’\u03a0\u03a1\u0395\u03a3\u03a3′, ‘\u2660\u2663\u2665\u2666′, ‘\u221a’];
var rand = Math.floor(Math.random()*buttonOptions.length);
var buttonText = document.createTextNode(buttonOptions[rand]);
var z = theButton.appendChild(buttonText);

The Explanation:
Line 1: gets the div containing the button.
Line 2: gets the button as an elementNode
Line 3: creates an array of strings that are made up of encoded entities. The could also read var buttonOptions = ['� ΡΕΣΣ', '� ♣♥♦', '√'];
Line 4: Creates a random number; in this case either 0, 1 or 2, since there are 3 elements in our array.
Line 5: creates a text node containing the string of javascript character entities.
Line 6: Appends the textNode created in line 5 to the elementNode targeted by line 2. We also create the variable z as a reference to the button’s textNode. I can then use that reference replaceChild() method.

Including Character Entities in JavaScript and CSS

The processes for including special characters in JavaScript and CSS are very similar:

  1. hex encode the numeric HTML entity value.
  2. Preced the hex-value with a slash "\" in CSS and a slash+U "\u" for JavaScript.
  3. Include your entity in your code/markup.

Javascript Character Entities

alert('M\u00E9nage \u00E0 trois.') Try it

CSS Character Entities

    #heart {list-style-type:none;}
    #heart li:before {content:'\2665 '; color:#FF33FF; padding-right:1em;}
  • In all but IE, this will be preceded by a heart

Notes:

  • Don’t know the numeric value of the entity you want to include? named entities in alphabetical order which may be a good place to start. Find the entity you are looking for there by appearance, then do a search for the numeric entity on the Named Entities in Numeric Order page. Or, you can simply search the first 5800 character Entities. At some point I’ll add the rest of ‘em.
  • Remember that IE doesn’t understand the :before pseudoclass with content, and you would have to set the list-style-type as none, or you would get 2 bullets in CSS compliant browsers.
  • In javascript you can also use octal values instead of hexadecimal values for the first 255 or so characters. Yup, that’s trivia!

Including Entities without Encoding them

The reason I always use encoded entities is because I have no clue how to use my keyboard to get the right letters. It’s faster for me to look up the letter from Named Entities in Numeric Order then it is for me to look up the keyboard sequence to display the same character. For the following sample, I pulled up the "character map" that came with my OS.
You can include odd characters if you correctly set your content-Type to UTF-8.
That is the setting for this page, which allows for the following code without HTML or JS encoding.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

alert('Ế ế ∑ ở Ẅ ۹'); Try it

The question is, short of editing your .htaccess character set, how do you tell your external scripts to be served up in UTF-8? This is external and doesn’t work. I tried <script type="text/javascript" src="/articles/entitycalculator.js" charset="utf-8"></script>, but it doesn’t work.

 
 

JavaScript Date Object July 29, 2007

Filed under: JavaScript, PHP, Web Development — Estelle @ 11:18 am

Javascript: Things you should know

Note: This is part IV of a "Javascript: Things you should know" series. I assume readers have an understanding of the core language. This section goes over the creation of date objects. Most resources go over creating a current time date object. This goes over the rest. The previous entry was JavaScript Objects. The next entry list all the date object methods. Please let me know what you think and it there is anything I am missing. Enjoy.

Creating JavaScript Date Objects:

There are fours ways of instantiating a date object:

  1. Without parameters
    Returns the users current date based on client computer’s clock.

    new Date();

    Example:
    var currentTime = new Date();

  2. With a numeric parameter:
    Returns the date measured from midnight January 1, 1970 (+/- GMT diff) plus the time in milliseconds that was passed as the parameter

    new Date(milliseconds);

    Examples:
    var startTime = new Date(0); // Returns
    your time when GMT hit the new year.
    var millenium = new Date ((365*30 + 7)*24*60*60*1000); // returns the millenium at GMT, The +7 is for the leap days.

  3. With a string parameter:
    The string parameter must be a date correctly formatted in string format. The Date object only seems to accept 1 date string format, which is provided in the examples below. The flexibility is only in the day: the number may include a leading zero, but it is not required.

    new Date(dateString)

    Examples:
    var auntsBirthday = new Date("September 4, 1902") // She’s 105
    var modifiedTime = new Date("July 27, 2005 12:22:00") // format must be exact

  4. With an array of parameters:
    Pass the different date element parameters in the order above. If you don’t specify all the parameters, or a parameter is non-numeric, 0 is passed. If your value is numeric, but not a valid value (such as hours == 25) no error will be thrown, though it may be a logic error. The most common error is the month parameter: remember that the arrays start at index of 0, so January is 0 and December is 11.

    new Date(year, month, day, hours, minutes, seconds, milliseconds)

    var modifiedTime = new Date(2007,7,27)
    var modifiedTime = new Date(2007,7,27,13,22,0)

Here are a few examples and what gets returned (javascript must be enabled):

  • currentTime = new Date()
  • timeBasis = new Date(0)
  • lastYear= new Date(-365*24*60*60*1000)

  • var currentTime = new Date("November 4, 2008");

  • anniversary = new Date(2003,8,21)
  • exactTime = new Date(1969,0,3,16,4,12,500)

Note:

  • new Date(0) will not return midnight of January first unless your computer set to GMT.

Common JavaScript Date Object Errors

  • new date()
    //Error: Date is case sensitive
  • new Date("412")
    //
    Error: No data conversion
  • new Date("June 31, 2005 29:95:73 ")
    //Logic Error: Too many hours in your day, and there are only 30 days in June.
    Returns July 2, 2005; which is unlikely your intention.
  • new Date("July 27, 2005 12:22pm")
    // invalid date error - doesn’t understand PM
  • new Date("2007-7-27")
    //Invalid Date: - string in wrong format**
  • new Date(1969,12,3,16,4)
    //Returns January 3, 1970 instead of December 3, 1969. Logic Error: monthArray is 0 - 11.

Notes:

  • When passing the month as a number, remember that the array starts at 0. Optional values are 0-11. Javascript will not throw an error, but there will be a logic error.
  • The date string must be of the correct fomat. The minimum is "Month dd, yyyy", to "Month dd, yyyy hh:mm:ss". The Month doesn’t seem to be case sensitive in my tests, but I haven’t checked all browsers. Good coding practices dictate that it should be capitalized. .
  • JavaScript uses the date of midnight, January 1, 1970 UTC as a starting point for all of its calculations.

An Example of Converting a PHP/Unix date to a usable JavaScript date:

So my quandry was that the date I received was written in an unusable format: The date the server sent was similar to 2007-07-22T22:57:35Z - yyyy-mm-ddThh:mm:ssZ, which is the date in ISO 8601 format (see converting ISO 8601 dates in PHP for a completely different take on conversion). I had to convert an ISO 8601 date to a parameter I could use in the Date object constructor

My first thought was to replace the T and Z with spaces, 2007-07-22 22:57:35 , which looks correct, but isn’t.
As we learned above (see Date error example above), date strings much be in the "Month dd, yyyy" format. The yyyy-mm-dd format will not work.

var myStringDate = "2007-07-22T22:57:35Z";
var myStringDate = new Date(myStringDate.replace(/\D/g, " ")) //returns "invalid date".

My second thought was to split the string into parameters.

var myStringDate = "2007-07-22T22:57:35Z";
var myStringDate = myStringDate.replace(/\D/g, " ");
var dObj = myStringDate.split(" ");
          //array is (2007, 07, 22, 22, 57, 35)
var myDate = new Date(dObj[0], dObj[1], dObj[2],
           dObj[3], dObj[4], dObj[5]);

That works, but gives me the wrong date. We have a logic error. The month array starts at 0. month[07] is August, not July. The solution was to subtract 1 from the 2nd parameter

var myStringDate = "2007-07-22T22:57:35Z";
var myStringDate = myStringDate.replace(/\D/g, " ");
var dObj = myStringDate.split(" ");
var myDate = new Date(dObj[0], (dObj[1]-1), dObj[2], dObj[3], dObj[4], dObj[5]);
document.write("Making a date from a string: " + myDate);



Writing Pretty Dates

Javascript 1.2 gave us some prettier ways of writing out dates. Still, you might not find the format you need with the methods provided. Here are some arrays that you should feel free to cut and paste into your code.

dyOfWeek = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
daysOfWeek = new Array("Sunday", "Monday", "Tuesday", "Wednesday",
             "Thursday", "Friday", "Saturday");
monOfYear = new Array("Jan.", "Feb.", "Mar.", "Apr.", "May", "Jun.",
             "Jul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec.");
monthsOfYear = new Array("January", "February", "March", "April", "May",
    "June", "July", "August", "September", "October", "November", "December"); 

toLocaleDateString() works for much of what I need. But, sometimes you need something a little different. You can either edit using regular expressions, or you can create a pretty date from scratch.

Here are some formats and how to create them. I will use the date we created, the methods described above and the 4 arrays posted here.

(myTime.getMonth() + 1) + "/" + myTime.getDate() + "/" + myTime.getFullYear()
var hours =  myTime.getHours();
var ampm = (hours > 11)? "PM" : "AM";
hours = hours%12;
hours = (hours == 0)? 12 : hours;
time = hours + ":" + myTime.getMinutes() + " " + ampm;
July 2007
monthsOfYear[myTime.getMonth()] + " " + myTime.getFullYear()

Formatting Javascript Dates:

Want to extend the Date object to be nicely formated? Gavin Kistner did the work for us. Extending the Date Object which creates the a custormFormat for the date object. To use this prototype, include the function in your javascript, and call it this way:

var prettyDate = myDate.customFormat('#DDDD#, #MMM# #D#, #YYYY#');
var prettyTime = myDate.customFormat('#h#:#mm##ampm#');

Here’s the code:

Date.prototype.customFormat=function(formatString){ 
    var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhh,hh,h,mm,m,ss,s,ampm,dMod,th;
    YY = ((YYYY=this.getFullYear())+"").substr(2,2);
    MM = (M=this.getMonth()+1)<10?('0'+M):M;
    MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substr(0,3);
    DD = (D=this.getDate())<10?('0'+D):D;
    DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getDay()]).substr(0,3);
    th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
    formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);
     h=(hhh=this.getHours());
    if (h==0) h=24;
    if (h>12) h-=12;
    hh = h<10?('0'+h):h;
    ampm=hhh<12?'am':'pm';
    mm=(m=this.getMinutes())<10?('0'+m):m;
    ss=(s=this.getSeconds())<10?('0'+s):s;
    return formatString.replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm);
	 } 
 
 

Javascript Objects July 20, 2007

Filed under: JavaScript, Web Development — Estelle @ 12:22 am

Javascript: Things you should know

Note: This is part III of a "Javascript: Things you should know" series. I assume readers have an understanding of the core language. This section goes over objects at a very basic level. Most books cover objects in a confusing manner. Below are really simple examples which, if you have been confused, will hopefully make things make sense. The previous entry was JavaScript Switch Statement Quirks.

JavaScript Objects Demystified

Everything in JavaScript is an object except core types. true, false, null, undefined and numeric values are not objects. Strings, with the length property and numerous methods, are objects.

Most JavaScript objects are collections of name-value pairs. I think of objects as associative arrays. The "name" or key of an object is a string except for in the array object where it can be a string or a incremental integer. The value can be any JavaScript value, including an array or other object.

Creating a JavaScript Object

There are two basic ways to create an object which are semantically equal. You can declare an object using an object function and instantiate the object by using the "new" keyword or you can use the object literal method:

  • var obj = new Object();
  • var obj = {}; // object literal method

Assigning properties to an object

An object’s properties can be assigned with the dot operator or like an associative array::

obj.name = "Estelle";
obj["name"] = "Estelle";

the property values can be retrieved in a similar fashion

var myname = obj.name;

var myname = obj["name"];

The difference between using the dot operator versus the array method is that since the key value is a string, you can use reserved words for the "name". If you plan on creating property names based on user input, this can be aspirin for what otherwise would be a headache. Otherwise, the dot syntax is easier, and reserved words should not be used. Using a reserved word is a bad idea. Both the object name and property name are case sensitive.

obj.for = "Estelle"; // produces an error
obj["for"] = "Estelle"; // allowed

Object Literals

Object literal syntax can be used to initialize the entire object.:

var obj = {
  name: "Estelle",
  gender: "Female",
  outfit: {
     top: "t-shirt",
     bottom: "jeans",
     shoes: "hiking boots"
     }
}

You can chain it together:

obj.outfit.shoes; // hiking boots
obj["outfit"]["bottom"]; // jeans

Even though outfit in the example above seems like it is a newly created object within obj, it isn’t:

outfit.shoes; // error, since outfit is not defined
obj.shoes; // undefined, not an error, since obj is defined, but the property shoes has not been assigned a value

Assigning methods to an object

Methods are simply functions tied to objects. For example, toUpperCase is a method of the string object. The simplest way to attach a method to an object is to use an anonymous function:

var greeting = {
  name: "Estelle",
  message: "this was written by ",
  welcome: function(){
     alert("Objects now make sense");
     },
  sayhi: function(){
     alert(this.message + this.name);
    }
}

welcome is a method of the greeting object. Calling greeting.welcome();, with the parenthesis, will cause the alert.

sayhi is also a method of the greeting object. Calling sayhi.welcome();, with the parenthesis, will cause the alert. The this keyword refers to the object that is calling the function, and will be discussed in further detail in a future entry.

Method names are also case sensitive.

the Window object.

All variables that are not assigned as properties of other objects become properties of the window object.

var animal = {};
var myCat = animal.pet = "Sassafrass";

In this case, animal is an object, pet is a property of the animal object and myCat is a property of the window object.

The following all work and return "Sassafrass":

  • animal.pet;
  • window.animal.pet;
  • myCat;
  • window.myCat;

The following may not return what you expected:

  • pet; // throws an error as pet is a property of the animal object, not the window object
  • window.pet; // undefined
  • window.animal // evaluates to object.

Note: JSON, or JavaScript Object Notation, is a subset of JavaScript’s oject literal notation.

JavaScript Object Properties and Methods

All objects in javascript inherit from the Object object, and therefore inherit the properties and methods of Object, including:

  • constructor property
  • prototype property
    used to assign new properties and methods to future instances of the object type.
  • hasOwnProperty() method
  • isPrototypeOf() method
  • propertyIsEnumerable() method
  • toString() method
  • toLocaleString() method
  • valueOf() method

Extending Objects

It is fairly simple, though not always necessary, to extend objects with new methods and properties. Use the protoype property, inherited from the Object object to add methods to an object. Here are some examples of String, Array and Date object methods.

String.prototype.capFirst = function(){
   return this.charAt(0).toUpperCase() + this.substr(1);
}

String.prototype.trim = function () {
  return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

Array.prototype.sortCaseInsensitive = function(){
    return this.sort(function(a,b){ return (String(a).toLowerCase() > String(b).toLowerCase())? 1: -1;}
}

Date.prototype.customFormat = function(formatString){
  //The code for this is in the javascript date object article.
}