GridView Plugin For JQuery

There are many times when I am writing an application I need to display data in a table. Most of the time a simple HTML table styled with CSS is all that I need but occasionally I want a bit more. Today we’ll look at designing a plugin for jQuery that will add some advanced features such as row selection and sorting.

Design Goals

Starting out we are going to keep this pretty simple and as it progresses we’ll add more features.

For now we are going to start with a hand coded HTML table and CSS. In a later post we’ll look at populating the grid from a data source.

In this post today we’ll apply the CSS to the table but will expand this to a skinning system later on.

We’ll also be applying the row selection feature today.

Starting Point

Let’s use a simple table as out starting point.

<table cellpadding="0" cellspacing="0" class="easygrid">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Bill</td>
        <td>CEO</td>
        <td>53</td>
    </tr>
    <tr>
        <td>Jason</td>
        <td>Developer</td>
        <td>29</td>
    </tr>
    <tr>
        <td>Sue</td>
        <td>Accountant</td>
        <td>37</td>
    </tr>
    <tr>
        <td>Frank</td>
        <td>HR Manager</td>
        <td>42</td>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Graphic Artist</td>
        <td>31</td>
    </tr>
</table>

Basic Style

Next we will apply some basic CSS to make our grid look nice.

body, table {
     font-family: verdana, arial, sans-serif;
}

table.easygrid {
     font-size: 11px;
     width: 600px;
     border-top: 1px solid #b8b8b8;
     border-left: 1px solid #b8b8b8;
}

table.easygrid th {
     text-align: left;
     padding: 5px;
     background: #424242;
     color: white;
     border-bottom: 1px solid #b8b8b8;
     border-right: 1px solid #b8b8b8;
}

table.easygrid td {
     padding: 5px;
     border-bottom: 1px solid #b8b8b8;
     border-right: 1px solid #b8b8b8;
}

table.easygrid td.alt {
     background: #f6f3f6;
}

table.easygrid td.selected {
     background: navy;
     color: white;
     font-weight: bold;
}

Building The Plugin

Here is the basic layout of our plugin. We’ll look at implementing those functions in a minute.

This is pretty simple so far. We have our default values, we merge the user passed options with the defaults, and then call two methods on each jQuery instance.

(function($) {
     $.fn.easygrid = function(options) {
         var defaults = {
             alternateBackground: true,
             allowRowSelect: true
         };

         options = $.extend(defaults, options);

         return this.each(function(index, table) {
             setAlternateBackground($('tr:odd td', table), options.alternateBackground);
             rowSelection(table, options.allowRowSelect, options.alternateBackground);
         });
     };
})(jQuery)

Here is our setAlternateBackground method. Note we are passing all the odd rows found in the current table.

function setAlternateBackground(rows, alt) {
     if(alt == true) {
         rows.attr('class', this.className + ' alt');
     }
}

This function appends the alt CSS class to each row if alternate row backgrounds is enabled.

The next function adds a click handler to each row to implement the row selection functionality.

function rowSelection(table, allowSelect, alt) {
     if(allowSelect == true) {
         $('tr', table).click(function() {
            //reset all rows
            $('tr', table).each(function() {
                $('td', this).each(function(index, cell) {
                    $(cell).attr('class', cell.className.replace(' selected'));
                });
            });

            //restore alt backgrounds
            setAlternateBackground($('tr:odd td', table), alt);

            //select this row
            $('td', this).attr('class', this.className + ' selected');
        });
    }
}

There is a little more involved with this function. If this feature is enabled we are adding a click handler to all the rows in the table.

First the click handler will clear any selected rows and reapply the alternate background colors. I am not sure why this gets lost.

Then, finally, the row that was clicked is selected by applying the selected CSS class to each cell of the row.

What’s Next?

That is it for this post but we will look at adding sorting to our grid in post in the near future.

Currently the row selection is a bit buggy in Firefox but works fine in IE. I will have the Firefox issues sorted out for the next post. You can check out a demo here.

Be sure you don’t miss out by grabbing the RSS feed, updates by email, or following on Twitter.

kick it on DotNetKicks.com Shout it

6 Tools To Be An Effective Web Developer

Over the last few years Rails has helped Ruby’s popularity explode. One of the biggest reasons for this is the time that Rails can save you. By working within a well defined framework a lot of development decisions are simplified and it is easier to be more organized. Throw in some great tools like ORM, Unit Testing, Mocking, and more and you have a powerhouse of developer efficiency and quality.

There has always been and probably always will be feuds over what is the best platform but what I want to show you is that those arguments are mostly irrelevant. Regardless of what platform you choose to develop on there are most of the same tools available in one form or another. The common components, for me anyway, that help me produce high quality code faster and is easier to maintain are a good IDE, easy to use unit testing and mocking frameworks, an ORM, a MVC framework, and a good JavaScript library.

I am a .Net developer by trade and a PHP developer sometimes by choice. I enjoy both environments for different reasons. I am going to talk about each of these components in a bit of detail and explain why I think they are important and then at the end of the article I will provide a list of each of these components for various languages (.Net, Java, PHP, Python, and Ruby). I have decided to only list free or open source tools because they are easy for someone to try out and we all like to save a few bucks.

The Integrated Development Environment (IDE)

To me this is the prime essential. Sure you can program in Notepad and compile with the command line but it will likely take longer and it will require more discipline to stay organized. With a good IDE you have easy project management (all you files grouped together with tabbed browsing), syntax highlighting, compilation (if applicable), and auto complete.

IDE are continuously getting more and more sophisticated and plugins allow for lots more functionality like svn and git management in the IDE.

For me my favorite IDE is Visual Studio. There are some other great programs out there like NetBeans and Eclipse but for whatever reason I have become partial to Visual Studio.

Unit Testing And Mocking

These two items go hand in hand. No application is complete without proper testing. There are plenty of people on both sides of the fence when it comes to testing. I know, I was a skeptic for a along time. It just felt weird to spend time writing code to test the real code I was going to write. Finally I just decided to give it a try and it has changed the way I program. When you are focusing on how to test your code you just write cleaner code and it’s nice to have a quick way to know if the change you just made broke anything.

Object Relational Mapper

If you have ever used an ORM you know that it can save you a huge amount of time. One of the concerns I had before jumping to an ORM was performance. I wanted to know if using an ORM would make my application slower but I was asking the wrong question. I should have been asking whether or not the small performance hit was worth the huge time savings. The answer to that is a definite YES! Rarely in an application will the ORM be the source of poor performance and if it is it can be refactored to improve or you can use straight SQL if need be.

It all comes down to not worrying about performance issues before you have any. Yes it is important to keep performance in mind but using an ORM shouldn’t be anything to worry about.

MVC Framework

MVC has become very popular thanks in part to Rails and it’s revolution in the way we do Web Development. The key component to it’s popularity is that it separates the different concerns of your application into seperate pieces. This separation allows easier testing, better design, and makes your application more maintainable overall.

JavaScript Library

It seems there is a JavaScript library for just about everything these days. I remember not too long ago there were that many and JavaScript use hadn’t exploded yet. A JavaScript library is important to your productivity. The library shouldn’t compensate for poor JavaScript skills, you need a solid foundation, but should compliment a good understanding of it. The library will take care of browser compatibility issues and low level operations letting you focus on getting the job done.

ASP.Net
IDE: Visual Studio 2008 Express
Unit Testing: NUnit
Mocking: Rhino Mocks
ORM: NHibernate
MVC: ASP.NET MVC
JavaScript: jQuery

Java
IDE: NetBeans
Unit Testing: JUnit
Mocking: EasyMock
ORM: Hibernate
MVC: Struts
JavaScript: jQuery

PHP
IDE: PHPEclipse
Unit Testing: PHPUnit
Mocking: PHPMock
ORM: Propel
MVC: Symfony
JavaScript: jQuery

Python
IDE: PyDev
Unit Testing: PyUnit
Mocking: PythonMock
ORM: SQLObject
MVC: Django
JavaScript: jQuery

Ruby
IDE: RadRails
Unit Testing: Test::Unit
Mocking: Mocha
ORM: Sequel
MVC: Rails
JavaScript: jQuery

Be sure to grab the RSS feed, get updates by email, or follow me on Twitter to stay up to date and not miss any posts.

kick it on DotNetKicks.com Shout it

JavaScript And The rel Attribute

Working in JavaScript is one of my favorite things to do. I love how dynamic the language is and how powerful it can be. discount carpeting . This programming dream is often turned into a nightmare by varying browser implementations, blatant disregard for accepted Web Standards (I’m looking at you IE), and a host of other odd things that can pop up.

The Problem

As is usually the case, Internet Explorer is very forgiving when it comes to the DOM and lots of times implements alternate methods of accessing certain functionality.In my current project I am using the rel attribute to keep track of which row of data is being accessed. I know some of you may frown on this, however, it is an acceptable (to me) tactic as this is for a closed intranet where there is no concern for search engines. In Internet Explorer object.rel is an acceptable method for accessing the value of the rel attribute of a particular property.Somehow I worked past this point without testing in Firefox so when an error kept occurring that was caused by Firefox not liking object.rel it took me a while to work back through the code to isolate this problem.

The Resolution

The problem has a really simple fix. In my case it was harder locating the problem then actually fixing it. To get around this problem you don’t need any object detection, you just need to use the standard method for accessing attributes, object.getAttribute(‘rel’). Go figure.

The Moral Of This Story

The lesson that we should take away from this is to only use approved, standard methods of functionality. casino online . This too will lead you into problems due to inconsistent implementations but at least you are doing it the right way. You can then implement your own work-arounds or use a library like Dean Edwards’ IE7 script that will fill in all the holes in Internet Explorer to make it more standards compliant.kick it on DotNetKicks.com

How Do I Enable JavaScript On My Computer?

What is JavaScript?JavaScript is used on a lot of websites to make your experience better and to allow for more interaction with the website. It is possible for Javascript to be disabled so the steps below show you how to enable JavaScript in the event that is gets disabled.More and more sites and services are requiring JavaScript. relationships . An example is Google Docs. Without JavaScript enabled you cannot use the service at all.How do I enable JavaScript on my computer?Internet Explorer (6.0)1. Select Tools > Internet Options.2. Click on the Security tab.3. Click Custom Level button.4. Scroll down to the Scripting section.5. Under Active Scripting, select Enable and click OK.Internet Explorer (7.0)1. Select Tools > Internet Options.2. Click on the Security tab.3. Click the Custom Level button.4. Scroll down to the Scripting section.5. Select Enable for Active Scripting and Scripting of Java Applets.6. Click OK.7. Select YES if a box appears to confirm.8. Click OK. painting color wheel . Close window.9. Reload page.Mozilla Firefox (2.x)1. Open Firefox.2. On the Tools menu, click Options.3. Click Content in the Options list.4. Under the Content section, check the box next to Enable JavaScript.5. Click the Advanced button to open the Advanced JavaScript Options box.6. Check the boxes under Allow scripts to section that you want to allow.7. Basement Remodeling Denver . Click OK.8. Click OK.Why would you want JavaScript disabledThere are a few reasons you might want to disable Javascript:1. You don’t want to see annoying ads that get past popup blockers.2. JavaScript code can crash your browser or make the website very slow if it is written poorly.3. You don’t care about bells and whistles and just want to get to the content.

Why Must Internet Explorer Torture Me?

Internet Explorer never ceases to frustrate me. I have been writing my own JavaScript library, mostly to sharpen my skills. I was moving along and had written a large portion of code, easy OOP classes, a few utility functions, and my HtmlElement extensions. Problem was I had only been testing the code in Firefox. louis vuitton outlet . At this point I desided to run it through Internet Explorer just to verify that it worked. becker animal hospital . This is where I stayed for about 30 minutes. No matter what I did I could not get things to run in IE. landscape jobs . It kept throwing a useless error, ‘Object expected’, that didn’t seem to relate to anything.As it turns out IE has a couple of instances you cannot use.First off you cannot use the word class in any way, shape, or form. It doesn’t matter if it is a method or property of an Object, you just can’t use it.Secondly, you cannot have a method or propery of an Object named extends.These apply to all lowercase letters only. cheap longboards . If you try this IE will throw errors all day long while every other browser in the world will gladly accept it and run fine. I should have guessed when I saw that Mootools was using Class and Extends but then again it is just impossible to guess what kind of mess is under the hood of IE.If you are wondering this is not fixed in IE8 beta 2 either…probably never will be. My guess is that they are used internally somehow so you are blocked from using them.Hopefully my 30 minutes of frustration will save you from running into this problem.

//what doesn't workvar class = function() { };var obj = { extends: function() { } };//what worksvar Class = function() { };var obj = { Extends: function() { } };

How To Find The Position Of An Element

From time to time I need to know what the position of a particular element is.I could use trial and error until I find the correct position but this is not efficient and it breaks the second I make an adjustment to the elements or any of it’s parent elements. Atlanta Plumbing Company . So how can we easily get an elements position? I’m going to break this up a bit so it will be easy to understand.First we will create a function that excepts an element.

function getPosition(element) {

Next we’ll initialize some variables to hold our running totals.

var left = 0;var top = 0;

Now we’ll ensure that the offestParent property is supported.

if(element.offsetParent) {

This next part is the real meat of the function that will traverse the DOM and calculate the offset values. This loop will continue until element is null.

while(element) {left += element.offsetLeft;top += element.offsetTop;element = element.offsetParent;}

Finally we just return the calculated values.

}return {offsetLeft: left, offsetTop: top};}

This function will now give use the exact position of the top left corner of any element we pass to it. auto seat cover . limousine service . I have tested it in IE7 and Firefox 2 but it should work in any browser. We’ll look at a task in my next post that uses this function to calculate pixel coordinates on an image element. Be sure to grab the RSS feed from the link at the bottom of this post because you won’t want to miss the next post.Here is a working sample for you to try.

<html><head><title>Find Element Position Example</title></head><body><div style="padding:10px"><div style="padding:17px"><div id="elem">My Element</div></div></div><script>function getPosition(element) {var left = 0;var top = 0;if(element.offsetParent) {while(element) {left += element.offsetLeft;top += element.offsetTop;element = element.offsetParent;}}return {offsetLeft: left, offsetTop: top};}var element = document.getElementById('elem');var pos = getPosition(element);alert(pos.offsetLeft + ', ' + pos.offsetTop);</script></body></html>

Understanding scope in object oriented JavaScript

When you think of the keyword this you probably assume it refers to the current instance of the class. This is true for most object oriented languages like C# and Java.For example I could use the this keyword in C# like this:

class Cat {string _name;public Cat(string name) {this._name = name;}}

In the above example you see this illustrated. In C# and Java, this always refers to the class instance.So, knowing this you would probably assume the same would be true of JavaScript and it’s this keyword. This is, however, not the case. Like a lot of things about writing object oriented code in JavaScript, this behaves differently in some situations. this does not always refer to the class instance depending on how you use it.

function Cat(name) {this.Name = name;}

In the above example it works just like our C# example but let’s look at a situation where things can go wrong if you are unaware of some rules.

var wrong = new WrongClass();wrong.publicMethod();function WrongClass() {this.publicProperty = 'props';this.publicMethod = function() {console.log('public method');privateMethod();};var privateMethod = function() {console.log('private method');console.log('public property equals ' + this.publicProperty);};}

In my examples I am using the console object of Firebug to output my data.So what is wrong with the above example? It looks like everything should work, right? Well, operating on the assumption that this always refers to class instance then the above code would be correct. We are, however, using JavaScript and shouldn’t be that surprised that it does things a little differently.The output when publicMethod() is called would be:

>>> public method>>> private method>>> public property equals undefined

The reason this.publicProperty is undefined is because when entering the private method the scope of this changed. It no longer means the current instance of the class ‘WrongClass’ but it now means the current instance of the function ‘privateMethod’.Another situation where the scope of this would change is when dealing with event handlers.

document.getElementById('button').onclick = function() {alert(this.id);}

In the above example this would refer to the instance of the document element ‘button’. There are many cases of scope change that you need to be aware of when dealing with object oriented techniques.Back to our ‘WrongClass’ example. maryland self storage . I’ll show you how to make that example work the way you would have expected it to work in the first place.

var right = new RightClass();right.publicMethod();function RightClass() {var self = this;this.publicProperty = 'props';this.publicMethod = function() {console.log('public method');privateMethod();};var privateMethod = function() {console.log('private method');console.log('public property equals ' + self.publicProperty);};}

You’ll see that in the above code I have declared a variable called self. I assign this to this variable. This allows me to then use ‘self’ any time I want to refer to the class instance without worrying about scope.You can call your variable anything you like but ‘self’ seems to be a common practice. So, now in ‘privateMethod’ when ‘publicProperty’ is called using ‘self’ it will output the proper value.

>>> public method>>> private method>>> public property equals props

kick it on DotNetKicks.com

Update on the Twitter API

Firstly I would like to thank Wink Chin for sending me an email to let me know the link to the demo of the Twitter API was broken. I have fixed that so you should have no trouble previewing the code in action.

I haven’t done much work on the API lately but I have noticed a buzz around the blogosphere about Twitter and it looks like a good opportunity to revive the project. I hope to be posting more about the API in the near future and will hopefully have some updates and new features for you to play with.

The latest updates for the API are here and here and you can download the demo code here.

Friday roundup for May2, 2008

Here is some highlights from this week.

Hijax
When I was originally writing the DOM Scripting book, its scope was very clear – it was to be an introductory work on JavaScript and the Document Object Model, with an emphasis on best practices. I made a conscious decision not to cover advanced topics like XMLHttpRequest.

But as the writing of the book progressed, Ajax really began to explode. It became clear that I’d have to at least mention the subject, even if I couldn’t cover it in detail. That’s where the book’s final chapter came from.

Jason Calacanis, Please Help Me Become A Pathetic Affiliate Marketer
I’m hoping Jason Calacanis can help me out here. Everyone knows that Jason loves to stir up trouble at Internet conferences and he recently caused quite a stir at Affiliate Summit West a couple months ago when he referred to Zac Johnson’s $300,000 check from Yahoo as pathetic.

Simple Subverison Repository Setup with VisualSVN Server
I have a few projects I am developing for my own company and choosing source control has really not needed much discussion. I use Subversion for everything because it’s free, works really well, has great community support and support a wide-variety of clients on many operating systems.

Why I’m a better software developer than you
What makes one developer better than another? Shouldn’t we all be performing at the same level? Of course not, we’re not sewing buttons on an assembly line. We’re using every bit of our intelligence to create something that we can only begin to understand.

Friday roundup for April 25, 2008

Here is what I liked this week. Enjoy!

Comparing Popular JavaScript/Ajax Frameworks
After four days of ASP.NET AJAX training with Stephen Walther I set out to learn more about my options in choosing a solution for a JavaScript/Ajax framework. If I realized days later I would be writing this comprehensive post on 7 of the most popular frameworks, I may have just went with the “Inny-Minny-Miney-Moe” method!

jQuery AJAX calls to a WCF REST Service
Since I’ve posted a few jQuery posts recently I’ve gotten a bunch of feedback to have more content on using jQuery in Ajax scenarios and showing some examples on how to use jQuery to cut out ASP.NET Ajax. In this post I’ll show how you can use jQuery to call a WCF REST service without requiring the ASP.NET AJAX ScriptManager and the client scripts that it loads by default. Note although I haven’t tried it recently the same approach should also work with ASMX style services.

SQL SERVER – Better Performance – LEFT JOIN or NOT IN?
First of all answer this question : Which method of T-SQL is better for performance LEFT JOIN or NOT IN when writing query? Answer is : It depends!

Video: Write Your First Silverlight Game
In this video, I demonstrate how to start writing your first Silverlight game. I show how to create a dramatic space scene, add a soundtrack, and associate movement with the mouse wheel. This is the first part of a two-part series.

Reading binary files using Ajax
But when it comes to binary files, helping hands from server-side technologies are often necessary.

So I googled around to see what I can do about binary files with Ajax and found this Marcus Granado’s post at http://mgran.blogspot.com/2006/08/downloading-binary-streams-with.html

What he posted there worked like a charm for FireFox and Safari but I couldn’t get it to work for IE.

But luckily, within the same page, someone had posted up a solution for IE as a comment, which is written in VBScript.

Safari CSS Masks
Webkit continues to impress with it’s early implementations of new standards. WebKit now supports alpha masks in CSS. Masks allow you to overlay the content of a box with a pattern that can be used to knock out portions of that box in the final display. In other words, you can clip to complex shapes based off the alpha of an image.

Friday Roundup for April 18, 2008

aveda institute dc . It’s been a slow week for me as far as reading and blogging goes but here are a few bits from this week.Javascript: Introducing Using (.js)The goals of using.js are to:

  • Seperate script dependencies from HTML markup (let the script framework figure out the dependencies it needs, not the designer).
  • Make script referencing as simple and easy as possible (no need to manage the HTML files)
  • Lazy load the scripts and not load them until and unless they are actually needed at runtime

Youre Fat and I Hate YouIt irritates the hell out of me that so much modern JavaScript development hinges on frameworks. Not because theres anything wrong with that in pragmatic terms, but because Im interested in the mechanics of things, and programming with frameworks obscures the mechanics.

Friday roundup for April 4, 2008

Here are some interesting stories from this week.

IE 8 strict mode doesn’t allow for CSS opacity?
So the fact that this has been labeled as by design suggests that IE8 will be the only browser produced in the last 10 or so years that will not support opacity in its strictest mode. Thats rediculous.

Google Will Sell Performics, SEOs Exhale
Exciting news from The Official Google blog today that reveals Google will stop scaring SEOs everywhere and will sell off Performics, the search marketing company that they accidentally acquired when they bought DoubleClick last year. To avoid the conflict of interest that comes when you’re a search engine selling search engine optimization services, Google will split Performics into two companies – an affiliate marketing company and a search marketing company – and then sell the search marketing half.

Webforms is dead. Long live MVC!
Scott Hanselman’s fourth screencast *confirms* that the interfaces and abstractions made as part of the MVC (HttpContextBase, IHttpRequest, IHttpResponse, etc.) will not be put into the existing Webforms model. That means that once MVC is released, the old HttpContext object in WebForms will *not* inherit from HttpContextBase, nor will the WebForms versions of HttpRequest and HttpResponse objects implement the interfaces.

But I’m not moving my mouse!
The IE team reacted correctly: the bug has been solved in IE8b1. When the mouse does not move any more the mousemove event stops firing, as it should.

However, this same bug was recently introduced in Safari (Windows) and Opera!

Safari 3.0 and Opera 9.26 support mousemove correctly, but Safari 3.1 and Opera 9.5b have copied the IE bug.

JavaScript defining and using custom events

kick it on DotNetKicks.com

What are custom events?

Simply, a custom event is something that happens that you feel is important enough to define actions to execute when this something happens. Clear as mud? I think I confused even myself. A custom event is just like a native event (onclick, onload, etc) except you define what it is and when it should fire.Dustin Diaz explains custom events extemely well in his post about JavaScript custom events.So why am I posting about it too? Well Dustin’s explaination and implementation uses the Yahoo User Interface library (YUI). I don’t use YUI. So I wrote up a simple class that allows you to implement custom events that is library independent.

The class

Here is the JavaScript class that is the base for our custom events.

var CustomEvent = function() {//name of the eventthis.eventName = arguments[0];var mEventName = this.eventName;//function to call on event firevar eventAction = null;//subscribe a function to the eventthis.subscribe = function(fn) {eventAction = fn;};//fire the eventthis.fire = function(sender, eventArgs) {this.eventName = eventName2;if(eventAction != null) {eventAction(sender, eventArgs);}else {alert('There was no function subscribed to the ' + mEventName + ' event!');}};};

So here we have a class that defines the name of the event, subscribes a function to use, and a method to fire the event. Pretty simple.

Simple example

Here is a simple example of how to setup a custom event.

var myEvent = new CustomEvent("my event");myEvent.subscribe(function(sender, eventArgs) {alert(eventArgs.message);});

The above code creates an instance of CustomEvent and assigns a name of “my event”, how creative :D . denver retirement homes . Then it subscribes a function to the event via the subscribe method. The function that is subscribed will display an alert box with the value of the message event argument. The sender and eventArgs get passed when the event is fired. We’ll look at this next.

Firing the event

Finally we will fire the event. This can be done from anywhere in your application.

myEvent.fire(null, { message: 'you just witnessed the firing of a custom event called ' + this.eventName + '!'});

We assigned a value of null to the sender argument because there is nothing that initiated the event fire in this case. If you had created this event in a photo gallery application and the event was to fire whenever a photo was inlarged (onEnlarge?) you would probably make the sender the photo that was enlarged. This would allow you to pass the photo to your enlarge method from inside the event. The possibilities are endless.And lastly we assigned a value to message. Note that eventArgs is a JavaScript object (either { } or new Object()). This is important so you understand how to assign eventArgs properly.Happy event creating.

Friday roundup for March 28, 2008

Here is what I found interesting this week.

Key events and Safari 3.1
There has been a change in Safari 3.1 for how keypress events are handled. John Resig interviewed Yehuda Katz to get the skinny and understand why this was done.

eBay Discriminates Against Ebook Sellers, Squashes All Digital Downloads
In what will go down in Internet history as probably one of the lamest decisions ever in e-commerce, running second only to the firing of AOL CEO Jon Miller in 2006, eBay announced yesterday it will no longer allow any digitally downloadable product to be sold via an auction.

Where’s my .NET 3.5 (on IIS), Dude?
The not so obvious ‘problem’ is that if you fire up a machine that has .NET 3.5 installed, you might be surprised to find that the IIS service panel’s ASP.NET does not show an option to select the .NET Runtime of 3.5.

Opera and WebKit pass Acid3 test
The latest builds from Opera and WebKit are scoring a perfect 100/100 on the Acid3 test. Wow!

Where is Firefox on Acid 3? Here.
Some people have been surprised to not hear much from Mozilla around Acid 3. WebKit and Opera are duking it out, but what about Firefox?

Mike Shaver of Mozilla has posted on his views that Acid 3 is a missed opportunity and is pretty damning of the whole thing.

Using the YouTube API via Ext
With the YouTube API recently released, there’s bound to be lots of cool controls coming out soon. Thorsten Suckow-Homberg spent a weekend hacking up a Ext-based user extension that leverages YouTube’s chromeless API to build The Ext.ux.YoutubePlayer.

20 Types of Pages that Every Blogger Should Consider
When you use WordPress you’re given the choice when publishing between doing it as a ‘post’ or as a ‘page‘. Posts go up on your blog while ‘pages’ are static pages that you can publish without it having to go up on your blog.

Base2: A Standards Based JavaScript Library

I’ve posted about Dean Edwards‘ Base2 library in the past but I wanted to write a post that brings all the growth Base2 has under gone over the last couple of years into a brief overview of the project so it is easy to see the progress Dean has made and where the project is headed.

In early 2006 Dean Edwards began a little project called Base. This was he first attempt to ease the pain of developing Object Oriented JavaScript.

I want a nice base class for JavaScript OO:

  • I want to easily create classes without the MyClass.prototype cruft
  • I want method overriding with intuitive access to the overridden method (like Java’s super)
  • I want to avoid calling a class’ constructor function during the prototyping phase
  • I want to easily add static (class) properties and methods
  • I want to achieve the above without resorting to global functions to build prototype chains
  • I want to achieve the above without affecting Object.prototype

About one year later Dean released the next iteration, Base2. Although Base was a fairly simple library to use there was no documentation. Other than Dean’s, very helpful, posts on his website there was nothing you could refer to in the traditional reference sense.

In August of 2007 there appeared a nice post on Dean’s site that annouced the arrival of some documentation for Base. Although it is stamped as currently incomplete (at the time of this article anyways) it is a huge boost for the library and the community that has grown around it.

In early 2008 Dean released some improvements for Base2 and some nice code examples further demonstrating what the library can do to make developer’s lives easier.

One thing that, I believe, makes Base stand out, and Dean as an excellent programmer, is his commitment to standards. Base adherse to some fundamental OOP rules, which Dean has outlined in a nice reference guide for library developers.

Base has enjoyed great admiration in the JavaScript community with other libraries using it as a starting point for their library cores.

Thanks Dean for the great leadership you bring to the web development community and keep up the great work.

Method overloading in JavaScript

If you have been programming for any length of time you probably know what method overloading is or have at least heard of it.

What is method overloading?

Method overloading is a feature found in various object oriented programming languages such as C#, C++ and Java that allows the creation of several functions with the same name which differ from each other in terms of the type of the input and the type of the output of the function.[Wikipedia]

With the formalities out of the way, there are times when method overloading can be very helpful. JavaScript is no exception. The problem is it is not as apparent how to achieve method overloading in JavaScript because it doesn’t work the same as more traditional languages do.

What won’t work

Let’s look at implementing an overloaded function how you would think it should work.

function myFunction() {  //function with no arguments}function myFunction(arg) {//overloaded function with one argument}

Now JavaScript will accept this and you may think you are done. car seat cover . Think again. You do not have an overloaded function. In the above example your second function definition just overwrote the first so you only have a function that excepts one argument. I told you it doesn’t work the same.

What will work

Now that we have looked at what won’t work let’s take a look at the proper way to implement an overloaded function.Let’s look at a simple example using bunnies. Awww, how cute.

function getBunnyColor() {var name = arguments[0] == null ? 'peter' : arguments[0];switch(name) {case 'peter':return 'brown';break;case 'flopsy':return 'white';break;default:return 'unknown bunny';break;} }getBunnyColor(); //-> 'brown'getBunnyColor('flopsy'); //-> 'white'

What is that?

Now I’ll explain what I did. Every function has an array called arguments. This array contains the arguments that are passed into the function even if specific arguments are declared in the function definition.So knowing that I didn’t bother to declare any arguments when I defined the function. malibu alcohol detox . I instead used the arguments array to detect what had been passed in. If arugments[0] was null (no argument had been passed) then I assigned a default name of ‘peter’.

Conclusion

So JavaScript implements method overloading a bit differently than most languages meaning your function definitions will look different but you use the overloaded functions the same way. Hope this helps you out!

Friday roundup for March 21, 2008

Well it is Thrusday but I won’t be around to post this on Friday being a holiday and all. I only have one link for you this week. d man . Either it has been a boring week for dev blogs or I have been way to busy with other things to find them. Enjoy.A collection is not an arrayJames Edwards summeriezes this point. heating repair . Although at first glance a collection of DOM elements may look like an array (you can iterate like an array) but ultimately it is not an array and lacks many of the array methods like push().


Friday roundup – March 8, 2008

I have decided to start doing a Friday round up of all the interesting articles I find during the week. Here are some stories I found interesting for the week of March 3 to March 8. Enjoy!

Internet Explorer 8 will render in Standards Mode by default
The IE team has announced that it will render HTML markup in “the most standards compliant way it can.” It is nice to see that MS has decided to actually listen to what web developers want, in regards to IE, for a change.

The Top 5 Recommendations For Monetizing Your Blog
The readers over at ProBlogger have given their top recommendations on how to make some money with your blog.

Acid 3 released, Webkit praised
Jon Tan ran a few tests and posted the results. Hixie commented on his blog about the release, and praised WebKit on how they have been closing a large number of bugs

Silverlight to run on Symbian phones
Microsoft is working with Nokia to get Silverlight running on Symbian mobile phones. Would this help influence your decision to use Silverlight for UI over other technologies?

MVC Framework Preview 2 released, Jeff Palermo disappointed
Jeff gives a good overview, along with his opinion, of the changes that have been made in preview 2.

Internet Explorer 8 beta 1 is now available for download.
Take the first release of IE8 for a test drive. Will it deliver this time?

Use Javascript to open a link in a new window

This is a common question I see a lot on the Web Development Forum I help moderate. Many new developers read the tutorial on XHTML and ask “if target is depreciated then how do I open a link in a new window?” The answer is you use JavaScript. It is true that if the user has JavaScript disable then the link won’t open at all, right? I’ll show you the best way to open a link and have it degrade gracefully if JavaScript isn’t enabled and will even defy popup blockers.

Our leading lady, the anchor

Here is the link we’ll use for this article and will add our JavaScript to this link later on.

<a href="http://www.w3schools.com">Web Development Tutorials</

IE7.js version 2.0 (beta)

Dean Edwards has released the next version of his IE7 script to fix IE’s implementation of JavaScript.

I’ve made some important changes to the script which Ill now outline. * The IE7 project is now hosted on googlecode (I got fed up with SourceForge). Toshiba TVs . * IE7 is no longer modular. storage unit . Instead Ive merged the scripts into two: IE7.js and IE8.js * IE7.js includes only fixes that are included in the real MSIE7 browser. * All other enhancements are moved to IE8.js. * IE7 is now much smaller (11KB gzipped). * IE7 is now much faster (it uses the selector engine from base2.DOM) * There are no dependencies on other files (except blank.gif) * You can hotlink IE7/IE8.js directly from Googles servers (usage instructions below)Some fixes are removed completely: * the :root selector * support for XML files * support for CSS namespaces * the fix for base64 encoded images

Base2: Dean Edwards announces beta

There has been some movement on the base2 project by Dean Edwards. He recently announced the beta testing stage for base2 after being in development for sometime.

There are some great features in base2 and you should check it out. Dean has posted 3 articles on his blog with code samples for the base2 beta.

base2/base2.DOM in Beta
base2.DOM is now ready for a beta release. As previously discussed, I’ve renamed the Selectors API methods to keep in line with the standard.

base2: An Introduction
I’ve been working on base2 for a couple of years now and it is finally ready for a beta release. With base2 I aim to solve various problems with inconsistent JavaScript implementations and add a little sugar to the language at the same time.

Organise Your Code with base2.Package
A base2.Package provides a mechanism for bundling classes, constants and functions within a closure. You can define what symbols you want to export from the Package and you can define the symbols you want to import into the closure.

Internet Explorer doesn’t just suck, it also blows!

brothercake of sitepoint.com has taken the time to outline not only how Internet Explorer fails to implement standard specifications but also that it doesn’t even implement it’s own propritary features in a consistant way. This article proves once again just how badly IE is implemented.

Im spending most of my time these days working on SitePoints upcoming Ultimate JavaScript Reference, a task that I can fairly say is eating my brain.Unlike the authors of the imminent Ultimate CSS Reference, I didnt have any particular inclination to be nice to Internet Explorer. Solar Training . Robert M Pardes . And I knew I was going to run into bugs and quirks, none of which would be any different in IE7, because the DOM simply wasnt on the development radar for that version.Even so, Ive been nothing short of staggered at the sheer amount of chaotic brokenness evident in its implementation of even the simplest of things.You may remember, not so long ago, that I wrote about the behavior of href attributes in Internet Explorer, and how for links they come back as qualified URIs rather than literal attribute values. But, oh man that is so the tip of the iceberg when it comes to getAttribute()

Read more…

Object Killing in IE7

Jon Sykes has discovered a bizarre bug in Internet Explorer 7 (and presumably IE6 as there is next to no difference in the JScript engines). You probably wouldn’t encounter this bug very often but if you did it would really make you pull out your hair trying to debug.

There is a bug in IE7 where by a line of code inside a conditional statement that NEVER runs, can cause an object that is set with a fairly standard object declaration to be whipped. heating and air . Things To Do In Atlanta . Even weirder is that it will have whipped the code even if you put a debug alert of the object before the code that does the whipping. Confused? I know I am.Thankfully it does look fairly simple to work _around_ and avoid. But it’s probably a debug nightmare, and it’s a bug I couldn’t find referenced anywhere, so I figured it was worth sharing.

Links for November 26 2007

Ajax with the ASP.NET MVC FrameworkOne of the prototypes is around bringing some basic Ajax functionality – basically to get post-back-less partial rendering and some behavior-like extensions to associate with DOM elements – sort of like ASP.NET Ajax but in a manner that fits with the pattern around how controllers and views are written. I should say that eventually Ajax functionality will exist out-of-the-box, so you can think of this as an early experiment, and by no means complete. In the spirit of experimentation, feedback and suggestions are welcome.Automatic Bug Reporting in Global.asaxOne thing I really like about .NET is the flexibility and speed it gives you to implement new functionality. By using ASP.NET’s Global.asax file, you can very easily hook into any major application events that occur in your system. Perhaps one of the most useful of these is the Application_Error event, which fires everytime an unhandled exception occurs within your site. roofing repairs . During your testing phase, this can be a very useful place to find out how your users are experiencing your stystem.

How not to use ASP.Net AJAX

.Net Playground has put together a great series on avoiding mistakes when using ASP.Net AJAX.

Part 1
Part 2
Part 3
Part 4

I’ve worked with ASP.NET AJAX long enough now to appreciate both the increases in productivity on the development side, whilst also discovering the significant bloat it adds to sites where it’s implemented. In light of this, I’ve decided to put up a number of posts on how you can reduce the dependancy your sites have on this model.

On the development side of things, the ASP.NET AJAX model is fantastic. Any part of your site that you want working asynchronously you just drop inside an UpdatePanel and you’re away. You don’t need to code nor maintain any javascript, it’s simply plug & play.

However with this convenience comes a lot of overhead. Not only do visitors to your site have a significant initial download to get all the javascript libraries, each call from a control or trigger for an UpdatePanel will then cause the entire viewstate for that page to be sent to the server, and a new one returned. This is where things can get out of hand.

For small sites with a limited number of sever controls on a page, the viewstate can be quite small and hence this isn’t an issue. However as the size and scale of your site increases, it’s almost inevitable that more server controls will be added to your page, increasing the viewstate size, and each subsequent postback to the server.

Links for November 19 2007 – ASP.Net MVC Framework, Tamarin in IE

Why MVC Has Me Concerned
Everyone is talking about the new MVC framework that will be released in the coming weeks as a CTP, and so far everyone is very pumped about the way it will revolutionize web application development…how it will allow us to utilize testing tools, TDD, etc. It’s always mentioned with reverence and joy.

Well, hello: my name is Killjoy…

ASP.NET MVC Framework is almost here
Tutorials and previous are already posted on the web, As always Scott Guthrie is the first person to provide with an complete overlook of the new framework.

Mozilla Announces Screaming, Iron, Action Monkeys – Tamarin in IE
Brendan Eich always delivers on a great keynote, and to conclude the opening day of the show, he had some announcements up his sleeve.

Mozilla has three monkey’s up their sleeve:

Getting started with Virtual Earth Mashups: showing current weather conditions on a map

Juan DoNeblo has put together an amazing tutorial on getting started with Virual Earth Mashups. atlanta tree removal . This is a must read if you are even thinking about taking Virtual Earth for a test drive.

In this article we’ll see how easy it is to use Virtual Earth SDK to produce a simple mashup, using web services that provide information in JSON format.If you are not familiar with JSON or how to integrate JSON services in ASP.NET AJAX applications, you can take a look at my 3-part series of articles on JSON and ASP.NET AJAX here.First of all, we need to create a simple .aspx page, and add a ScriptManager to it. Then, we’re going to reference the Virtual Earth API in the ScriptManager’s Script section…

Is Microsoft Committed to AJAX ?

This is a great post by Joe Stagner on where Microsoft is heading with AJAX and it’s plans for the future.

I got this recently in an email from a developer friend.
Is Microsoft committed to Ajax? If so, why is development so slow? (Yeah I know, Silverlight, that means nothing until it is at least version 2 and wide spread.) I am seriously disappointed, and I think others are too. After the 1.0 excitement, there is nothing to get excited about. (What’s up with ASP.NET Futures anyway, how about right now?)

I guess that it’s hard to keep up with all the new stuff in our profession, so I thought I would hi-light some of the new AJAX related stuff that we’ve been building, especially in ASP.NET 3.5 and Visual Studio 2008 (currently in Beta) as an illustration our investments in AJAX enabling technologies. * Core Integration of ASP.NET AJAX – ASP.NET AJAX is no longer an add-on to ASP.NET. It is now a first class concept like XML Web Services or Data Access. This means full support, full feature lifecycle, etc. * Full and Dynamic JavaScript Intellisense support in Visual Studio 2008. This includes the JavaScript language and all the ASP.NET AJAX Extensions as well as dynamic support for the code that you write. * First Class JavaScript Debugging Support in Visual Studio 2008, complete with Break Points, Watch, Immediates, Call Stack, everything you would expect from a first class debugger PLUS, both design time and run time code images so you can drill down into your applications exact JavaScript state and collection at runtime no matter how much dynamic JavaScript is involved in your application. mini storage . * JSON, RSS, and POX support for WCF so that all your WCF services can me AJAX Callable. * The AJAX Controls Toolkit has grown to 34 controls. * 64 ASP.NET AJAX How Do I Videos offering tutorial and prescriptive guidance on how to use the features of ASP.NET AJAX * Forthcoming soon….new ASP.NET AJAX controls like the history control, selector support, and other improvements on both the client and server side.To me that seems like a lot of work in a fairly short time (since ASP.NET AJAX 1.0 was released.)

What’s with the “Futures” ???

The current “Futures” include …. * History support for the Safari browser, inclusion of titles, encoding and encrypting of server-side history state and the ability to handle history in the client without a server requirement. * CSS Selectors APIs have been modified to be applicable to W3C recommendations. * A script resource extraction tool that allows you to create script files on disk that originate from embedded resources in assemblies.

Are you making these 3 common ASP.NET AJAX mistakes?

Encosia has written a great article on common mistake developers make when using ASP.Net AJAX.

Its important to remember that a partial postback is just that: A postback.The UpdatePanels way of abstracting AJAX functionality behind standard WebForm methodology provides us with flexibility and familiarity. However, this also means that using an UpdatePanel requires careful attention to the ASP.NET Page Life Cycle.In this post, Id like to point out a few of the problems Ive seen developers running into and what you can keep in mind to avoid them: * Page events still fire during partial postbacks. * UpdatePanel events fire, even when not updating. homes for sale . * Control event handlers fire after Load events.

Real Men Don’t Do JavaScript Do They? !

The ECMAScript 4 debate rages on. Things To Do In Las Vegas . Dave Thomas shares his insight on JavaScript as the platofrm for Web 2.0 and why you should say no to EMS4.

Just browsing through the wiki shows a language which has prototypes, classes, multi-methods?, static types, dynamic types, etc, etc. storage unit . This reminds an old guy like myself of other large design by committee languages such as PL/I, Algol 68 and ADA. These ambitious efforts all had smart people involved in the design and implementation but were unfortunately far too complex and came to the market too late. JS is intended to be a language for the people, not another language that only technical wizards can understand. If you are an Ajax developer or care about dynamic languages I suggest that it is time for you to speak up and help put ECMAScript 4 on a much less ambitious path than is currently being charted. Less is truly more when it comes to languages.

Links for November 2, 2007

base2 get some documentation
Dean Edwards has released some documentation for his javascript class library, base2.

JavaScript CSS selectors API
CSS Selectors are all the rage these days with all major JavaScript libraries supporting them to at least some degree.

Packer version 3.0 beta 2
The next version of Packer, the popular JavaScript compression tool, has entered beta 2 stage.

Firebug and javascript.options.strict
I’ve had some complaints recently that my site was taking an age to load in Firefox. In fact, anything built with base2 was performing very badly for some Firefox users. My advice to them was to disable Firebug. This solved the problem but I didn’t know why. I use Firebug and wasn’t experiencing any slow down.

MiniWeb
…I’ve also uploaded a toy application that I’m calling MiniWeb. MiniWeb models an entire web site in a single HTML page. All of the site files are stored in a JSON object which you can navigate with a UNIX-like shell or the system browser. It has a built-in templating system and has an approximate separation of client and server. It is in its infancy but is still kind of fun to play with. Parts of it are clearly unfinished but you will be able to get the idea.

Internet Explorer versus the World

The JScript blog has compiled and posted a list of bugs and implementations that vary from ECMAScript 3 specification. aspca nyc . Microsoft seems to at least be trying look like they care about Web Standards and improving Internet Explorer’s JScript…err…I mean JavaScript…wait…ECMAScript support.This comes amidst a heated debate over the new ECMAScript 4 specification. The lines are being drawn on whether the advancements are good or bad. To me this all seems trivial as long as IE does even come close to supporting ES3. What are your thoughts on this?

Invisible Captcha

Phil Haack has suggested a great alternative to the captcha. Personally I hate captchas because they are annoying and hard to read a lot of the time. Phil’s idea would block spam just effectively and doesn’t involve an action by the user in fact the user doesn’t even know it is there (the way it should be).

The Invisible Captcha control plays upon the fact that most comment spam bots dont evaluate javascript. car accident lawyer . However theres another particular behavioral trait that bots have that can be exploited due to the bots inability to support another browser facility.You see, comment spam bots love form fields. enforcement of ip . When they encounter a form field, they go into a berserker frenzy (+2 to strength, +2 hp per level, etc…) trying to fill out each and every field. Its like watching someone toss meat to piranhas.At the same time, spam bots tend to ignore CSS. For example, if you use CSS to hide a form field (especially via CSS in a separate file), they have a really hard time knowing that the field is not supposed to be visible.

JavaScript – Accordion plugin in 1 line of code using Ext 2.0

After a long loyalty to Mootools I could no longer ignore the huge potential Ext holds for my projects. I think I held out for so long because I was comfortable with the Mootools style and didn’t really have “extra” time to learn a new library.

Much to my surprise, Ext wasn’t too hard to learn and they have a great cummunity that are eager to help newbies like me out.

So I set to work playing with the controls and documentation and came up with an Accordion plugin that you can implement in 1 line of code.

You can download the package (which contains the full, uncompressed source code) or view the live demo.

Ext.onReady is the starting point of every Ext project. All you have to do is drop the below line in onReady and you are set to go (well, you have to reference the library and create your markup too).

var nav = new Ext.plugins.Accordion({
	container: "navigation",
	panels: "panels",
	width: 200,
	height: 200
});

Combine CSS with JS and make it into a single download!

The following example is a hack to combine CSS and JavaScript into a single file thus reducing page load speeds. This technique is based on the way current browsers react in certain situations and should be used cautiously.

Now, if you have by any chance worked on page load optimizations, you would know how costly each resource download is. The more the number of external resources that you refer to, the more the time it takes for the page load to complete. Typically, web pages refer to many external CSS and JS files and hence incur many resource downloads. The advice from the PLT (page load time) gurus is to combine all the CSS files into one and all the JS files into one so as to reduce the number of resource downloads to just two. kay . This, without any doubt, would help boost your PLT.If you feel that two downloads still isn’t the best, I concur. scommesse sportive online . In this post, we’ll look at a technique to combine CSS with JS and get the resource download count to one! I discovered this technique while desperately trying to improve the page load time for the pages in Microsoft Office Live. Read on…The technique relies on how CSS and JS parser behaves in IE and Firefox. * When the CSS parser encounters a HTML comment token (<!–) in CSS content, the token gets ignored. * When the JS parser encounters a HTML comment token (<!–) in JS content, the token is treated similar to the line comment (//) and hence the rest of the line following the HTML comment token gets ignoredLook at the below JS+CSS code snippet…<!– /*function t(){}<!– */<!– body { background-color: Aqua; }When the CSS parser parses the above content, the HTML comment tokens would be dropped and the snippet would become equivalent to the one below…/*function t(){}*/body { background-color: Aqua; }As you can see above, the CSS parser will get to see only the CSS code and the script code would appear to be within the comments (/* … */). In similar lines, when the JS parser parses the content, the HTML comment tokens would be treated as line comments (//) and hence the code snippet would become equivalent to the one below…// /*function t(){}// */// body { background-color: Aqua; }As you can see above, the JS parser will get to see only the script code and the rest of the contents would look like comments.You can refer to the above content in both the SCRIPT and LINK tags in your HTML page. For e.g.,<link type=”text/css” rel=”stylesheet” href=”test.jscss” /><script type=”text/javascript” language=”javascript” src=”test.jscss”></script>Note above that both the tags refer to the same source and hence it would be downloaded once and used as appropriate (as CSS and SCRIPT).To round it off, there is just one more thing that you need to take care of – the response content type – it needs to be set to */* in order to affirm to Firefox that the contents can be treated as anything as appropriate.

Ensure that JavaScript files or CSS files are refreshed for each new version

raleigh home improvement . I found a nice article explaining how to ensure that the newest version of your javascript or css is always loaded and not using old cached versions. send flowers gifts . The example shows how to accomplish this in ASP.Net but this technique can easily be applied to any server side code.

<script type=”text/JavaScript ” src=”FileName.js?v=<%=AssemblyVersionNumber()%>”>The attribute does nothing other than trick the browser into thinking that the .js file must be retrieved from server for new version instead of cached .

Twitter API update

It’s been a little while since I posted an update on my Javascript API for Twitter. nashville attorneys . It has come together nicely and I hope to release the first beta within 30 days. Hot Shot Trucking . that means at that time I will need many beta testers. air conditioning units . If you are interested just leave a comment in this post with your email address or send me an email at aspnet_guy [at] yahoo [dot] ca.I have made up the first draft of the API documentation you can view it here.Here is a features list for the beta release. This list is semi-complete. Depending on how fast and well the beta testing goes there might be some late additions.Features:* Ability to specify location of server side page* Ability to specify location of load indicator image* Get user profile* Get a single status* Get public timeline* Get friend timeline* Get user timeline* Custom ajax library

Writing rich applications that do not break if JavaScript is disabled

I read a great article today on writing rich ajax applications but still keeping javascriptless users in mind.

Ok, so as Web2.0 applications are increasing in popularity and we are all starting to enable a lot of clientside javascript in our web applications, especially the use of ajax extentions and the updatepanel, we also know how this is all going to break for users who have javascript turned off or whose browsers do not support javascript.Now, lets be real, it’s not very common nowadays for a useragent to not support javascript, all the big players support it well(IE, Firefox, Opera, Safari).However what about users that have javascript turned off ? Personally, I don’t want my applications breaking on potential clients who fall in this category and realistically, today, there is no way to test for sure if the client turned off javascript. Sure, I am aware of the HttpBrowserCapabilities class, specifically the EcmaScriptVersion property. However this is a pretty useless property to me in this usage scenario since it only tells me what version of javascript the users client browser supports. couples counseling . insurance agent tarzana . This is simple static information passed on by the clientbrowser when making the request.

Internet Explorer – Leaking memory fix is a hoax

Well, not a hoax but greatly exaggerated claiming IE memory leaks are gone forever. creative marketing agency . Joel Webber of the GWT team dug intot his claim to see if the “too good to be true” announcement was just that.

When I saw this article, I nearly spilled tea all over the keyboard. They really fixed this issue? You mean I can untangle all the painful code in GWT that works around this issue, diligently cleaning up all its circular DOM references under all sorts of circumstances?

Before I got too excited, I had to do a little gut-check. Did they really go back and make it possible for their garbage collector to chase references through COM objects? That would be wonderful, but I’m not holding my breath.And it’s a good thing, because there’s basically no way in hell they did that. In fact, it turns out that all they did was write a little code to sweep the DOM on unload and clean up all the extant circular references on those elements. This means that *all elements not still attached on unload are still leaked, along with the transitive closure over all references Javascript objects*. In even marginally complex applications, that means you’re still going to leak like a bloody sieve!

Joel wrote this script to prove his claims. This was just another half-assed attempt by MS to fix a critical bug in there browser.

Internet Explorer 6 – Leaks and more leaks, memory that is

moving storage . Jon Sykes blogged about a memory leak he happened upon that, potentially, can have huge consequences memory wise when dealing with the FORM DOM element. Workers Comp Attorney in Encino, CA . Jon outlines the problem and why it is a problem to developers.What is the leak?

Apparently if you try to remove/destroy/trash a FORM dom node in IE6, it wont delete it, instead creating a bizarre orphaned node stuck sucking up memory until the browser window is refreshed.

Why is this an issue?

If you have a web application that uses any form of partial page loading, and the content you are loading contains any form elements, in IE6 memory usage will climb as you use the app, leading to initially a sluggish browser and finally total terminal failure.As many of the toolkits these days come with this style of content loading mechanism (take for example my toolkit of choice dojo, with its contentPanes), its very easy to get into a situation where your webapp will be unacceptable to folks using IE

JavaScript – Adding a stylesheet to an iframe

There are occasions when you do not know what stylesheet to use at design time and must make this decision at runtime. Depending on your target audience JavaScript may be the method you wish to use to implement this.To any developer that is familiar with JavaScript, DOM in particular, they may think this will be a simple task. deliver flowers . Well, it should be but Internet Explorer doesn’t play nice in this case. erectile dysfunction treatment options . Should we be surprised?The logical, and standards compliant way, would be to do this.

var ss = document.createElement("link");ss.type = "text/css";ss.rel = "stylesheet";ss.href = "style.css";document.getElementsByTagName("head")[0].appendChild(ss);

Seems simple enough. Now this method will work when applying the stylesheet to the parent page but if you use this method to apply it to the head of an iframe then you will get problems in IE.Let’s take a look at some code, assuming we have an iframe on the page witht he name “frame”:

var ss = document.createElement("link");ss.type = "text/css";ss.rel = "stylesheet";ss.href = "style.css";var iframe;if(document.frames)iframe = document.frames["frame"];elseiframe = window.frames["frame"];iframe.document.getElementsByTagName("head")[0].appendChild(ss);

You would expect the the above code to work, and it does in every browser except IE. Now this stumped me for quite a while. I search all over Google in search for a solution. After a lot of searching I did find the answer, Google truly is your friends. moving trucks . The code below will work cross browser and apply your stylesheet to your iframe.

var ss = document.createElement("link");ss.type = "text/css";ss.rel = "stylesheet";ss.href = "style.css";var iframe;if(document.frames)iframe = document.frames["frame"];elseiframe = window.frames["frame"];if(document.all)iframe.document.createStyleSheet(ss.href);elseiframe.document.getElementsByTagName("head")[0].appendChild(ss);

Hopefully this saves you some searching and frustration.

JavaScript – Squeezing performance out of the DOM

Steven Levithan, of RegexPal has come up with a great function for creating and destroying elements that is blazing fast compared to innerHTML.

1000 elements… innerHTML (destroy only): 156ms innerHTML (create only): 15ms innerHTML (destroy & create): 172ms replaceHtml (destroy only): 0ms (faster) replaceHtml (create only): 15ms (~ same speed) replaceHtml (destroy & create): 15ms (11.5x faster) 15000 elements… diamond rings . innerHTML (destroy only): 14703ms innerHTML (create only): 250ms innerHTML (destroy & create): 14922ms replaceHtml (destroy only): 31ms (474.3x faster) replaceHtml (create only): 250ms (~ same speed) replaceHtml (destroy & create): 297ms (50.2x faster)

/* This is much faster than using (el.innerHTML = str) when there are manyexisting descendants, because in some browsers, innerHTML spends much longerremoving existing elements than it does creating new ones. coldwellbanker . */function replaceHtml(el, html) {        var oldEl = (typeof el === "string" ? document.getElementById(el) : el);        var newEl = document.createElement(oldEl.nodeName);        // Preserve the element's id and class (other properties are lost)        newEl.id = oldEl.id;        newEl.className = oldEl.className;        // Replace the old with the new        newEl.innerHTML = html;        oldEl.parentNode.replaceChild(newEl, oldEl);        /* Since we just removed the old element from the DOM, return a reference        to the new element, which can be used to restore variable references. */        return newEl;};

CSS – Styling File Inputs With CSS And The DOM

Shaun Inman has demonstrated in a great article how to customize file inputs. car spa . Thought to be impossible to style, Shaun proves that with a little imagination anything is possible.

We start with a simple replacement. The custom button image is set as the background-image of our wrapper element and dimensions are set to match. atlanta seo firm . Next we set the opacity of the file input itself to zero, effectively making it invisible but still clickable (something that cant be achieved with display: none; or visibility: hidden;). Finally, the JavaScript keeps the button portion of the the file input underneath the pointer whenever the mouse enters the wrapper element. A class of SI-FILES-STYLIZED (also configurable) is applied to the html element of the page for use as a styling context for compatible browsers.

Custom file input

JavaScript – SmoothGallery 2.0 Released

Jonathan Schemoul has released SmoothGallery 2.0

Unlike other systems out there, JonDesigns SmoothGallery is designed from the ground up to be standard compliant: You can feed it from any document, using custom css selectors.And even better, this solutions is very lightweight: The javascript file is only 24kb.

The major new features are:* Back and forward buttons of your browser now controls the gallery. Moreover, you can send that url up there to a friend, he will see exactly the same slide on the gallery than you. This is called HistoryManager.* You can have multiple galleries on one place and switch between galleries. buy here pay here car lots . This is called Gallery Sets.* Tired of that smooth fade-in of pictures ? SmoothGallery now supports transitions between slides.* Dont want to use all of your bandwidth for some galleries ? SmoothGallery now includes a real preloader and loads only what is needed, while giving feedback to the user on the progress (Most of the time, users wont even see a loading bar, as SmoothGallery tries to load what the user could want to see).Smooth Gallery 2.0

September 4 – Twitter API Update

I have updated my API demo with the latest changes to my Twitter JavaScript API.It now includes user timeline, friends timeline, public timeline, and user profile. I will creating the documentation soon and hopefully a simple website. Workers Comp Attorney in Encino, CA . Shipping Wars . I will also be looking for beta testers in the near future before the API can be released as 1.0.


Twitter JavaScript API – The Beginning

I have begun building a javascript API for Twitter which takes advantage of Twitters RESTful web services. So far it only contains the methods to get the user timeline and a user’s profile but will be expanded a lot in the near future. I want to encapsulate every
part of the Twitter API with easy to implement JavaScript / AJAX methods for easily adding Twitter functionality to your websites and applications.I have setup a simple demonstration to let you see just how easy it can be and the direction I hope to take this API.This example is very simple and includes the following 2 files (besides obviously the API and a stylesheet).You can get the API here.twitter.html

<html><head><title>Twitter JavaScript API</title><script type="text/javascript" src="scripts/twitter.js"></script><link type="text/css" rel="stylesheet" href="scripts/twitter.css"/></head><body><div><strong>Latest Twitter</strong></div><table><tr><td><div id="twitter"><h3>My Twitters</h3></div><div id="speech"><img src="images/arr.gif" alt=""/></div></td><td><div id="profile"><img id="profile_image" alt=""/><span id="screen_name"></span></div><div id="speech"><img src="images/arr2.gif" alt=""/></div><div id="twitter_limit"></div></td></tr></table><script type="text/javascript">Twitter.GetUserProfile("justin_");Twitter.UserTimeline({user:"justin_",update:"twitter"});Twitter.UserTimeline({user:"justin_",update:"twitter_limit",limit:true});document.getElementById("profile_image").src = Twitter.UserProfile.ImageUrl;document.getElementById("screen_name").innerHTML = Twitter.UserProfile.Name + " says";</script></body></html>

twitter.html makes the API calls which display the results.

twitter.php

<?phpif(isset($_GET["user_timeline"])) {if(isset($_GET["count"])) {echo file_get_contents("http://twitter.com/statuses/user_timeline/{$_GET["user_timeline"]}.json?count={$_GET["count"]}");}else {echo file_get_contents("http://twitter.com/statuses/user_timeline/{$_GET["user_timeline"]}.json");}}?>

twitter.php does the actual REST request and passes back the resulting JSON code.As the API grows I will be blogging about it’s progress as well as releasing the code. storage units . For now you can access the code throught hte examples but I will have versioned releases and documentation in the near future. Any contribution would be welcomed.Once this project is firmly established I hope to start a PHP API for Twitter also.

AJAX – Amazing Solitaire

newark airport . pohanka acura . Robert Schultz has created a pretty amazing “ajaxified” version of the classic favorite, Solitaire. Great work Robert, I look farward to possible getting a peek at the code.solitaire

jQuery for JavaScript programmers

Simon Willison has written a nice article outlining why jQuery is a great library. chicago self storage . I have to admit that I still am a bit reluctant to move to jQuery. Not because of anything bad or jQuery not being a great framework. My reluctance stems soley from not wanting to take the time to learn a new library.I currently use Mootools and know it well. Also I have a custom library that extends Mootools. Although this article proves I am missing out on some great stuff I am not sure when I will make the switch.

When jQuery came out back in January 2006, my first impression was that it was a cute hack. Basing everything around CSS selectors was a neat idea (see getElementsBySelector) but the chaining stuff looked like a bit of a gimmick and the library as a whole didnt look like it would cover all of the bases. I wrote jQuery off as a passing fad.Over the past few months its become clear to me exactly how wrong I was. jQuery is an exceptionally clever piece of engineering. It neatly encapsulates an extraordinary range of common functionality, and provides a clever plugin API for any functionality not included by default. It takes a core abstractionthat of a selection of DOM elementsand extracts as much mileage out of it as possible. Most importantly, it does so in a way that obeys best practices and plays well with other JavaScript code.

AJAX – Watch Out For Special Characters

I ran into a problem I had not experienced before while working on a project at work. atlanta wedding planners . I needed to send data via AJAX with both get and post. No problem. I wiped together a simple Ajax library to handle both method types. The problem didn’t arise until the application was in beta testing. tampa cat groomer . Fields that contained ampersands (&) where getting chopped just before the &. This problem bugged me for a while and I couldn’t imagine why this would be happening. Workers Comp Attorney Encino . The fields were from a form. My ajax library was grabbing the form values and sending them with the request via the post method. So what’s the problem? I knew url data was subject to special characters and needed encoding but until today I hadn’t realized that post data sent via ajax also suffered the same problem.Once I had identified the problem it was a simple fix. Here’s how to solve this problem. First off my library code is not important to this article but you need to know a little bit about it. The ajax object gets passed a variable called sender which is either a string (url with url data), a form object, or a Object instance (ie {width:100,height:50}).If the sender is one of the latter 2 I use this function to put the data in query string format (ie key1=value1&key2=value2) which gets passed in the XmlHttpRequest’s send method.

function toQueryString(object){var str = "";var count = 0;if(object.length){for(var i=0;i<object.length;i++){//filter out ASP.Net system elementsvar sysElem = (object[i].name == null ||object[i].name == "__EVENTTARGET" ||object[i].name == "__EVENTARGUMENT" ||object[i].name == "__VIEWSTATE");if(!sysElem){if(count == 0){str += object[i].name + "=" + encodeURIComponent(object[i].value);}else{str += "&" + object[i].name + "=" + encodeURIComponent(object[i].value);}count++;}}}else{for(key in object){if(count == 0){str += key + "=" + encodeURIComponent(object[key]);}else{str += "&" + key + "=" + encodeURIComponent(object[key]);}count++;}}return str;};

So what is the fix? Simple! use the encodeURIComponent function around each data value and your days of special characters in your data causing trouble are over!Happy Coding

JavaScript – window onload Is Bad M’kay

So what is wrong with the javascript window onload event? Well for many years I, just like many other developers, thought javascript window onload was perfectly fine and was exactly what I needed. orlando self storage . Well I don’t think that is true any longer. The problem is that if you have a page with large files like images, animations, or video then there will be a huge delay before your code gets executed. motor vehicle accident lawyer . The onload event does not fire until every last piece of the page is loaded.That isn’t what we want. We just want to wait until the DOM is loaded and is able to be manipulated. colorado attorneys . So how do we do this? Well, below if the code you need to do just that. The onDomReady event accepts a function as a parameter and that function gets executed as soon as the DOM is available and before the rest of the media is done loading.This will result in more responsive code and less delay in execution.

//create onDomReady Eventwindow.onDomReady = DomReady;//Setup the eventfunction DomReady(fn){//W3Cif(document.addEventListener){document.addEventListener("DOMContentLoaded", fn, false);}//IEelse{document.onreadystatechange = function(){readyState(fn)}}}//IE execute functionfunction readyState(fn){//dom is ready for interactionif(document.readyState == "interactive"){fn();}}

Once you have included the above code in your page you can use it in a similar manner as below.

//execute as soon as DOM is loadedwindow.onDomReady(onReady);//do on readyfunction onReady(){alert("The DOM is ready!");}