Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Friday, May 14, 2010

Repeating and aligning elements using jQuery and CSS

Today I had a need to create a dynamic list of checkboxes, and I wanted them all aligned properly, so the results would look something like this:

image

The layout was simple with CSS, then I added some jQuery to simulate getting the checkbox items dynamically.

Example:


That example produces a list that adjusts appropriately when resized:

image image

Friday, April 11, 2008

How To: Hide a Button When Clicked on an ASP.NET Page Containing Validation Controls

Suppose you have a form with some ASP.NET validation controls on it, and you want to prevent users from clicking the form's submit button more than once.

image

It might sound easy at first. Just add some javascript to the asp:Button's OnClientClick to hide the button and show your custom message:

<script language="javascript" type="text/javascript">
function DisableButton(button)
{
button.style.display
= 'none';
document.getElementById(
'loading').style.display = 'inline';
}
</script>
<asp:Button ID="LoginButton" runat="server" Text="Login" OnClientClick="DisableButton(this)" />
<span id="loading" style="display: none;">Logging in...</span>

Except if you do that, and you're using ASP.NET validation controls on the page, your user could end up in a situation like this:

image

Now your user is stuck because the Login button is gone!

So, this is how to get around that:

<script language="javascript" type="text/javascript">
function DisableButton(button)
{
Page_ClientValidate();
if (Page_IsValid)
{
button.style.display
= 'none';
document.getElementById(
'loading').style.display = 'inline';
}
}
</script>

In the script above, you'll notice I'm using a Page_ClientValidate() method and a Page_IsValid boolean variable. Those are exposed as part of ASP.NET's Client-Side Validation API.

What's happening:

  1. Page_ClientValidate() forces the validation to happen immediately.
  2. If the validation tests pass (Page_IsValid), hide the button, show the message, and submit the page.
    image
  3. If the validation tests fail, ASP.NET will handle showing the validation errors for you, and the page will not be submitted.
    image

For more information on ASP.NET Validation, see this article on MSDN:
http://msdn2.microsoft.com/en-us/library/aa479045.aspx

Friday, April 4, 2008

Javascript: More than meets the eye...

I recently ran across a presentation on InfoQ by Glenn Vanderburg called "The Power of Javascript" that was recorded at JAOO.

Summary
Glenn Vanderburg makes the case for Javascript, a language long overlooked. This presentation from JAOO 2007 shows how its OOP model and other language features make it a very powerful tool and how to use these features to get the most out of the language.

The presentation describes how Javascript got its name - starting out as LiveScript developed by Netscape and later rebranded as Javascript to exploit the popularity of the new kid on the block - Java, developed by Sun. He explains why it is commonly considered to be a "toy language" and why it isn't.

A while ago I posted the first in a series of articles about javascript. Since then I've been somewhat stingy in releasing the other proposed articles.  I'll try to get back into the swing of things promptly.

Wednesday, July 25, 2007

Object Oriented? You can't even define classes, can you?

For some reason, unlike other modern languages, the ability to define custom types seems to be a Javascript language feature that is often passed over. Only advanced Javascripters seem to ever get around to learning about this underused feature. Defining a new type in Javascript is easy; you just have to get used to the syntax and understand that in Javascript, everything is an object; Functions are Objects, too.

   1: function Person(fname, lname)
   2: {
   3:     this._fname = fname;
   4:     this._lname = lname;
   5: }
   6: var dave = new Person("Dave", "Haynes");

The code above defines a function called Person which takes two parameters; notice how it assigns the value of the parameters to a pair of expando properties on this. What is this?

First, notice the new keyword used in the assignment to dave. The new keyword basically calls the function in the context of a new object of type Person - this refers to that new object within the scope of the function. The function then adds new expando properties to this object, then the object is assigned to dave. You can consider the Person function to be both the constructor for and the definition of the Person type. Without the new keyword, the expando properties would be added to the global scope and dave would be assigned the return value of the traditional function call. Since the function doesn't have a return statement, it implicitly returns null.


Remember earlier when I said "Functions are Objects, too"? Let's expand the sample a bit...



   1: function Person(fname, lname)
   2: {
   3:     this._fname = fname;
   4:     this._lname = lname;
   5:     
   6:     this.GetFullName = function(){
   7:         return this._fname + " " + this._lname;
   8:     }
   9: }
  10: var dave = new Person("Dave", "Haynes");
  11: alert(dave.GetFullName());

Now we have added a new expando property called GetFullName, but this time it is assigned a function that takes no formal parameters. This demonstrates that a function is an object just like everything else in Javascript. It can be passed around to other functions, stored in variables, garbage collected, etc.

Wednesday, April 25, 2007

Garbage Collection? That's gross!

"Garbage Collection" probably sounds like a strange term if you've never heard of it before. So what is it? Well, you've all probably heard of a "memory leak" before. Garbage Collection, or GC, is essentially an attempt to prevent memory leaks. Back in the old days, developers had to be very diligent about cleaning up after themselves. If an object was allocated repeatedly but never "destroyed" or cleaned up the system would gradually use more and more memory until there was no more available memory and the application would crash.

Today, platforms like Java, .Net, Javascript, Perl, Ruby, and PHP have GC built-in. In platforms with GC, objects that are no longer referenced (because the reference has gone out of scope or because the variable was set to null) become eligible to be automatically destroyed and the memory used made available for new allocations. Notice that i said they become eligible; the objects are not immediately cleaned up when they go out of scope. The garbage collector only performs the collection when it is necessary, such as when the system is running low on memory.

Javascript has the ability to be garbage collected or to use explicit memory management when necessary or desired with the delete keyword. The two graphs below show the difference.

The first graph shows memory consumption over time while the garbage collector is allowed to manage the memory.

The second graph shows the same thing while the program manages it's own memory by explicitly deleting the objects when it is done with them.

   1: <%@ Page Language="C#" AutoEventWireup="true" Codebehind="Default.aspx.cs" Inherits="ItsJustJavascript._Default" %>
   2:  
   3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4: <html xmlns="http://www.w3.org/1999/xhtml">
   5: <head id="Head1" runat="server">
   6:     <title>Untitled Page</title>
   7: </head>
   8: <body>
   9:     <form id="form1" runat="server">
  10:         <div>
  11:             <button onclick="cancel = false; useMemory(false);">
  12:                 start (normal)</button>
  13:             <button onclick="cancel = false; useMemory(true);">
  14:                 start (self cleanup)</button>
  15:             <button onclick="cancel = true;">
  16:                 stop</button>
  17:             <br />
  18:             <input type="text" id="output" />
  19:         </div>
  20:     </form>
  21:     <script type="text/javascript">
   1:  
   2:     var cancel = false;
   3:     var output = document.getElementById("output");    
   4:     
   5:     function useMemory(selfCleanUp)
   6:     {
   7:         if (cancel) return;
   8:         
   9:         output.value = (new Date()).toString();
  10:         for (var i = 0; i<100000; i++)
  11:         {
  12:             var foo = new Object(); //just consume a small amount of memory
  13:             foo.bar = new Object(); // and a bit more memory, plus an expando!
  14:             if (selfCleanUp)
  15:             {
  16:                 foo.bar = null;
  17:                 delete foo.bar;
  18:                 foo = null;
  19:                 delete foo;
  20:             }
  21:         }
  22:         
  23:         window.setTimeout("useMemory(" + selfCleanUp + ")", 1);
  24:     }
  25:     
</script>
  22: </body>
  23: </html>

Additional Info:

Monday, April 23, 2007

Presto Expando

It's hard to know where to start, but you've got to start somewhere, right?

JavaScript is a very dynamic language. That basically means that objects can be created and modified at runtime. It is also very loosely-typed which means that you can treat a string variable as an integer or an integer as a date, or a date as a string, or... well, you get the point.

So what do I mean by "objects can be created and modified at runtime"? In static languages, the members (attributes, properties, methods, etc.) and behaviors of a type are explicitly defined at design-time and then compiled. After compilation you cannot add or remove any of the members. I suppose you've already guessed what i'm going to say next. In dynamic languages (depending on the degree of dynamicism), any member can be added, removed, or replaced at runtime. In Javascript, members you add at runtime are commonly called "expando properties".

   1: var someObject = new Object();
   2:  
   3: //calls builtin toString method
   4: alert(someObject.toString());
   5:  
   6: // adding an attribute
   7: someObject.myExpando = "hello expando";
   8:  
   9: // replaces builtin toString method
  10: someObject.toString = function()
  11: {
  12:     return this.myExpando;
  13: }
  14:  
  15: // notice how the toString method has been replaced
  16: alert(someObject.toString());
  17:  
  18: // adding a new method to the new object
  19: someObject.tellTime = function()
  20: {
  21:     alert(new Date());
  22: }
  23:  
  24: someObject.tellTime();
  25:  
  26: //removing the method we just added
  27: delete someObject.tellTime;
  28:  
  29: //calling the method now will be an error
  30: try
  31: {
  32:     someObject.tellTime();
  33: }
  34: catch(e)
  35: {
  36:     alert(e.message);
  37: }

Additional Info:

Friday, April 20, 2007

It's just Javascript, right?

Recently I realized that most developers I've known (and therefore, probably most developers in the world) think of Javascript as just:

  • a bunch of variables,
  • inline code in an onClick attribute, and
  • global methods on a webpage.

How many of you are saying "yeah, what else is there?"; raise your hands...

I'll discuss the language in more detail in a series that will start out simple and then build upon itself. Hopefully each episode will leave you dying to find out what happens next - like an episode of Lost or 24. Some of the episodes will be called:

  1. Presto Expando
  2. Garbage Collection? That's gross!
  3. Boolean. Not the meat cubes; and not the gold bricks.
  4. Object Oriented? You can't even define classes, can you?
  5. Prototype? But hasn't Javascript been around for a while now?
  6. Functional? Of course it is, I mean, I've seen it work.
  7. What's in the Dictionary?
  8. Who is this J[a]SON i've been hearing about?
  9. The library formerly known as "Atlas"