Using PNG Transparency + the jQuery Colour Change Plugin

See the cute little pictures on the left? The ones below the site menu? Go ahead and run the mouse over them a few times – a faded circle behind the animals changes colour each time, doesn’t it? Yep.

The idea for this came from Artemy Lebedev’s Mandership. Go there and hover the cursor over the bar-code in the top right, notice that it changes colour as you do so.

I really like this effect, and wanted to implement on this site, as I needed something to distract me from important work.

The effect is accomplished with jQuery, a colour generation function and a transparent PNG.

I thought I’d share this effect, and variations, with the world with this tutorial.

Below are four variations, each adding an additional function/plugin to achieve the different effects:

Vanilla

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

Colour Animation

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

Hover Intent

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

Brightness/Darkness Modification (darkness shown here)

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

Vanilla

First, the library:

You’ll need to include jQuery in your page. First download the jQuery library, then upload it to your server. To include the library in your page, you need to modify then paste this code somewhere in your page’s header (the bit between the … tags):

<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.js"></script>

Change src to reflect the location of the jQuery file you uploaded to your server.

Second, the functions:

This code needs to be pasted just below the jQuery library link, also in the header.

1
2
3
4
5
6
7
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
<script type="text/javascript">/* generate random colour http://www.therustybarrel.com/david/experiments/randhex.html */
function genHex(){
	colors = new Array(14);
	colors[0]="0";
	colors[1]="1";
	colors[2]="2";
	colors[3]="3";
	colors[4]="4";
	colors[5]="5";
	colors[5]="6";
	colors[6]="7";
	colors[7]="8";
	colors[8]="9";
	colors[9]="a";
	colors[10]="b";
	colors[11]="c";
	colors[12]="d";
	colors[13]="e";
	colors[14]="f";
 
	digit = new Array(5);
	color="";
	for (i=0;i<6;i++){
		digit[i]=colors[Math.round(Math.random()*14)];
		color = color+digit[i];
	}
	return "#"+color;
}
 
jQuery(document).ready(function(){
jQuery(".colour-change").hover(function(){
jQuery(this).parent().css("background-color", genHex());
});
});
</script>

The genHex() function is from The Rusty Barrel, but the site seems to be down. It strings together some random hex values, returning them in a string suitable for use in CSS.

jQuery code that is to be triggered by some event needs to be placed between jQuery(document).ready(function(){…}); In this case we have some code that will be executed when when the visitor hovers the cursor over any element with the class ‘colour-change’. The next line selects the anchor, then gets its parent. It then asks genHex() for a random colour, uses this to change the parent’s background colour. Simple! jQuery makes Javascript much simpler, fun even. It also alleviates many issues related to browser incompatibility.

Note that this code must be pasted below the line calling the jQuery library. Why? Because the colourChange() function needs jQuery to run, and javascript code only knows about libraries included above themselves.

Third, the HTML:

1
2
3
4
5
<div style="width:600px; height: 188px; background-color: #333333; margin: 0px auto;">
<a href="http://pagesofinterest.net/blog/2009/06/using-png-transparency-the-jquery-colour-change-plugin" class="colour-change"
<img src="http://pagesofinterest.net/images/post/dizi.png" alt="Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples."/>
</a>
</div>

The HTML required for this effect consists of three elements: an outer div, an anchor and an image. The styling for the div is very important. It must be given width and height values equal to the width and height of the image it is wrapping, and it must be given a background colour.

The anchor is given the class “colour-change”, which is required for jQuery to handle the cursor hover event.

The image should be whatever image you want to use – with at least a little transparency!

You can use this effect as many times as you want on any page – as long as whatever page you’re using it on has 1) the jQuery library link in the header, 2) the functions below the jQuery link in the header, and 3) the anchors must be given the class ‘colour-change’.

Colour Animation

Follow the vanilla section of this tutorial first.

Any of the variations can be combined with the excellent colour animation plugin for jQuery. This results in a smooth transition between colours, which is desirable in some cases. Here is our example + colour animations:

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

To integrate the colour animation plugin with this example:

Download the colour animation plugin, upload it to your sever.

Link to it in the header of your page, between the jQuery link and the functions code, e.g:

1
2
3
4
5
6
7
8
9
10
<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.js"></script>
<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.colouranimations.js"></script>
<script type="text/javascript">
function genHex(){
[...]
}
jQuery(document).ready(function(){
[...]
});
</script>

Swap the line “jQuery(this).parent().css(“background-color”, genHex());” with:

jQuery(this).parent().animate({backgroundColor: genHex()},500);

the ‘500′ value tells the function how long you want the transition to take, in milliseconds. Change this to whatever you like!

Hover-Intent

Any of the effect variations can be combined with hover-intent. If you plan on applying this colour-change effect to multiple items on a page, you should seriously consider this plugin. If will prevent the crazy “piano key” behaviour that can occur when a visitor hovers over multiple items in quick succession.

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

Follow the vanilla section of this tutorial first.

Download the hover-intent jQuery plugin, upload it to your server.

Link to it in the header of your page, between the jQuery link and the functions code, e.g:

1
2
3
4
5
6
7
8
9
10
<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.js"></script>
<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.hoverintent.js"></script>
<script type="text/javascript">
function genHex(){
[...]
}
jQuery(document).ready(function(){
[...]
});
</script>

Replace the jQuery code with:

1
2
3
4
5
jQuery(document).ready(function(){
jQuery(".colour-change").hoverIntent(function(){
jQuery(this).parent().animate({backgroundColor: genHex()},500);
}, function(){});
});

You’ll notice that I’ve combined the hover intent plugin with the colour animation plugin in the code above. If you’d like to do this, make sure you include both plugins! Your jQuery, hover-intent and colour animation links should look like:

<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.js"></script>
<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.color.animation.js"></script>
<script type="text/javascript" src="http://pagesofinterest.net/js/jquery.hover.intent.js"></script>

Remember that the jQuery link must be first! In this case the order of the following two doesn’t matter. The rule is this: if javascript X requires functions within javascript Y, then javascript Y must be included before javascript X.

Brightness/Darkness Manipulation

Any of the effects can be combined with this to produce a random colour change of a consistently darker/lighter brightness level. This can be good in situations where you want the randomized colour change to be more subtle.

Brightness:

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

Darkness:

Disciples are not necessarily inferior to teachers, teachers are not necessarily superior to disciples.

Follow the vanilla section of this tutorial first.

I include this section in case you want to use only light/dark colours. Maybe the full range is too garish for you?

You’ll need to include the following two functions. Copy them just above the genHex() function. The functions are modified from code found in this post this post on the Experts Exchange.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function LightenColor(h, d) {
 
	var r, g, b, txt;
 
	h = (h.charAt(0) == "#") ? h.substring(1,7) : h;
 
	r = parseInt(h.substring(0,2),16);
	g = parseInt(h.substring(2,4),16);
	b = parseInt(h.substring(4,6),16);
 
	r = (r+d > 255) ? 255 : (r+d < 0) ? 0 : r+d;
	g = (g+d > 255) ? 255 : (g+d < 0) ? 0 : g+d;
	b = (b+d > 255) ? 255 : (b+d < 0) ? 0 : b+d;
 
	txt = b.toString(16);        if (txt.length< 2) txt = "0"+ txt;
	txt = g.toString(16) + txt;  if (txt.length< 4) txt = "0"+ txt;
	txt = r.toString(16) + txt;  if (txt.length< 6) txt = "0"+ txt;
 
	return "#"+ txt;
}
function DarkenColor(h, d) {
	return LightenColor(h, d* -1);
}

To get a random light colour, swap the jQuery(this).parent().css(“background-color”, genHex()); for:

jQuery(this).parent().css("background-color", LightenColor(genHex(),100));

To darken:

jQuery(this).parent().css("background-color", DarkenColor(genHex(),100));

There you go! I hope you found this tutorial helpful – please let me know if you spot any errors :)

Like this post? Move it on along with:

email Email | delicious delicious | digg Digg | Tweet this post Tweet | reddit Reddit | newsvine Newsvine | furl Furl | google Google | StumbleUpon Stumble | Hao Hao HaoHao


Trackback:

Comments: 0 | Comments Feed

Scroll to post title

No commentsTrackback

jQuery Error: ‘g is undefined’

Discovered the cause of this annoying (but seemingly impotent) error in a response by Karl Swedberg on Nabble.

The error was caused by my passing only one function to jQuery.hover(), eg:

 jQuery(".blog-entry-date").hover(function(){
                jQuery(this).animate({color: genHex()},100);
        });

Hover takes two functions. Instead ‘mouseenter’ should be used:

 jQuery(".blog-entry-date").bind('mouseenter',function(){
                jQuery(this).animate({color: genHex()},100);
        });

The error didn’t seem to have any effect on the execution of the code (at least in Firefox), but errors are errors, and the the cause should be hunted down. Always.

Like this post? Move it on along with:

email Email | delicious delicious | digg Digg | Tweet this post Tweet | reddit Reddit | newsvine Newsvine | furl Furl | google Google | StumbleUpon Stumble | Hao Hao HaoHao


Trackback:

Comments: 0 | Comments Feed

Scroll to post title

No commentsTrackback

Shadowbox rel=’shadowbox’ Doesn’t Work? Here’s a Workaround

Yesterday I was trying to implement a Shadowbox contact form in the Bay of Islands SPCA site, but I just couldn’t get it to work. I was using the standard setup that works perfectly well on the Te Kuiti SPCA Site:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script type="text/javascript" src="http://tekuitispca.org/sb/jquery-1.2.3.min.js"></script>
<script type="text/javascript" src="http://tekuitispca.org/sb/shadowbox-jquery.js"></script>
<script type="text/javascript" src="http://tekuitispca.org/sb/shadowbox.js"></script>
<script type="text/javascript">
 
Shadowbox.loadSkin('classic', 'http://tekuitispca.org/sb/skin');
Shadowbox.loadLanguage('en', 'http://tekuitispca.org/sb/lang');
Shadowbox.loadPlayer(['iframe'], 'http://tekuitispca.org/sb/player');
 
window.onload = function(){
 
    var options = {
        initialWidth:     '0',
        initialHeight:    '0'
    };
 
    Shadowbox.init(options);
    }
 
</script>

And the HTML:

<a href="http://www.tekuitivets.co.nz/" rel="shadowbox;initialHeight=0;initialWidth=0;width=900;height=700;" title="Atkinson &amp; Associates Vet Clinic">Atkinson &amp Associates Vet Clinic</a>

I uploaded all the files, changed the addresses in the above code. Strangely, it worked find in Rapid Weaver, but not in Safari, Firefox, Epiphany or any other browser – either in export mode or after a full upload. My search for “Shadowbox just won’t work!” yielded no results, so was forced to use the programmer’s final weapon – exhaustive trial and error.

I tried various things for about an hour, and finally struck gold with this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<script type="text/javascript" src="http://boispca.org/sb/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="http://boispca.org/sb/shadowbox-jquery.js"></script>
<script type="text/javascript" src="http://boispca.org/sb/shadowbox.js"></script>
<script type="text/javascript">
 
	Shadowbox.loadSkin('classic', 'http://boispca.org/sb/skin');
	Shadowbox.loadLanguage('en', 'http://boispca.org/sb/lang');
	Shadowbox.loadPlayer(['iframe'], 'http://boispca.org/sb/player');
 
	jQuery(document).ready(function(){
 
		var options = {
		initialWidth:     '0',
		initialHeight:    '0'
		};
 
		Shadowbox.init(options);
 
		jQuery("#contact-us").click(function(){
			Shadowbox.open({
			        player:     'iframe',
			        title:      'Contact Us',
			        content:    'http://boispca.org/contact/',
			        height:     500,
			        width:      400
			    });
		    return false;
		});
	});
 
</script>

And HTML:

<a href="http://boispca.org/contact/" id="contact-us" title="Contact" >Contact</a>

Now whenever one clicks the contact button, Shadowbox is called through jQuery.

I don’t know why the normal way didn’t work!

Like this post? Move it on along with:

email Email | delicious delicious | digg Digg | Tweet this post Tweet | reddit Reddit | newsvine Newsvine | furl Furl | google Google | StumbleUpon Stumble | Hao Hao HaoHao


Trackback:

Comments: 0 | Comments Feed

Scroll to post title

No commentsTrackback