Category Archives: Web

A better $ function

U may remember the $ function from prototype.js and the famous Top 10 JavaScript Functions.

It was when it struck me, that the multiple arguments to the $ function returns an array, a numeric index based array. So to refer to the numeric indexes, u need to remember the order that u’d specified ur ids.

My new $ function is a little better, it returns an object with the id’s name as the member name.

function $() {
	var elements = {};
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements[arguments[i]] = element;
	}
	return elements;
}

So if u use multiple ids as this…

var myObjects = $('id1', 'id2');

// Now u can use the references as 
myObjects['id1'].setAttribute("class", "myclass1");
myObjects['id2'].setAttribute("class", "myclass2");

New HTML Version

In Tim Berners-Lee’s Blog entry, Reinventing HTML, It seems W3C failed to implement the new XHTML standard amongst the developers. Thanks to all easy-go browsers, which will not validate tags, attributes, etc…

456bereastreet.com suggests some of the changes required in the new HTML version, I’d say version 5.0. Some of the points mentioned are.

  • New attributes that will make forms easier to validate: required for input, textarea, and select elements, maxlength for textarea elements.
  • The reappearance of the start and value attributes for ol and li elements respectively.
  • Stricter, XHTML-like syntax: make lowercase required for all element and attribute names, make quoted attribute values required, require all end tags that are currently optional.

Changes required for HTML v 5.0

  • Browsers shouldn’t render anything if there is any major error in Document, or atleast give a warning
  • Direct Form validation support: no need of Javascript for trivial validations
  • A “TABLE” like tag that works as well as “TABLE” for layout and positioning, Developers are sick of making CSS work for all browsers

Web Accessibility: Anchor tags for Popup windows

Many a times, on your page, you need to have a JavaScript pop-up window for Slideshow, gallery, comment form, etc. But you also want to have your site WAI compatible. What do you do ?

The idea is to pop-up windows in Browsers that support JavaScript and provide actual href value to the Anchor tag a. But also provide an onclick event that pops up the window.

Consider I want to have a slideshow on a particular link, which actually should pop a 500 x 400 window keeping WAI in its place. This is the code that helps me solve the problem.

Code

...
<script type="text/javascript">
function popW(url) {
  window.open(url, 'newPop', 'width=500,height:400, directories=0');
}
</script>
...
<a href="/slide-show.html" onclick="popW('/slide-show.html');return false;">Slideshow</a>
..

Let us understand it..

  • The Slideshow page is spearate document/page
  • The anchor’ href attribute specifies the correct link to the page
  • The onclick handler pops the window, in browsers with JavaScript enabled
  • Notice return false; after the function call in onclick. This prevents JavaScript enabled browsers to load the href link on the current page

Search Engine Optimization Checklist

Got a site online? and want to make it really SEO Friendly?

Here is a checklist that you need to consider before you put your site live.

SEO Checklist

  • Find keywords and phrases, and try to include them in the title element.
  • Make sure the keywords and phrases occur in the page, But need not overdo its occurance
  • Use meta tags, to define keywords and description
  • Use keywords and phrases in heading elements like h1, h2, ..
  • Try structuring the content, using heading elements instead of changing font-sizes and colors, they can also be applied to headings
  • Do not keep a splash page, I hate it, so do Search Engines
  • The URL should ideally contain keywords related to that page, Apache URL Rewriting
  • Avoid GET parameters to change content of page
  • Avoid using javascript URLs, if you do, remember to add actual hrefs that lead you to that page or similar content
  • Make sure none of the links are created by JavaScript, they should be available in plain HTML
  • Adhering to semantic content, All menu links should ideally go into a list using li
  • Avoid writing CSS inline, keep them in files and call using link href="style.css" ... tag
  • Use semantic markup like em tags for italics and strong for bold text.
  • Try placing the actual content of the page at the begining…, Use CSS to change its position
  • The image tags should ideally have alt attribute that defines the image, inclusion of keywords in it will be helpful
  • The image filename should ideally describe the image

Spawning popup windows in Firefox

New browsers like Firefox(my fav.), IE 7 are very intelligent, they will not allow the standard popup of window.onload or standard…

...
<body onload="load_popup()">
...

They have decent pop-up blockers, which we want to escape.

The new browsers, will consider it a spammed popup, and will kill it before its spawned. They will only create a popup if there is user interaction, as you can see, window.onload and body’s onload is not user interaction.

So, how should my advertiser’s pop-up be displayed? What user interaction should I wait before I get my popup?

There is a trick, you users must have crossed by but may be you have not identified it. You can pop a window on any user interaction, and such a action is not considered as spam pop by Firefox.

What we do is add an EventListener to a particular piece of content, which u are sure that the visitor is going to read. Browsing habits state that most user often keep clicking and selecting a particular text which they are reading. And that is our exact target.

Let us consider within our page, we’ve got a div with id named as “article”. What we’ll do is add a click event Listner to it.

<div id="article">
...
</div>

<script type="text/javascript">
function make_popup() {
  // open any popup window you want.
  url = "http://www.yahoo.com/";
  window.open(url, "popwindow", "width=550,height=300,status=0,directories=0");
}

aid = document.getElementById("article");
aid.addEventListener("click", make_popup, false);
// Adds a click event for div tag with id article
// Which spawns the popup.

</script>
Click here to check if popup loads….

And so at last the beast fell and the unbelievers rejoiced.
But all was not lost, for from the ash rose a great bird.
The bird gazed down upon the unbelievers and cast fire
and thunder upon them. For the beast had been
reborn with its strength renewed, and the
followers of Mammon cowered in horror.

JavaScript

A lot is still unexplored in this area (of JavaScript). I shall try to help out others, who are keen to get with it.

var js = {
  lang: "JavaScript",
  amIGood: function () { return "O u bet!"; },
  start: function () { return "Read more on ruturaj.net"; }
};

alert(js.amIGood());
alert(js.start());

URL Rewriting for content pages

Many of the content sites (blogs, news sites) that you see these days have a specific url for each page. Eg. News.com

Many of the sites have something like /news/75-news-title.html. You can’t have a actual distinct page for each content. The most common solution to this is URL Rewrite the content.

The idea is to grab the specific content from the URL and then map that content, id, or whatever from the url as a get parameter’s value to a specific page.

In the above scenario, check the URL: /news/75-news-title.html. What is commonly done is the content_id the key by which the content is mapped in the content table is placed in the URL along with the title.

As in this case
Content ID: 75
Title Text: news-title (The hyphens are to make it readable instead of %20 for space)

So lets assume that we have a page called news.php in which we will give a get parameter as newsid. All we got to do now is write the URL Rewrite rule using Apache’s mod_rewrite engine.

We’ll use the RewriteCond and RewriteRule

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_URI} /news/([0-9]+).*\.html$
    RewriteRule (.*) /news.php?newsid=%1 [L]
</IfModule>

Now Let us look how we built the thing.

  • First we used the Server Variable REQUEST_URI, to match the pattern with the request. The variable is referenced using %{SERVER_VARIABLE} format.
  • The RewriteCond is basically a If condition, which means if the condition is true, only then the condition or rules below that statement will be executed. That means the pattern should match for the rule to work
  • The regular expression pattern we made was accepting a integer value after /news/, After that integer value any text can come. But should end with .html. As emphasized by the $ at the end.
  • Now if the Condition works, we need to write the rule for it, so we use RewriteRule. The first argument is .*, which means accept any URL
  • The second argument is the actual mapping of the news.php with the newsid parameter. Check that we’ve used %1 which means the first back reference of the RewriteCond regex pattern
  • Since our pattern was /news/([0-9]+).*\.html$ and had just one class in it, that class i.e. ([0-9]+) should be referenced by %1 in the RewriteRule directive

The magician, .htaccess file

Long before anything like web.config or web.xml was used/invented, Apache had this wonderful file “.htaccess”

This file as you would expect, is a file to control the Web Application’s behaviour. The possibilities with this file are endless… from Password Protected Directories to Complex URL Rewrites, All can be done using this file.

.htaccess

The file’s extension is “htaccess” and has no initial filename. This comes from the *nix’s legacy system of having all the hidden files starting with a period “.”

This file could be placed in any directory of your web application. Lets say your DocumentRoot is /domains/ruturaj.net. Now if you place the .htaccess file in the main DocumentRoot, Any configurations that are present in the .htaccess file are available in all the subfolders of ruturaj.net

So if I put the fol. code in the .htaccess file,

DirectoryIndex rutu-default.php

All the sub directories or folders in directory ruturaj.net will have rutu-default.php page as the default index page.

But to ensure that the .htaccess file is read and implemented, you need to tell Apache.
To tell Apache which is the standard Configuration file, you need to modify the entry in the httpd.conf file. AccessFileName is the parameter which specifies which file is the “.htaccess” file, by default, the value of the parameter is set to “.htaccess”

AccessFileName .htaccess

There is also another parameter, AllowOverride, which tells Apache whether to read and implement the AccessFileName. You need to make the foll. settings in your VirtualHost or Directory mapping as

AllowOverride All

This will enable the implementation of the .htaccess file.

Creating a Live Score Board Client Logic

The the custom JavaScript object player is defined as below.

function player () {
	
	this.name = '';
	this.serving = false;
	this.gamepoint = 0;
	this.sets = new Array();
	
	this.toString = function() {
		return (this.name + ": " + (this.serving ? 'Serving' : 'Facing') + "\n" + this.sets + "\n" + this.gamepoint);
	}
}

The sets member variable is an array.


Next comes the import updateScoreBoard function

function updateScoreBoard() {
	sc = xmlScore;
	pDOM = sc.getElementsByTagName("player");
	players = new Array();
	for (i=0; i<pDOM.length; i++) {
		players[i] = new player(pDOM[i].getAttribute("name"));
		players[i].name = pDOM[i].getAttribute("name");
		if (pDOM[i].getAttribute("serving") == 1) {
			players[i].serving = true;
		}
		// Now get the match sets for the players
		setDOM = pDOM[i].getElementsByTagName("set");
		for (j=0; j<setDOM.length; j++) {
			players[i].sets[j] = setDOM[j].childNodes[0].nodeValue;

			// Now get the curent Game point for the players
			players[i].gamepoint = pDOM[i].getElementsByTagName("gamepoints")[0].childNodes[0].nodeValue;
		}


//		alert(players[i].toString());
	}

	// Now that all data has been gathered...
	document.getElementById("player1").innerHTML = players[0].name;
	document.getElementById("matchplayer1").innerHTML = players[0].name;
	document.getElementById("player2").innerHTML = players[1].name;
	document.getElementById("matchplayer2").innerHTML = players[1].name;

	//Serving
//	document.getElementById("serving1").innerHTML = (players[0].serving)?'o':'';
//	document.getElementById("serving2").innerHTML = (players[1].serving)?'o':'';

	// Sets
	document.getElementById("setplay11").innerHTML = players[0].sets[0];
	document.getElementById("setplay12").innerHTML = players[0].sets[1];
	document.getElementById("setplay13").innerHTML = players[0].sets[2];
	document.getElementById("setplay21").innerHTML = players[1].sets[0];
	document.getElementById("setplay22").innerHTML = players[1].sets[1];
	document.getElementById("setplay23").innerHTML = players[1].sets[2];

	// Game points
	document.getElementById("gamepoints1").innerHTML = players[0].gamepoint;
	document.getElementById("gamepoints2").innerHTML = players[1].gamepoint;
}
</script>

Notice the players variable is an array of player object. The traversing of XML content is easy. If you are unable to understand JavaScript DOM methods check following links

You can find a full working example here, Live Score Board