2
Feb/09
2

The one real reason to not use JQuery

JQuery is a very nice for DOM manipulation and access.  As I mentioned in my last post, JQuery uses standard CSS selectors by default which is very nice.  You can create fairly complex actions with very few lines of code.

What it does not have that MooTools and Prototype.js both have is a rich set of object oriented oriented development functions.  JQuery is ver DOM centric and does not have much in the way of utilities that are not directly related to accessing and manipulating the DOM.  You can greatly extend the functions of elements in the DOM or add elements to the DOM.  Once you are working with pure JavaScript objects JQuery does not have much to offer.  This begins to become eveident right away when compairing the core sections of both MooTools and JQuery.  In JQuery’s core the first things are DOM element access and creation functions; where MooTools’ core is all JavaScript and OO featrues.  The Extend function is a good example, extend is a core componenet of MooTools and a Utility in Jquery.

Beyond that the true reason for using MooTools is the the object oriented programming features.  The Function and Class features of MooTools are simply not implimented in JQuery.  This makes taking advantage of Encapsulation, Inheritance and Polymorphism very difficult with JQuery, which pretty much leaves all of the work of implementation of those features up to you. 

That being said you can use the JQuery’s noConflict() function and use both MooTools and JQuery.  I have not explored how the two will play together when writing object oriented code with Mootools functions and accessing the DOM with JQuery, but I do plan to give this a try in the near future.

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

29
Jan/09
2

Three real good reasons to use JQuery, from a Mootools lover

I have been an avid mootools user for many years. A couple of times I have looked at JQuery and turned up my nose. That being said I am a firm believer that one should reassess ones knowledge/opinions/assumptions periodically just to make sure the world has not changed while you were not looking. This is one time that the reassessment did indeed change what I believe, and here are 3 things making that change:

Community Support

JQuery has a large community of active users. This makes finding information supplementary to the JQuery official documentation very easy. JQuery’s community also means that when you post a question some where you will not wait long for an answer.

Selectors

JQuery uses the same selectors as CSS. When working with a team of both developers and designers this is wonderful. When it comes to addressing the DOM with JQuery both the designers and the developers are speaking the same language. Every bridge you can build between your developers and designers makes for a stronger team. Not to mention using CSS selectors is just easier than all the hoops you have to jump through in other frameworks.

Speed

With the release of version 1.3 of the JQuery framework, many of the functions are faster than any other JavaScript framework. With the ever increasing amount of JavaScript executing on a page the speed is a welcome relief.

These are three very important reasons to take another look at JQuery.

I have done a little more playing around with JQuery and have found one major draw back when compared to Mootools

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

7
Dec/08
2

How to: Use MooTools to Fade Between Multiple Images

After I wrote my post “Using MooTools to fade between two images” I have received many request on how to fade between multiple images. So here is “How to: Use MooTools to Fade Between Multiple Images”. We start with the same HTML setup as we do in “Using MooTools to fade between two images” plus a few buttons; setup two DIV tags that are absolutely positioned over one another inside another DIV tag that uses default placement. Then you place your image tags inside each of the absolutely positioned DIV tags. Each of the DIV tags needs to have an id attribute so they can be referenced in your javascript code.

The HTML for the task will look like this:

1
2
3
4
5
6
7
8
<div id="button1" style="background-color:#aaaaaa; border: 1px solid #444; cursor: pointer;" onclick="toggle(this.image.src);">Image 1</div>
<div id="button2" style="background-color:#aaaaaa; border: 1px solid #444; cursor: pointer;" onclick="toggle(this.image.src);">Image 2</div>
<div id="button3" style="background-color:#aaaaaa; border: 1px solid #444; cursor: pointer;" onclick="toggle(this.image.src);">Image 3</div>
<div id="button4" style="background-color:#aaaaaa; border: 1px solid #444; cursor: pointer;" onclick="toggle(this.image.src);">Image 4</div>
<div style="height:112px;" >
    <div id="div1" style="position:absolute; opacity: 0;"><img id="image1" src="image1.jpg" /></div>
    <div id="div2" style="position:absolute; opacity: 1;"><img id="image2" src="image2.jpg" /></div>
</div>

For fading between multiple images there is some preparation we will need to do before we are ready to start switching images. First you need to create an object to associate buttons to your image source URLs, this makes it easy to change the number of buttons and images they load later. Then iterate that object creating new elements for each image and attaching them to the buttons. Creating new images and attaching them to the buttons does two things, it pre-loads the images and associates the image to the button that will show the image.

creating the object can be done with JavaScript Object Notation:

1
var buttonsAndImages = {'button1':'image1.jpg','button2':'image2.jpg','button3':'image3.jpg','button4':'image4.jpg'};

The loadImages function will take the buttionsAndImages object and create a new image object using the Mootools Element object and attach that image object to its associated button.

1
2
3
4
5
6
function loadImages(buttonsAndImages){
    for(biPairKey in buttonsAndImages) {
        var image = new Element('img',{ src:buttonsAndImages[biPairKey], style:'margin:3px;' });
        $(biPairKey).image = image;
    }
}

For multiple image switching we will use a function named toggle. In the toggle function we will set the source of the hidden image, start the effect to fade out the visible image and fade in the hidden image, and set a global variable to indicate which div is visible

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function toggle(newSrc){
    //stop the current animation if it is running.
    if($("div1").fx){$("div1").fx.stop();}
    if($("div2").fx){$("div2").fx.stop();}
    //Decide which div to hide and which to show.
    if(visibleDiv == $("div1")){
        //change the hidden image's source
        $("image2").src = newSrc;
        //fade the visible out and the hidden in.
        $("div1").fx = new Fx.Style($("div1"), 'opacity', {duration: 2000}).start(0);
        $("div2").fx = new Fx.Style($("div2"), 'opacity', {duration: 2000}).start(1);
        //Set which div is visible.
        visibleDiv = $("div2");
    }else{
        //change the hidden image's source
        $("image1").src = newSrc;
        //fade the visible out and the hidden in.
        $("div1").fx = new Fx.Style($("div1"), 'opacity', {duration: 2000}).start(1);
        $("div2").fx = new Fx.Style($("div2"), 'opacity', {duration: 2000}).start(0);
        //Set which div is visible
        visibleDiv = $("div1");
    }
}

Check out the demo of fading multiple images to see this in action. If you want to create a slide show or other implementation of this that automatically switches the images, read through my post on Delay, Periodical and Closures. Below you will find the source of the example:

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Untitled Document</title>
    </head>
    <body>
        <script type="text/javascript" src="js/mootools-release-1.11.js" language="javascript"></script>
        <script language="javascript">
            var visibleDiv = $("div1");
            function toggle(newSrc){
                if($("div1").fx){$("div1").fx.stop();}
                if($("div2").fx){$("div2").fx.stop();}
                if(visibleDiv == $("div1")){
                    $("image2").src = newSrc;
                    $("div1").fx = new Fx.Style($("div1"), 'opacity', {duration: 2000}).start(0);
                    $("div2").fx = new Fx.Style($("div2"), 'opacity', {duration: 2000}).start(1);
                    visibleDiv = $("div2");
                }else{
                    $("image1").src = newSrc;
                    $("div1").fx = new Fx.Style($("div1"), 'opacity', {duration: 2000}).start(1);
                    $("div2").fx = new Fx.Style($("div2"), 'opacity', {duration: 2000}).start(0);
                    visibleDiv = $("div1");
                }
            }

            function loadImages(buttonsAndImages){
                for(biPairKey in buttonsAndImages) {
                    var image = new Element('img',{ src:buttonsAndImages[biPairKey], style:'margin:3px;' });
                    $(biPairKey).image = image;
                }
            }

            function faderInit(){
                //create an object to store the relationship of the buttons to the images.
                var buttonsAndImages = {'button1':'image1.jpg','button2':'image2.jpg','button3':'image3.jpg','button4':'image4.jpg'};
                loadImages(buttonsAndImages);
            }
            window.addEvent("domready", faderInit);
        </script>
        <div style="width:453px">
            <div id="button1" style="background-color:#aaaaaa; border: 1px solid #444; cursor: pointer;" onclick="toggle(this.image.src);">Image 1</div>
            <div id="button2" style="background-color:#aaaaaa; border: 1px solid #444; cursor: pointer;" onclick="toggle(this.image.src);">Image 2</div>
            <div id="button3" style="background-color:#aaaaaa; border: 1px solid #444; cursor: pointer;" onclick="toggle(this.image.src);">Image 3</div>
            <div id="button4" style="background-color:#aaaaaa; border: 1px solid #444; cursor: pointer;" onclick="toggle(this.image.src);">Image 4</div>
            <div style="height:112px;">
                <div id="div1" style="position:absolute; opacity: 0;"><img id="image1" src="image1.jpg" /></div>
                <div id="div2" style="position:absolute; opacity: 1;"><img id="image2" src="image2.jpg" /></div>
            </div>
        </div>
    </body>
</html>

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

17
Mar/08
3

Using MooTools to fade between two images

Fading between two images is actually a fairly simple task with MooTools. The first thing you need to do is setup up two DIV tags that are absolutely positioned over one another inside another DIV tag that uses default placement. Then you place your image tags inside each of the absolutely positioned DIV tags. Each of the DIV tags needs to have an id attribute so they can be referenced in your javascript code.

The HTML for the task will look like this:

1
2
3
4
5
6
<pre>
&lt;div style="height:112px;" &gt;
    &lt;div id="div1" style="position:absolute; opacity: 0;"&gt;&lt;img id="image1" src="image1.jpg" /&gt;&lt;/div&gt;
    &lt;div id="div2" style="position:absolute; opacity: 1;"&gt;&lt;img id="image2" src="image2.jpg" /&gt;&lt;/div&gt;
&lt;/div&gt;
</pre>

This gives you two DIV tags that will stack on top of one another but the DIV they are inside of will flow with the page. One of the DIV tags starts with an opacity of zero and the other with an opacity of one.

Next you will need a way to make one image disappear and the other appear. We do this by using the MooTools effects. MooTools allows you to animate the change of a style from one value to the next. The easiest way to do this is to use the effect member available on any element accessed with MooTools. To transition from one image to the other smoothly we animate the opacity of each DIV element in opposite directions one becoming fully opaque and the other becoming fully transparent. We do that with the following function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<pre>
function show(whichOne){
    if(whichOne == 1){
        tDiv = "div1";
        vDiv = "div2";
    }else{
        tDiv = "div2";
        vDiv = "div1";
    }
    if($(tDiv).fx){$(tDiv).fx.stop();}
    if($(vDiv).fx){$(vDiv).fx.stop();}
    $(tDiv).fx = $(tDiv).effect('opacity', {duration: 2000}).start(0);
    $(vDiv).fx = $(vDiv).effect('opacity', {duration: 2000}).start(1);
}
</pre>

First you decide which DIV tag will become Transparent and which one will be visible. Next there are two lines of code to check for an active animation and stop any animations that are already running, before we start some new animations. The last two lines create an animation attached to each DIV, going from the current opacity to the specified Opacity, and sets the animation object to the DIV tags .fx member. See the full code below or check out the example.


Update: By popular demand I have created an new post that covers fading multiple images here: How to: Use MooTools to Fade Between Multiple Images

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

25
Feb/08
0

The MooTools Ajax class, the easiest path to dynamic content.

The guys over at MooTools created a whole series of remote server JavaScript classes that make it easier to communicate asynchronously with the server. One of the easiest is the object found in MooTool’s Ajax.js file aptly named the Ajax object.

The Ajax object is not really designed for complex handling of the response from the server; it is really a down and dirty go here and put what you find there in this element kind of object. So the basic syntax is:

1
2
3
4
5
&lt;div id="showTime"&gt;&lt;/div&gt;
&lt;script language="JavaScript">&gr;
var myAjax = new Ajax('http://www.sweetvision.com/servertime.php', {update: $('showTime')});
myAjax.request();
&lt;/script>&gr;

In the preceding code we are creating a new Ajax object that accesses the URL ‘http://www.sweetvision.com/servertime.php’ and what ever is retuned by that URL is injected into the DIV identified by “showTime”. Request() is the member function of the Ajax object that actually sends the request, the object handles the rest.

Another thing that the Ajax object simplifies for you is sending the contents of a form asynchronously. If you have included Ajax in your download of MooTools then any time you reference a form with $(‘formID’) it automatically has an Ajax object in it and you can use $(‘formID’).send() to send the form to the server. Send() takes the same options that the Ajax() constructor takes so you can use update: just like in the example above to display the results of your form submission on your page. You also might want to pass in a function to the onComplete event and hide the form when the ajax request is completed.

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

5
Dec/07
0

Using setTimeout in objects with Mootools

Often you wish to use setTimeout to call a function in the objects you are creating with MooTools or perhaps even more often you would like to pass parameters into your set time out calls. Well, the MooTools framework has given us a plethora of tools to do all of this and more. In this post I will discuss how you can pass parameters with setTimeout (Well, not really ‘into’ setTimeout, but a better way to get the same result.) and call your functions, delayed and recurring, from your objects created with the MooTools class function.

Closures and bind()

The first problem we tend to encounter the first time we try to do this is that when our member function gets called by setTimeout we get a bunch of errors that our variables are undefined. This problem is caused by JavaScript’s lack of closures which means that there is not hard binding between the function and the object that it is declared in. If you do a little debugging you will discover that the this operator is pointing at the window object not your object. The reason for that is that setTimeout causes the function to be called by the window object and in JavaScript this points to the calling scope.

Because the issue of closures is a problem in many cases when using JavaScript MooTools came up with a generic solution to the problem called bind. The bind() method is a part of the functions.js, found in the Native collection of MooTools functions. Their docs on bind can be found here. The Bind() member function will allow you to bind the this operator to any object you choose, which often will be the this of the object you define it in, but could be any object in the DOM. You can use bind when you call set time out like setTimeout(this.myfunction.bind(this), 1000) to call functions in your object delayed and have still have the this operator point at what you expect it to. That having been said, MooTools has two other functions to help you with delayed and recurring function calls in a much more efficient manner.

Delayed and Recurring calls

As this is an article about setTimeout, you are most likely unconcerned with what closures are and are just wanting your delayed function or recurring/polling/periodic function to work. If so, this is the section for you! The MooTools library provides two functions for calling functions, either delayed or periodically. They are, not surprisingly, called ‘delay’ and ‘periodical’. You use delay when you want a function to execute in so many seconds or periodical when you want a function to execute every so many seconds. Both of these functions return their timer ID and can be stopped by passing that into the $clear() function.

Delay example:

delay_demo = new Class({

    initialize: function(dateString){

        this.count = 0;

        this.delayTimer = this.updateCount.delay(1000, this);

    },

    updateCount: function(){

        this.count++;

    }

});

periodical example:

periodical_demo = new Class({

    initialize: function(dateString){

        this.count = 0;

        this.startTimer();

    },

    updateCount: function(){

        this.count++;

    },

    stopTimer: function(){

        $clear(this.periodicalTimer);

    },

    startTimer: function(){

        this.periodicalTimer = this.updateCount.periodical(1000, this);

    }

});

Passing Parameters

Another important feature of bind, delay and periodical is that they will allow you to pass parameters or arguments to the functions they call. Passing arguments to a function called with bind, delay or periodical is as easy as adding a second parameter for bind and, in the case of delay and periodical, a third parameter that is an array of parameter values; e.g., myfunction.periodical(1000, this, [ParamVal1, ParamVal2, "strParamVal3"]) or myfunction.bind(this, [ParamVal1, ParamVal2, "strParamVal3"]).

Common Errors Encountered

There are some situations where you might get an error that does not really explain what the problem is. I have run into two when working with these functions. The first is the “too much recursion” error from Firefox or FireBug. This error indicates that you have used the parenthesis in a place you should not have, an example is using myfunction().delay(1000, this) instead of myfunction.delay(1000, this). The other is having a function that calls periodical that calls its self, which will cause an exponential increase in the number of calls to that function until your browser locks up.

periodical lockup example:

periodical_demo = new Class({
    initialize: function(dateString){
        this.count = 0;
        this.startTimer();
    },
    updateCount: function(){
        this.count++;
    },
    stopTimer: function(){
        $clear(this.periodicalTimer);
    },
    startTimer: function(){
        this.periodicalTimer = this.startTimer.periodical(1000, this); //Note calling startTimer from inside startTimer with periodical is very bad.
    }
});

MooTools has neatly provided simple ways to accomplish all of the tasks we would normally use setTimeout for.

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

8
Apr/07
0

Color Picker version 1.0.2 released

I have made a couple of small updates to the JavaScript Color Picker and the Color Picker project page today.

I fixed a bug with IE and dynamically created tables using the DOM method. Fixed a few layout issues I came across and added the showColorInfo Option. I also updated the example pages so they are integrated into the site and layout a little better.

Enjoy!

-=Kelly

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

2
Apr/07
2

Color Picker v1.0.1 Released

I have done some debugging of the color picker in Opera. There were problems with many of the Canvas functions needed in Opera 9.0, but things work beautifully in Opera 9.1.

I have also done some testing with Firefox 1.5 and Safari. Things do not work at all well in FireFox 1.5 as it is missing some key functionality and I am not planning on making it work in old versions of FireFox given 2.0’s wide spread install base.

Safari is close to working but I am having specific problems with the context.createLinearGradient() function in my version of Safari. Even though; when I look at the context it says that the createLinearGradient function exists it keeps returning undefined for me when I call it. If there are any Mac/Safari gurus out there that can see why this might be happening I would love to hear from you.

The Color Picker now supports FireFox 2.0, IE 7.0, and Opera 9.10.

See examples and download from the Color Picker Project Page.

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

1
Apr/07
0

Complete JavaScript Color Picker

Welcome to the final installation of my JavaScript based Color Picker series. I have made a lot of changes to the color picker since my last installment.

Layout
I found some major problems based on the document type with the way I was laying out elements in the color picker dialog, so I decided that it needed to use the lowest common denominator in order to work reliably, so it is laid out with, *gasp* tables.

Sizing
After adding the support for the Canvas element I decided to add options to size the HueBar and the SV Box.

1
2
3
4
5
6
7
8
9
10
    if(this.Options.hueBarWidth){
        this.HueBar.setStyle("width", this.Options.hueBarWidth);
    }else{
        this.HueBar.setStyle("width", "30");
    }
    if(this.Options.hueBarHeight){
        this.HueBar.setStyle("height", this.Options.hueBarHeight);
    }else{
        this.HueBar.setStyle("height", "360");
    }

Options
I added the ability to pass in an Options object that gives the ability to customize many parts of the Color Picker.

1
2
3
4
    this.Options = {};
    if(objOptions){
        this.Options = objOptions;
    }

Open/Close
I created Open and Close member functions on the color picker object its self.

1
2
3
4
5
6
    open: function (){
        this.Container.setStyle("display", "block");
    },
    close: function (){
        this.Container.setStyle("display", "none");
    }

You can download the full source from the JavaScript Color Picker project page.

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

25
Mar/07
1

Enhancing the JavaScript Color Picker with the Canvas element

With the previous implementation of the Color Picker I used div elements to make the individual “pixels” of the color picker, attaching an event to each div element. This incurs quite a bit of overhead, causing the color picker to perform poorly especially on slower systems. The most obvious way to create something like a color picker efficiently is to use the Canvas element.

First, I needed to detect whether the browser supports the Canvas element. I do that by creating a Canvas element and then seeing if it will return a context like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
testcanvas = document.createElement("canvas");

if(testcanvas.getContext){

 this.supportsCanvas = true;

 delete testelement;

}else{

 this.supportsCanvas = false;

 delete testelement;

}

Next, in the constructor I needed to create Canvas elements instead of div containers for the Hue Bar and SV Box. Here is a snip of code for the Hue bar:

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
36
37
if(this.supportsCanvas){

 //create the canvas Saturation Value Box.

 this.HueBar = new Element("canvas");

 this.HueBar.setStyle("cssFloat", "left");

 this.HueBar.setStyle("styleFloat", "left");

 this.HueBar.setStyle("margin-right", "5px");

 this.HueBar.width=30;

 this.HueBar.height=360;

 this.HueBar.addEvent("click", this.setCurrentHue.bind(this));

 this.Container.appendChild(this.HueBar);

}else{

 //create the container for the hue bar.

 this.HueBar = new Element("div");

 this.HueBar.setStyle("width", "30px");

 this.HueBar.setStyle("cssFloat", "left");

 this.HueBar.setStyle("styleFloat", "left");

 this.HueBar.setStyle("margin-right", "5px");

 this.Container.appendChild(this.HueBar);

}

Note: in the case of using the Canvas element, the events are attached to the canvas instead of child elements.

The next difference is in the drawHueBar and drawSVBox functions. In the drawHueBar function, we figure out the multiplier we will need for get steps between 0 and 360 for the height of our bar. Create a new color that is at hue 0 and full saturation and brightness. Get a 2d context to the HueBar canvas element. Iterate over the height of the HueBar. Set the hue for the current position on the HueBar. Get the Hex color string for the new Hue. Set the Canvas Context’s fill style to the Hex color string. Then, fill a Rect that is as wide as the HueBar and 1 pixel tall with that color. Rinse and repeat until we have iterated the whole HueBar.

Here is a snip of code from the drawHueBar function:

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
36
37
38
39
drawHueBar: function (){

 if(this.supportsCanvas){

    hSteps = 360 / this.HueBar.height;

    hColor = new Color([0,100,100], 'hsb');

    myCTX = this.HueBar.getContext('2d');

    strhHex = "";

    for(hi =  this.HueBar.height; hi &gt; 0; hi--){

        hColor.changeHue(hi*hSteps);

        strhHex = hColor.rgbToHex();

        myCTX.fillStyle = strhHex;

        myCTX.fillRect(0, this.HueBar.height-hi, this.HueBar.width, 1);

    }

 }else{

    hsvColor = new Color([0,100,100], 'hsb');

    fcoDiv = new Element("div");

    fcoDiv.setStyle("width","30px");

    fcoDiv.setStyle("height","1px");

    ...

 }

}

For the SVBox, it is mostly the same, changing the Brightness in the loop instead of the Hue. I make use of the Canvas element’s gradient fill functions to simplify the work. Inside the loop over the height of the SVBox, we create a new gradient that goes from the left side of the SVBox to the Right. We add a color stop to the linear Gradient that is just a gray value between white and black based on the current position in the height of the SVBox. Then we add a color stop that is based on the current iterations HSV value. Set the Canvas context’s fill style to the gradient and then fill one row of the SVBox.

myLinearGrad = myCTX.createLinearGradient(0, 0, this.SVBox.width, 0);
myLinearGrad.addColorStop(0, "rgb("+vi+","+vi+","+vi+")");
myLinearGrad.addColorStop(1, strsvHex);
myCTX.fillStyle = myLinearGrad;

In the case of using the Canvas element, the UpdateSVBox code does the exact same thing as the drawSVBox.

Getting the color clicked on is a little different and we need to deal with the DOM a little more. In order to get the color clicked on we need to call the getImageData(X, Y) function from a Canvas context object. The issue with that is the event.ClientX and the event.ClientY that is passed in is in the window coordinate space, not our canvas elements coordinate space, so we have to translate. In the event call back functions we need to do the following to get the colors from the Canvas elements. Get a 2d context to the Canvas element. Call the MooTools Element.getCoordinates() function to get the left and top of the canvas in the Window coordinate space. Then, for each axis subtract the Canvases left or top from the clientX or clientY then add the window.scrollX or window.scrollY to deal with the page being scrolled if it is. Pass the resulting X and Y into the context’s getImageData function to get an imageData object for the pixel. The imageData.data array will contain the RGB values for the pixel.

myCTX = this.HueBar.getContext('2d');
hBoxCoords = this.HueBar.getCoordinates();
myImageData = myCTX.getImageData(e.clientX - hBoxCoords.left + window.scrollX, e.clientY - hBoxCoords.top + window.scrollY, 1, 1);
CurHueColor = new Color([myImageData.data[0], myImageData.data[1], myImageData.data[2]]);

With this update the Color Picker is significantly faster with a capital ‘S’, unless you are using IE and then it is just as slow as before. (A fact which totally burns my britches, since IE has such a large portion of the browser market share. I will have to figure out something to do about that in the IE case.)

See the code for the whole Canvas enhanced ColorPicker class

Canvas based Color Picker example

This code was tested in IE 7 and Firefox 2. The Canvas element was not added to Firefox until version 2, no Canvas element in IE.

[Post to Twitter]  [Post to Plurk]  [Post to Yahoo Buzz]  [Post to Delicious]  [Post to Digg]  [Post to Ping.fm]  [Post to Reddit]  [Post to StumbleUpon] 

Tweet This Post links powered by Tweet This v1.3.9, a WordPress plugin for Twitter.