Creating an unobtrusive website is not an easy task, it requires deep knowledge of the web technologies involved in creation of a website, like CSS, XHTML, XML and of the programming language the developer choses to use, like PHP, VB.NET, C#.
Doing it unobtrusively means doing it the right way, because it forces the web developer to keep the web layers separate, that is not messing the page content with inline styling or javascript.
The three layers of web are:
- the Content Layer - HTML
- the Presentation Layer - CSS
- the Behavior Layer - JavaScript
the Obtrusive way:
<span id=”theSpan” style=”color: #ff0000;” onclick=”doSomething();”>sample text</span>
the Unobtrusive way:
<span id=”theSpan” class=”text”></span>
The unobtrusive way will now force you to use Cascading StyleSheets (CSS) and JavaScript:
CSS:
.text {
color: #ff0000;
}
JavaScript:
function doSomething() {
var ctl = document.getElementById(“theSpan”);
…
rest of the code
}
Using Objects:
var MyCustomObject = {};
MyCustomObject =
{
func_1: function()
{
// … code
},
func_2: function(msg)
{
alert(msg);
// … code
}
};
Accessing Objects’ methods:
alert(MyCustomObject.func_1());
MyCustomObject.func_2(“Function called!”);
Now we can create our own real world example, and for this one I’ll show you how can you store a value in a cookie, unobtrusively.
The code will be splitted in 4 sections as follows:
- Section #1 -Main Functions to handle Cookie
- Section #2 - Main Functions to handle Events
- Section #3 - Setting Event Handlers on controls
- Section #4 - Clean up the code
// SECTION #1
//=========================================
//
// Main Functions to handle cookies
var Page = {};
Page =
{
/* { Check to see if the client browser has cookies enabled } */
checkCookies: function()
{
return (((document.cookie) || (navigator.cookieEnabled)) || Page.OnError(“Error: Cookies are disabled!”));
},
createCookie: function(name, value, days)
{
if (Page.checkCookies()) {
if (days) {
var date = new Date(),
_time = date.getTime(),
_period = (days * 24 * 60 * 60 * 1000);
date.setTime(_time + _period);
var expires = “; expires=” + date.toGMTString();
}
else { expires = “”; }
}
return document.cookie = name + “=” + value + expires + “; path=/”;
},
readCookie: function(name)
{
if (Page.checkCookies()) {
var cookieName = name + “=”;
var cookies = document.cookie.split(‘;’);
for(var i = 0; i < cookies.length; i++) {
_c = cookies[i];
while (_c.charAt(0) == ‘ ‘) {
_c = _c.substring(1, _c.length);
}
if (_c.indexOf(cookieName) == 0) {
return _c.substring(cookieName.length, _c.length);
}
}
}
return null;
},
deleteCoookie: function(name)
{
return Page.createCookie(name, “” , -1);
},
onError: function(msg)
{
if (!msg) { /* { “msg” parameter is missing } */
return null;
}
else if (msg.length != “”) { /* { Check to see if it’s not an empty string } */
alert(msg);
}
}
};
The checkCookies function will return a boolean value (true or false) if cookies are enabled or disabled respectively. Optionally there can be set an error message to be displayed if cookies are disabled.
The createCookie function will create a cookie file on the client computer. It takes 3 parameters:
- name: as String, represent the name of the cookie,
- value: represent the value to be stored in the cookie (can be anything),
- days: as Integer, represent the time this cookie should exist on the client computer until it would be deleted.
The readCookie function will return the value stored in the cookie. It takes one parameter:
- name: as String, the name of the cookie to be read.
The deleteCookie function will delete the selected cookie from the client computer. It takes the same parameter as the readCookie function.
The onError function will return a custom message in an alert window. It takes one parameter:
- msg: as String, the message to be displayed in the alert window.
Also, the msg parameter can be omitted.
// SECTION #2
//================================================
//
// Create main functions to handle Events
var EventHandler = {};
EventHandler =
{
addEvent: function(theEvent, theControl, theFunction)
{
if (theControl.addEventListener) { theControl.addEventListener(theEvent, theFunction, false); }
else if (theControl.attachEvent) { theControl.attachEvent(“on” + theEvent, theFunction); }
},
removeEvent: function(theEvent, theControl, theFunction)
{
if (theControl.removeEventListener) { theControl.removeEventListener(theEvent, theFunction, false); }
else if (theControl.detachEvent) { theControl.detachEvent(“on” + theEvent, theFunction); }
}
};
The EventHandler Object methods will help us create unobtrusive code. They are self-explanatory so I won’t elaborate them.
// SECTION #3
//=====================================
//
// Set Event Handlers on controls
//
var cookieName = “MyCookie”;
var PageManager = {};
PageManager =
{
createCookie_btnClick: function() /* { Set cookie values } */
{
var cookieValue = document.getElementById(“CookieValueTextBox”).value;
var daysToKeep = “7″;
if (cookieValue != “”) {
Page.createCookie(cookieName, cookieValue, daysToKeep)
}
else {
Page.onError(“You must set the cookie value!”);
}
alert(“Cookie created.\n Cookie name: “ + cookieName);
},
readCookie_btnClick: function() /* { Read the cookie } */
{
var spanCtl = document.getElementById(“ShowCookieSpan”);
if (!spanCtl) {
return false;
}
else {
spanCtl.innerHTML = Page.readCookie(cookieName);
}
},
deleteCookie_onUnLoad: function() /* { Delete cookie if found } */
{
if (!Page.readCookie(cookieName)) {
return null;
}
else {
Page.deleteCoookie(cookieName);
/* { update the span element } */
var ctl = document.getElementById(“ShowCookieSpan”);
ctl.innerHTML = “”;
alert(“cookie: “ + cookieName + ” has been deleted!”);
}
}
};
These functions will be assigned to our designated elements when the page will be loaded in the browser.
// SECTION #4
//=========================================
//
// Add selected events on page load and remove them on page unload
// Clean up the code
var Controller = {};
Controller =
{
runOnLoad: function()
{
var ctl_1 = document.getElementById(“CreateCookieButton”);
var ctl_2 = document.getElementById(“ReadCookieButton”);
EventHandler.addEvent(“click”, ctl_1, PageManager.createCookie_btnClick);
EventHandler.addEvent(“click”, ctl_2, PageManager.readCookie_btnClick);
alert(“Events attached”);
},
runOnUnLoad: function()
{
var ctl_1 = document.getElementById(“CreateCookieButton”);
var ctl_2 = document.getElementById(“ReadCookieButton”);
EventHandler.removeEvent(“click”, ctl_1, PageManager.createCookie_btnClick);
EventHandler.removeEvent(“click”, ctl_2, PageManager.readCookie_btnClick);
/* { Delete Cookie } */
PageManager.deleteCookie_onUnLoad();
alert(“All clear”);
}
};
window.onload = Controller.runOnLoad;
window.onunload = Controller.runOnUnLoad;
The HTML content:
<body>
<h3>Using cookies</h3>
<input type=”text” id=”CookieValueTextBox” value=”cookie value” />
<input type=”button” id=”CreateCookieButton” value=”Create cookie” />
<hr />
<span id=”ShowCookieSpan”></span>
<input id=”ReadCookieButton” type=”button” value=”Read cookie” />
</body>
The Internet Explorer browser “has a problem” (called Memory Leakage) when it comes to clearing the memory and it’s considered good practice to clean up the code yourselves in order to avoid hard loading pages.
The removeEvent function called on page onunload event will clear all the memory that has been allocated by the addEvent function.
If you’re not using a javascript library, then I recommend you to verify your code and see if you didn’t forgot to clean up !!
If you’d like to test it, here’s the link: test
Popularity: 10% [?]




SEO MegaCorp news blog is dedicated to provide tips, tricks and latest news around the industry that one might miss. We're a SEO company which is based in India, which is dedicated only to serve the clients with thier full satisfaction...
No User Responded in " Write better code - part 2 : unobtrusive javascript using Objects "
Leave A Reply Here