JavaScript library

Sitemagic comes with a small JavaScript library, which is used for both GUI controls and extensions. The purpose of the library is to simplify common task such as creating a pop up window, performing AJAX requests, storing data client side using cookies among other things.

Jump to a specific section:


AJAX / HTTP Request

The SMHttpRequest class is useful for sending and requesting data. The following snippets demonstrates this.

var reguest = new SMHttpRequest("data.txt", false);
request->Start();
alert("Data received: " + request->GetResponseText());
The example above is a simple example of how to use the HttpRequest class. The content of a text file is requested. It is also possible to request XML data. Simply point the URL to an XML file, and instead of calling GetResponseText(), use GetResponseXml().

The following example demonstrates how an asynchronous request can be made.

var reguest = new SMHttpRequest("feed.txt", true);
request->SetStateListener(handleResponse);
request->Start();

function handleResponse()
{
    var state = "";

    if (request->GetCurrentState() === 1)
        state = "Connection established";
    else if (request->GetCurrentState() === 2)
        state = "Headers received";
    else if (request->GetCurrentState() === 3)
        state = "Loading data ...";
    else if (request->GetCurrentState() === 4)
        state = "Done - data is now ready to be read";

    alert(state);

    if (request->GetCurrentState() === 4)
        alert("Data received: " + request->GetResponseText());
}
Sending data is just as easy, as shown below. In this example we subscribe a user to our newsletter, without performing a post back.

var reguest = new SMHttpRequest("newsletter.php", true);
request->SetStateListener(handleResponse);
request->SetData("function=subscribe&mail=jack@jacksdomain.com");
request->Start();

function handleResponse()
{
    if (request->GetCurrentState() === 4)
        alert(request->GetResponseText());
}
SMHttpRequest class

Function Return type Description
SMHttpRequest(url:string, async:boolean)   Constructor. Create instance of the request class. Specify URL to which the request is to be send, and a boolean value indicating whether to perform an asynchronous request or not.
AddHeader(key:string, value:string)   Set custom header. By default the following headers are set.
Content-type = application/x-www-form-urlencoded;
Content-length = [Length of data string]
Connection = close
Notice that none of these headers will be set automatically, if AddHeader(key:string, value:string) is used.
SetData(data:string)

Set data to be send as a string. Each piece of data must be separated by the character &. Example: name=Jack&email=jack@hotmail.com.
Data will always be send using the POST method. To send data using the GET method, simply specify the data as arguments to the URL in the constructor.
Start()

Start request. If SMHttpRequest object has not been initialized with the asynchronous flag in the constructor, the function will pause the execution, until a response is received.
GetReponseXml()
XMLDocument
Get response as an XML document.
GetReponseText()
string
Get response as ordinary text.
SetStateListener(func:function)

Assign function to execute, every time the state of the request changes. The function assigned can take no arguments.
GetCurrentState()
Integer
Get the current state of the request. The function returns the following values:
0 = Unsend
1 = Connected open
2 = Headers received
3 = Loading data
4 = Done
GetHttpStatus() Integer Get status code of the HTTP request. Some of the most common status values:
200 = OK (all went well)
403 = Forbidden (access denied)
404 = Not found (page not found)
500 = Internal Server Error


Creating pop up windows

Windows can be easily opened and customized using the SMWindow class, which the following example demonstrates.

var window = new SMWindow("UniqueId");
window->SetUrl("http://google.com");
window->SetSize(640, 480);
window->Show();
It is also possible to assign content to the window, instead of loading it.

var window = new SMWindow("UniqueId");
window->SetContent("<html><body>Hello world!</body></html>);
window->Show();
SMWindow class

Function Return type Description
SMWindow(identifier:string)

Create instance of a new window with a unique identifier.
SetUrl(url:string)

Set address of page to load inside the new window.
SetContent(content:string)

Set content to render inside the new window.
SetOnload(func:function)

Set function to execute when the page is done loading, inside the new window. The function specified can take no arguments.
SetSize(width:integer, height:integer)

Set the dimentions of the new window (in pixels).
SetDisplayToolBar(value:boolean)

Set True to have toolbar displayed in new window, False not to (default).
SetDisplayLocation(value:boolean)

Set True to have location/address field displayed in new window, False not to (default).
SetDisplayMenuBar(value:boolean)

Set True to have menu bar displayed in new window, False not to (default).
SetDisplayStatusbar(value:boolean)

Set True to have status bar displayed in window, False not to (default).
SetDisplayScrollBars(value:boolean)

Set True to have scroll bars displayed (default), False not to.
SetResizable(value:boolean)

Set True to allow resizing of new window (default), False not to.
SetPosition(pixelsLeft:integer, pixelsTop:integer)

Set position of window. First argument is the number of pixels from the left side of the screen, second argument is the number of pixels from the top of the screen.
SetCenterWindow(value:boolean)

Set True to have new window centered on the screen (default), false not to.
Show()

Make window appear on the screen.
Close()

Close window if opened.
GetInstance()
Window
Get the actual instance to the window internally used in the SMWindow class. The instance is not available until after Show() has been invoked.


Working with cookies

Storing information on the visitors computer is another common task in web applications and websites. Unfortunately this is not at all intuitive with JavaScript, which is why the SMCookie class was written. See how easy it is, to create and read cookies in the example below.

// Create cookie called PreferedStartPage with the value news.php. It expires after 365 days.
SMCookie.SetCookie("PreferedStartPage", "news.php", 365 * 24 * 60 * 60);

// Read cookie value
alert("Your prefered start page: " + SMCookie.GetCookie("PreferedStartPage"));

// Remove cookie again
SMCookie.RemoveCookie("PreferedStartPage");
SMCookie class (all functions are static)

Function Return type Description
SetCookie(name:string, value:string, seconds:integer) Boolean Create cookie of the specified name with the given value and timeout in seconds. Returns True on success, otherwise False. Important: Value cannot contain the semi colon character.
GetCookie(name:string) String Get cookie value. NULL is returned if cookie was not found.
RemoveCookie(name:string) Boolean Remove cookie with the specified name. True is returned on success, otherwise False.


Using event handlers

The event handler class allows for developers to register event handlers with just one line of code, without the need to write browser specific code.

SMEventHandler.AddEventHandler(window, "load", onLoadHandler);

function onLoadHandler()
{
    alert("Page done loading");
}
The AddEventHandler function takes three arguments. The element which fires the event, the name of the event (without the "on" prefix - ie "onload" becomes "load"), and a reference to the event handler function.

Also notice that since Internet Explorer does not support event capturing, only event bubbling is supported.


SMEventHandler class (all functions are static)

Function Return type Description
AddEventHandler(element:object, event:string, eventFunction:function   Register event handler on specified element. The name of the event is specified as a string without the "on" prefix. The last argument is a reference to the function to execute when the event fires.


Message dialogs

The SMMessageDialog class provides a few simple functions for popping up message dialogs, confirmation boxes and input boxes. Each function is described in the class description below.


SMMessageDialog class (all functions are static)

Function Return type Description
ShowMessageDialog(content:string)   An ordinary alert message box pops up with the content specified.
ShowMessageDialogOnLoad(content:string)   An ordinary alert message box pops up with the content specified, when the page is done loading.
ShowConfirmDialog(content:string) Boolean Displays an ordinary confirmation dialog with an OK button and Cancel button. The function returns True if OK is clicked, False if Cancel is clicked.
ShowInputDialog(content:string, value:string) String
Displays an ordinary input dialog with the content specified and a text field for entering a custom value. The value of the text field can be predefined using the value argument. The user input is returned.


Common DOM operations

The JavaScript library also contains a set of useful functions for interacting with the DOM (Document Object Model). These functions are gathered on the SMDom class as static members.


SMDom class (all functions are static)

Function Return type Description
GetInnerValue(elmId:string)   Get the inner value of the element with the specified ID.
SetAttribute(elmId:string, attr:string, value:string)   Set attribute on element with specified ID. Returns True on success (element found), otherwise False.
GetAttribute(elmId:string, attr:string) String Get specified attribute value for element with specified ID. Returns NULL if element is not found.
SetStyle(elmId:string, property:string, value:string)   Set specified style property for element with specified ID. Returns True on success (element found), otherwise False.
GetStyle(elmId:string, property:string) String Get specified style for element with specified ID. Returns NULL if element is not found.
ElementExists(elmId:string) Boolean Get value indicating whether element with specified ID exists or not.
GetElement(elmId:string) Object Get element with specified ID. NULL is returned if element was not found.


String utilities

The SMStringUtilities class serves as a toolbox for string function that are not found in the ordinary repository of JavaScript functions.


SMStringUtilities class (all functions are static)

Function Return type Description
Trim(str:string) String Removes whitespaces from string.
Replace(str:string, search:string, replace:string, offset:integer) String Replace content within string from the specified offset. Only once occurence is replaced.
ReplaceAll(str:string, search:string, replace:string) String Replaces all occurences of the search string, with the value of the replace string.


Browser detection

This is a very simple browser detection component capable of detecting IE, Firefox, Safari and "Others" (Unknown).


SMBrowser class (all functions are static)

Function Return type Description
GetBrowser() String Returns "MSIE" for Internet Explorer, "Safari" for Apple's Safari browser, "Firefox" for Mozilla's browser, and finally "Unknown" for anyone else.