When I see search boxes I am often wondering which search parameters to enter. Am I searching for users of this site, or searching for content?

In comes help tips to the rescue! Help text placeholders are used often on search text boxes, but also on inputs which ask for a URL (eg. to remind users to prefix the link with http://).

or:

Here’s an simple function to do this using JavaScript:

1
2
3
4
5
6
7
8
9
10
function ToggleDefaultHelpText(obj, helptext, isFocus)
{
	var curr = obj.value.replace(/^\s+|\s+$/g, '') ;  // trim the text box's value
	var isEmpty = (curr.length < 1 || curr == helptext);
	obj.style.color = (isFocus) ? "#000000" : (isEmpty) ? "#999999" : "#000000";
	if (isFocus)
		obj.value = (isEmpty) ? "" : curr;
	else
		obj.value = (isEmpty) ? helptext : curr;
}

You will want your text box’s default state to be the same as the blur state, so execute the function with isFocus = false.

1
2
<input type="text" id="myTextBox" onfocus="javascript:ToggleDefaultHelpText(this, 'search user or tag', true);" />
ToggleDefaultHelpText(document.getElementById("myTextBox"), "search user or tag", false);

The better way to do this is to programmatically attach this function to the onfocus and onblur events of your text input. If you’re using MooTools it’ll be clean and simple - the above code turns into something much neater:

1
2
3
4
<input type="text" id="myTextBox" />
$('myTextBox').addEvent('focus', function() { ToggleDefaultHelpText($('myTextBox'), 'search user or tag', true); });
$('myTextBox').addEvent('blur', function() { ToggleDefaultHelpText($('myTextBox'), 'search user or tag', false); });
$('myTextBox').fireEvent('blur');  // execute the onblur function to initiate this text box

Hope this helps you to help your users.

I recently wrote some Javascript to create a rotating headlines section, complete with fading animation, for a client’s site. It was based off the Hot News Headlines section on the front page of Apple’s website, and with the help of MooTools (with Moo.Fx), it was a simple task. Here’s what the rotating headlines look like at Apple.com:

Hot News Headline

Lets start. My HTML section looked something like this:

1
2
3
4
5
6
7
<style>
div.Headline { display: none; }
</style>
<div id="divHeadlines">
    <div class="Headline"><a href="#">Link 1</a></div>
    <div class="Headline"><a href="#">Link 2</a></div>
</div>

And my Javascript took care of the rest. The basic idea is to show a headline, and then set a timeout to hide the current headline and show the next one, with all the transition animations handled by MooTools:

8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<script type="text/javascript">
var arrHeadlines = null; 	// array to hold headline objects
var intAniDuration = 1;		// duration of transition animation (seconds)
var intViewDuration = 5;	// time before rotation (seconds)
 
function Init()
{
    if ($('divHeadlines'))
    {
        // get all headlines
        arrHeadlines = $('divHeadlines').getElements('div[class=Headline]');	
        // convert time to milliseconds        
        intAniDuration = intAniDuration * 1000;
        intViewDuration = intViewDuration * 1000;
        if (arrHeadlines != null && arrHeadlines.length > 0)
        {
            // hide all
            for (var i = 0; i < arrHeadlines.length; i++)
            {
                var fx = new Fx.Styles(arrHeadlines[i], { duration:0, wait:false });
                fx.set({ 'opacity': 0 });
            }
            // show first link
            ShowHeadline(0);
        }
    }
}
 
function ShowHeadline(idx)
{
    var oTargetDiv = arrHeadlines[idx];
    oTargetDiv.style.display = "block";   // make div appear
    var fx = new Fx.Styles(oTargetDiv, { duration:intAniDuration, wait:false });
    fx.start({ 'opacity': 1 });     // set opacity to visible
    // in X seconds time, hide this headline's div
    setTimeout("HideHeadline(" + idx + ")", intViewDuration)
}
 
function HideHeadline(idx)
{
    // get index of next headline to show
    var newIdx = idx + 1;
    if (newIdx >= arrHeadlines.length)
        newIdx = 0;    // reset index
    var oTargetDiv = arrHeadlines[idx];
    var fx = new Fx.Styles(oTargetDiv, { duration:intAniDuration, wait:false,
        onComplete:function(){
            oTargetDiv.style.display = "none"; ShowHeadline(newIdx);
        }/*end onComplete*/ });
    fx.start({ 'opacity': 0 });     // set to fade out, on complete, show next headline
}
 
// call Init after everything loads
Init();
</script>

Make sure you place the JavaScript block at the bottom of your page (before the </body> tag). Comments and suggestions appreciated, especially if you know of a more elegant solution.

Web development has been moving towards faster and quicker deployment. Popular frameworks such as .NET 2.0 and Prototype.js allow for quick AJAX and web services development, but are rarely used together. Web services made with ASP.NET are usually used along-side with ASP.NET AJAX on ASP pages. However, if your site does not use ASP but you would still like to consume your ASP.NET web services with just JavaScript, then read on.

First, create your ASP.NET web service. Once you are finished, visit the Web.Config file and enter the following under the <system.web> node:

<webservices>
    <protocols>
        <add name="HttpGet" />
        <add name="HttpPost" />
    </protocols>
</webservices>

After that’s done with, view your web service’s .asmx file in a web browser. Click the name of a web service operation and you’ll be taken to the operation’s Invoke page. Scroll to the bottom and you can clearly see how to structure your header for calling your web service method using POST or GET:
ASP.NET Web Services Invoke Page

You can now use Prototype or another JavaScript method to call the web service. An example AJAX call using POST with Prototype.js could be:

new Ajax.Request('/myws.asmx/HelloWorld',
    {
        method: 'post',
        postBody: 'strName=David',
        onSuccess: function(transport){
          var response = transport.responseText || "no response text";
          alert("Success! nn" + response);
        },
        onFailure: function(){ alert('Something went wrong...') }
    }

JavascriptIn the DOM Level 2 specifications, the disabled property is defined for <LINK> and <STYLE> elements. Toggling this property using JavaScript allows for quick CSS style switching. It’s great for switching between themes!

To illustrate, I’ve written a simple JavaScript CSS theme toggling function. It supports both external CSS stylesheet references and local STYLE declarations.

Click here to see the demo (view the source code for more information).

There are a few ways to call a Javascript function from a link. If the function does not return a value, then you may use:

<a href="javascript:Function();">Click me</a>

However, if the function returns a value, then using the above link will cause the page to display the return value.

Another popular implementation uses “#” as the href attribute value, and puts the function call in the onclick attribute:

<a href="#" onclick="javascript:Function();">Click me</a>

This will not cause the page to display the return value, but it will have the affect of returning to the top of the page.

The solution is to use the void operator. The void operator discards the value of its operand and returns undefined. You may then put the call to a Javascript function in the href attribute and not worry about having the page to display the return value:

<a href="javascript:void Function();">Click me</a>

Here’s a test page to demonstrate.

JavascriptQuick Javascript tips to help you juggle and handle the known browsers.

Quick browser detection:

Edit: this quick browser detection should be used only to execute IE (or non-standard) Javascript. The way I use this is:

if (window.ActiveXObject)
{
// IE-only code
}
else
{
// standard code
}

window.XMLHttpRequest is implemented in IE 7 (but not in IE 6 and below). Thanks to Niko Bellic for the heads up.
IE:

if (window.ActiveXObject)

Mozilla/Safari:

if (window.XMLHttpRequest)

Getting event source element:

IE:

var oSource = event.srcElement;

Moz:

var oSource = event.target;

Cross-browser page redirect:

var sUrl = 'http://adavidchan.com';
setTimeout(function() {window.location.href = sUrl;}, 1);