9
Jul/09
2

Quick Tip: don’t use links with JavaScript unless the link goes some where

We have all done it, many times I am sure. You need an element to attach some JavaScript to, that will execute some function, so you use <a href=”#” onclick=”myfunction(); return false;”>click me</a>. The link does not go any where so we take steps to prevent the link from actually going any where. I say don’t use a link, use any other DOM element instead and style it like a link, if you actually want it to look like a link.

1
2
3
4
5
6
7
8
9
  <style>
    .linkLike{
      cursor: pointer;
      text-decoration: underline;
      color: #0000ff;
    }
  </style>
  <span class="linkLike" onclick="document.getElementById('clickie').innerHTML += 'clickity click<hr />'">Click Here</span>
  <div id="clickie"></div>

Click Here     Clear

I can think of one situation that you would actually want to use links and that is if you want the link to go some where in the case that JavaScript is disabled. You could for instance take users to a page detailing the need for JavaScript for the page to function properly with instructions to enable JavaScript.

[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
Jul/09
1

How to use object oriented programming with jQuery

Unlike many other JavaScript frameworks jQuery provides few object oriented programming utilities, since JavaScript is all ready object oriented there is no need to. That being said, the means of using object oriented programming with jQuery are limited by some aspects of jQuery it’s self. jQuery is really a function that returns a jQuery object or an array of jQuery objects. That can be confusing since there is both a jQuery function and a jQuery object. Due to this fact there is nothing exactly to sub-class before the jQuery function has returned a jQuery object. What you can do is define a JavaScript object that specifies your own member variables and functions. Once you retrieve a jQuery object, you can use the jQuery.extend() function to copy the members of your object to the returned jQuery object.

Here is a simple example to illustrate:

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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
  <title> Object Oriented jQuery </title>
  <script src="jquery-1.3.2.js"></script>
  <script language="JavaScript">
    var hideMeShowMe = {
      hideME: function(){
        this.data('baseDisplay', this.css('display'));
        this.css('display', 'none');
      },
      showMe: function(){
        this.css('display', this.data('baseDisplay'));
      }
    };

    jQuery(
      function(){
        var pageElement = jQuery('#myElement');
        jQuery.extend(pageElement, hideMeShowMe);
        pageElement.hideME();
      }
    );
  </script>
  </head>
 <body>
  <div id="myElement">
    This is hideable
  </div>
 </body>
</html>

This allows you to extend a single jQuery object with your object’s functionality. There is another approach that you could take which is to use the jQuery.fn.endtend function. That function will cause all of your objects members to be copied to all jQuery objects returned by the jQuery function, that is how plugins work. Which approach you use depends on what you are trying to do, if you are going to make one kind of control that has a specific purpose, it makes sense to use the approach I cover here instead of adding it as a plugin. If you are going to add functionality that will be used more broadly then it makes more sense to add that functionality as a plugin.

This is part of my ongoing series of posts exploring the use of jQuery and object oriented JavaScripts, you might be interested in these posts as well:

[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
Jun/09
0

Twitter Name change, the name should reflect the spam

Hey I know, this post has nothing to do with the trend you were looking at when you clicked the link to get here. I tweeted there just to make a point, trends are broken and full of spam!

So I have been working on some bits of code to analyze the twitter trending topics. I figure it would be a great way to be aware of what is going on in the general social consciousness. So I developed some code to pull the current trends and also list the recent tweets for those trends to give them context. Over the last few weeks I have been monitoring my prototype and making tweaks here and there. One cool thing about it is that I am much more aware of what is going on in the world, at least the world according to twitter. This morning I was looking at the tweets for the Spain trend and over half the tweets were spam. The more of them I read the more I was getting turned off of twitter. Currently I don’t think twitter has any spam fighting systems in place at all, it sure does not seem to any way. It got me to thinking about how the spammers are actually altering the trends and that as they spam a trend it makes the trend artificially strong. So not only are the spammers junking up the stream they are also diverting it as well.

With FaceBook about to release public feeds; I think Twitter had better start working fast and furious on fixing the spam issue. FaceBook’s greater verification of people, and strong desire to take Twitter’s traffic could make Twitter’s traffic surge just a blip on the internet stat counters. Frankly I am torn between wanting FaceBook to be the main public stream and Twitter. FaceBook allows longer updates and integrates video and link sharing, but Twitter gives me all of the fresh stats, feels more mashupable, and is over all much simpler.

Any one have any suggestions on what we should rename twitter so that it reflects its new spammie nature? Spitter? Spameme?

[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] 

24
Jun/09
1

jQuery makes me go hmmm

So I was busy looking into the ways to use jQuery in a prototype based object oriented fashion and was having a devil of a time geting it to work. I eventually turned to Goolge for help and I discovered this thread which is a discussion of sub-classing the jQuery object. It is mostly a back and forth between John Resig and Nate Cavanaugh covering Nate’s attempts at sub-classing jQuery. The long and short of the discussion is that jQuery has so many references to the global jQuery object that it cannot be cleanly sub-classed

So my initial concept was to subclass the jQuery object in my own objects to make new JavaScript objects with all of the functions of jQuery as well as my additions, but that is not going to work. That being said jQuery has a number of methods of adding objects and functions to jQuery; which is basically how plugins are developed. I will explore extending the jQuery and JQuery.fn objects with my own objects next.

This is part of my ongoing series of posts exploring the use of jQuery and object oriented JavaScripts, you might be interested in these posts as well:

[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] 

22
Jun/09
2

jQuery is object oriented

When I first looked at the jQuery frame work, a few years ago I immediately discounted it as a viable framework. My whole reason for that decision was that it did not add a traditional class based object oriented layer. A little more than a year later I started reading about jQuery’s speed and small size. I decided that I would give it a full chance and start using it on a few projects. I found many advantages to jQuery but was still turned off by its apparent lack of object oriented features. I wrote a blog post to that affect and the response was rather vehement as many took my statement that “you should not choose jQuery if you wanted an object oriented framework,” to be a condemnation of jQuery. Some statements though were rather enlightening, specifically ones that pointed out that JavaScript is all ready object oriented and does not need a framework to make it so.

That last point was interesting as I all ready knew that JavaScript was an object oriented language, but since it did not do objects like I learned to do them in C++ and PHP it sort of slid under my obvious filter. Suddenly I realized I need to look into how JavaScript was object oriented, started learning about Prototype-based programming, and learn how JavaScript uses it. This began a cascade of shifting thought about how to program in JavaScript and how to use jQuery. So now I am exploring how to create objects in a JavaScript centric way and how to do object oriented jQuery development.

Some things to take away from this little post is that JavaScript is object orented, JavaScript is a prototype based language and jQuery is a prototype centric JavaScript library.

This is part of my ongoing series of posts exploring the use of jQuery and object oriented JavaScripts, you might be interested in these posts as well:

[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
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] 

2
Dec/08
3

Debug JavaScript in Internet Explorer

If you have ever had the horror of finishing up some complex JavaScript in Firefox, and when you try it in IE you just get a bunch of usless and cryptic errors that all point to the wrong line of code, this article is for you. You can actually get a full debugger for Internet Exploerer for free that is about as cabable as debugging Javascript as Firebug is in Firefox.  There is no plugin or addon for IE that will give you a firebug like experience, but with a little extra downloading and work you can get a setup that will allow you to set break points and inspect objects in JavaScript applications in IE.  First thing you will need to download the free Visual Web Developer Express IDE from Microsoft Visual Web Developer is like Firebug for Internet Explorer, only it is not an addon and you have to do a bunch of setup befure it will be useful.  It is free but it will cost you more than 200 megs of hard drive space and about an hour of downloading and installing.

Once you have Visual Web Developer Express installed launch the IDE and create a new blank web site:
File >> New Web Site
Select “Empty Web Site” and give the project a name and click OK.

If your default web browser is something other than IE you will need to setup Visual Web Developer do debug in Internet Explorer by default.

On the right side of the IDE you will find the Solution Exploerer, right click on your solution and select “Browse With”.  In the browse with window select Internet Explorer and click the Set as Default button.  This will not change your system default browser just the browser that will be used by this solution by default.  Once you have IE set as default for the solution you can click cancel.



Now you need to make sure IE is ready to be debugged.  Open Internet Explorer, click on Tools >> Options, select the Advanced tab and remove the check from “Disable Script Debugging (Internet Explorer)” and click OK.

Now you are ready.  Switch back to Visual Web Developer and press F5 to start debugging.  If this is the first time you have launched this solution Visual Web Developer may display a dialog stating that a web.config could not be found.  If you recieve this dialog choose “Add a new web.config…” and click ok. This should launch Internet Explorer with an error page, just type in the URL of the page you want to debug in the address bar.  Once the page loads if you switch back to Visual Web Developer Express you will see all of the files loaded by the page in the Solution Explorer on the right.  Double click the file with the JavaScript you wish to debug, which will open the file in the IDE.  You can now set break points where you want them.  Once you have your break points set switch back to IE and take the action that will execute the code you are debugging and Visual Web developer will stop on your break points letting you inspect the objects and variables at that point.

To make the process easier you can right click on the solution in the solution explorer and select “Add New Item”.  From the presented installed templates choose “HTML Page”, and name it index.htm.  In the head of the generated HTML add a meta refresh to go to the page you wish to debug. e.g. <meta http-equiv=”refresh” content=”0;url=http://www.yourdomain.com/pagetodebug.html” />.  After adding that when you debug it will automatically redirect to the page you are working on.

[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] 

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