Google Closure and How to Create a Batch File for Running ClojureBuilder

Learn how to create a batch file on Windows to use the Google Closure compiler.

Hoping this will save someone time in the future; whether the future is bright and shiny… or robotic apocalypse. One of the relatively few issues I’ve had with Google Closure was moving from calcdeps (I think that’s what it was called) to ClosureBuilder was setting up a batch file to run it. With calcdeps, it was mostly just naming a bunch of folders, and it did the rest. When I moved to ClosureBuilder, it wasn’t that easy. At first I panicked, and promptly jumped through a second story window, then I decided getting used to the new compiler is healthier in the long run. Turns out that even if ClosureBuilder expects actual namespaces to include, it’s better in the end as it makes it much easier to include/uninclude a particular namespace incase there’s a need to pick and choose. Here’s an example of the batch file I created to compile a “live” (Not test”) version:

python c:/lib/closure/closure-library/closure/bin/closurebuilder.py ^
//Optional if you are running the 32 bit version of jvm/jre
--jvm_flags="-d32" ^
//This is where all the closure files exist
--root="c:/lib/closure/closure-library/" ^
//This is the folder in the project that has all the JavaScript files.
--root="content/script/live/" ^
//Here are the namespaces in that JavaScript folder that I want to include
--namespace="src.base.helper.arrayHelper" ^
--namespace="src.base.helper.constants" ^
--namespace="src.base.helper.domCreation" ^
--namespace="src.base.helper.domHelper" ^
--namespace="src.base.helper.events" ^
--namespace="src.base.control.gridBuilder" ^
--namespace="src.base.control.pager" ^
--namespace="src.site.view.mainContent" ^
--namespace="src.site.view.mother" ^
--namespace="src.site.view.tableOfContents" ^
--output_mode=compiled ^
--compiler_jar="c:/lib/closure/compiler.jar" ^
//This is optional if you want the super duper minimized version on compile.
//  I typically don't use the simple version, because I had found issues where
//   it works with simple, but not advanced.
--compiler_flags="--compilation_level=ADVANCED_OPTIMIZATIONS" ^
//This is where you want to save the compiled result.  I've found that it is easier
//  put the batch file in the web root, and have it use a relative path rather than
//  having to give it a drive path like c:\web\something\somethingElse\content...
--compiler_flags="--generate_exports" > "content/script/live/final.js"
//I keep this here for when I have to be on a computer with the 32 bit version of 
//  jrm/jvm.
rem --jvm_flags="-d32" ^

As you can see, it’s actually not all that complicated.

Google Closure: An Enter Key Press

How to set up an event handler for when the enter key is pressed withing the Google Closure system.

Real quick thing which was getting the enter key to be handled on press in an input/textbox… though probably other things.

goog.events.listen(element, goog.events.EventType.KEYPRESS, function(a) {
  if(a.keycode === 13) {
    doSomething();
  }
});

This assumes that 13 is the universal id for the enter key. Not sure if there is a case of browser dependent key codes.

JavaScript DSL Because I’m Tired of Writing If.. If…If…

A little while ago a co-worker had expressed a dream of his to create some kind of language agnostic standard for validation. Without actually listening to what he meant by that, I set forth on doing this for JavaScript. I wanted to Lisp it up, as I am that kind of zealot. The idea was simple, provide a list like structure for describing the validation needs, but not make it a complete cluster *($#. I got the first part, not sure about the second. Essentially I wanted something like this:

 var rules =
    ('Username',
      ('is not empty' 'Username is required.')
      ('is not longer than' 7 'Username is too long.'))

Where ‘Username’ is the name of the property needing the validation, and the ‘7’ is the maximum length, and the last part is the error. But, seeing as this was JavaScript, I had to do something a little more rigid.

Now for what the rules would look like:

 var rules =
    ['Username',
      ['is not empty', 'Username is required.'],
      ['is not longer than', 7, 'Username is too long.']],
    ['Name',
      ['is not empty', 'Name is required.']],
    ['Password',
      ['length is between', 4, 6, 'Password is not acceptable.']]];

As you can see, the rules turn out to be very readable. On top of that, since it is only a list, converting a json based array to the rules should be pretty easy. The advantage of that would be the ability for a server response to contain the rules at which time the interpreter would match them to the methods. Thus providing a way to help with consistency of error messages, and constant values like in the password rule above. Something that is a pain in the #@@ some… all of the time.

The structure is fairly simple. [Property name [[validation need][extra parameters][error]…..[validation need][extra parameters][error]]] Essentially every property that is going to be validated can have n number of validation methods “attached” to it. Now one catch is that the object being validated has to have a matching “Property name”. Kind of falls into the “opinionated programming” side of things.

For this example, there will be three fairly generic validation methods. The methods either return null, or an error message. Over simplistic much?

 function isNotEmpty(toCheck, propertyName, error, rest) {
    return toCheck[propertyName] === '' ? error : null;
  };

  function isNotLongerThan(toCheck, propertyName, error, rest) {
    return toCheck[propertyName].length > rest[0] ? error : null;
  };

  function isBetween(toCheck, propertyName, error, rest) {
    var length = toCheck[propertyName].length;
    return (length < rest[0] || length > rest[1]) ? error : null;
  };

And here is an example of how to attach the english to methods:

 var methods = [
    ['is not empty', isNotEmpty],
    ['is not longer than', isNotLongerThan],
    ['length is between', isBetween]];

I created a pseudo method look up table to match a much more “english” name for the validation method needed. Not exactly brilliant, and is sort of cheating. What would be nice is to actually read the english, break it down, and create the functions on the fly. BUT this works for now. That whole english breakdown I’ll attack at some point. After all, this was a sort of thought experiment.

The interpreter takes in the rules, matches the method, and send the extra values if needed. For example,

   ['length is between', 4, 6, 'Password is not acceptable.']

Is matched to:

  isBetween(toCheck, propertyName, error, rest)

Where “rest” is the 4 and 6. Rest is a carryover from Commmon Lisp’s &rest. It’s a collection of things that will be broken down by the validation method. Just think of them as optional values.

 var length = toCheck[propertyName].length;
  return (length < rest[0] || length > rest[1]) ? error : null;

There are two parts to the interpreter, but the first part is merely rolling through the rules, and making a call to this:

  src.site.validation.validationInterpreter.createAValidationCall = function(propertyName, methods, innerRule, find, car, cdr, peek, sink) {

 //Find the method that matches the english phrase
    var methodPair = find(methods, function(method) {
        return car(method) === car(innerRule);
    });

 //In Closure the find method returns the whole matched "row", so I need the method which is the second column.
    var methodToUse = peek(methodPair);

    return function(obj) {
        var error = peek(innerRule);                           //error is the last index
        var values = sink(cdr(innerRule));                     //get everything but the error  
        return methodToUse(obj, propertyName, error, values);  //construct the validation call
    };
};

car, cdr, sink, peek? The *(&^ are those? First two are carry overs from Common Lisp too. Car is just taking the first item of a list, if there is one.

  (car '(1 2 3)) ;;  1

Cdr returns a new list that is everything but the first item.

  (cdr '(1 2 3)) ;; '(2 3)

Haskell refers to them as Head and Tail. Clojure has First, and Rest. ect. ect. ect.

sink is used to get all but the last item in the list. Everything but the kitchen sink. Eh? Eh? Sigh. (The code for them can be seen here.).

peek is actually just a parameter cover for the goog.array.peek method. It gets the last element of an array. Remember, the structure is very specific. [validation need][extra parameters][error] Because of this, it’s easy to break down each rule into its respective parts using simple array manipulation.

Now at this point I only have created the method list creator (“Interpreter”), and haven’t created anything for running the validation. However, the code below is a rough estimate of how that would work.

 var result = interpret(rules, methods);

 var toValidate = {'Username': '12345678', 'Name': '', 'Password': '123'};
  for(var i = 0; i < result.length; i++) { something.innerText += '\n' + result[i](toValidate); };

The glaring issue with that is that I’m not removing empty strings. Other than that, it works. The working example is in the example folder for this repository. The removal would be nothing more than using a map -> filter type method chain.

 var validationMesssages = goog.array.map(result, function(item) { return item(toValidate); };
  return goog.array.filter(validationMesssages, function(message) { return !goog.string.isEmptySafe(message); });

Or something like that… probably not exactly like that unless you’re in with the Closure, or are stuck with Jsomethingry.

Coffeescript versus Javascript example for FUN

Coffeescript:

window.someList = [1, 2, 3, 4, 5]

addOne = (item) ->
  1 + item

window.runThings = () ->
  addOne item for item in someList

Coffeescript compiled to JavaScript:

(function() {
  var addOne;
  window.someList = [1, 2, 3, 4, 5];
  addOne = function(item) {
    return 1 + item;
  };
  window.runThings = function() {
    var item, _i, _len, _results;
    _results = [];
    for (_i = 0, _len = someList.length; _i < _len; _i++) {
      item = someList[_i];
      _results.push(addOne(item));
    }
    return _results;
  };
}).call(this);

jQuery Validator: Build Rules and Messages Dynamically

Ok so here’s your typical code for the jQuery Validator:

  jQuery(ELEMENT_FORM).validate({
    errorLabelContainer: ELEMENT_ERROR_DIV,
    wrapper: 'div',
    rules: {
      textboxEmailAddress: {
        required: true,
        email: true
      }
    },
    messages: {
      textboxEmailAddress: {
        required: ERROR_EMAIL_ADDRESS_REQUIRED
      }
    },
    ....

As you can see, the elements like “textboxEmailAddress” are hard coded in there which means if that name changes in the markup, this breaks. So the question is: How do I script the rules and messages so that I don’t have to hard code the element names?

Sorry was just waiting for you to finish you question. Ok, here’s the answer and it has to do with how great Javascript is as a language. (And oddly enough a trick I got from Python)

  var validationRules = new Object();
  validationRules[ELEMENT_TEXTBOX_EMAIL] = {required:true};

  var validationMessages = new Object();
  validationMessages[ELEMENT_TEXTBOX_EMAIL] = {required:ERROR_EMAIL_REQUIRED};

  jQuery(ELEMENT_FORM).validate({
            errorLabelContainer: ELEMENT_ERROR_DIV,
            wrapper: 'div',
            rules: validationRules,
            messages: validationMessages,
            ....

Where ELEMENT_TEXTBOX_EMAIL is a constant somewhere. How does this work? Well because the way dynamic languages like Javascript and Python work, objects can be treated like dictionaries which means you can add properties to them the way you would add a record to a dictionary:

  someObject['somePropertyName'] = 'hi';

is just like:

  someObject.somePropertyName = 'hi';

In fact I’m pretty sure the new Dynamic keyword in C# works in the same manor.

Now you could be a annoying and point out that replacing textboxEmailAddress with ELEMENT_TEXTBOX_EMAIL is still hard coding, and I would agree… to a point. The constant does two things:

1) Removes a “magic string” from your code.

2) Makes it really easy to update that string if the element name/id is changed in the HTML. Having only to look at one place to replace is a lot easier than 1+ places.

So there, smarty pants. What you gots to say now?

Child IFrame Page Interacting with Parent Page… Yeah I went there.

Example here.

File this under “Why?” but I wanted to see if a child could talk to a parent and then receive information back from the parent to update itself with. As usual, my lack of intelligent wording probably has you scratching your head… if you do that. Personally I don’t get that expression as when I’m confused I more than likely will grab a jar of peanut butter and start lathering up with it, but to each his own.

So here’s the idea, and this post is only the start.

You have a parent page, Parent.htm, with an iframe and you want the parent to do something and alert the child that something happened. For now, it’s actually really simple.

On the parent I have a method:

  function callMethod(text, methodDelgate) {
    if (methodDelgate != null) {
      methodDelgate(text);
    }
  }

And this simple markup:

  <iframe id="myFrame" src="Child.htm"></iframe>

Wow huh? Well on the child I have this:

  function callParent(text) {
    if (top.callMethod != null) {
	  top.callMethod(text, changeText);
    }
  }

This is easy. If the parent has the method, send the text through and a method to call when finished. What is this method? Well its:

  function changeText(text) {
    jQuery('#returnText').text(text);
  }

Which simply sets the text on some div to show it actually worked.

What happens when I click a button that calls callParent? It talks to the parent, the parent calls the passed in method, and the child updates itself.

Not sure this is rocket science, but there will be more on it as I add in the idea of a dynamically created pop up on the parent being used by the child. Until then, try not to be yourself. You embarrass your mother.

jQuery Validation – How to Use to Get Rid Of Even The Toughest Stains

So you want to use jQuery validation, huh?

What is it? Something that was added to the holy jquery site and is an easy way to validate input from users. Now this should in no way take over for server side validation, but it helps to at least catch a few things without having to send anything to the server. So how do ya do it?

Well to start, you need some files:

jquery-1.3.2.js and jquery.validate.js.

Now oddly enough the validation file isn’t hosted on the holy jquery site but how to use it is.

Ok now you have the files, what’s next? Well you need form, and I can do that for you.

So basically it’s a simple form with one input that is required.

jQuery(document).ready
    (
      function()
      {
        jQuery("#PrimaryForm").validate
        (
          {
            errorLabelContainer: "#ErrorDiv",
            wrapper: "div",
            rules:
            {
              FirstName :
              {
                required : true
              }
            },
            messages:
            {
              FirstName:
              {
                required : 'First Name is required.'
              }
            },
            onfocusout : false,
            onkeyup: false,
            submitHandler: function(label)
            {
              postSubmit();
            }
          }
        );
      }
jQuery("#PrimaryForm").validate

Real simple, just setting the validator to the primary form on the page.

 errorLabelContainer: "#ErrorDiv",

This sets the errors to show up in the ErrorDiv. Now this is optional, as you can have it show the errors next to the FirstName text box but personally I think that looks horrible. Setting up the ErrorDiv puts all the errors in one central location and allows for styling the actual div.

 rules:
 {
    FirstName :
    {
      required : true
    }
  },

This matches an element with the id of FirstName to the required rule, meaning that FirstName is required. Rocket science.

  messages:
  {
    FirstName:
    {
       required : 'First Name is required.'
    }
  },

If you can’t figure this out, I hear circus is hiring for the “World’s Dumbest Person”. You’ll fit in with Jub Jub the Dog Boy.

  onfocusout : false,
  onkeyup: false,

Basically this prevents the validation when leaving the textbox or on every key press. This is just another preference.

  submitHandler: function(label)
  {
    postSubmit();
  }

If the submit is successful, call this method.

But… BUT WHAT IF IT’S AN EMAIL?!??! WHAT WILL I DO???!?!?

Well for one, stop being such a child. And two, look here.

Some what different, as you can see it’s now email and there is one extra requirement in the rules:

  rules:
  {
    EmailAddress :
    {
      email : true,
      required : true
    }
  },
  messages:
  {
    EmailAddress:
    {
      required : 'Yo, email fool.',
      email : 'So not an email address.'
    },
  },

See? It has nice built in rule for email. Simple.

BUT WHAT IF I NEED A REGULAR EXPRESSION?!??! WHAT WILL I DO???!?!?

I swear if you don’t stop that, I’m turning this post around and going home.

Fine here it is.

  jQuery.validator.addMethod
  (
    "isZipCode",
    function(value, element)
    {
      return value.match(new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/));
    }
  );

Just have to create a method and “add it” to the validator itself. And then there’s the use:

  rules:
  {
    ZipCode :
    {
      required : true,
      isZipCode : true
    }
  },
  messages:
  {
    ZipCode:
    {
      required : 'For the love of me, enter a zip code!.',
      isZipCode : 'Serioulsy?  Do you know what a zip code is?'
    },
  },

Woo hoo right?

Don’t do it… Don’t you yell.

But what if one input depends on another?

Much better. Well that’s not as hard as it may seem and here’s the example.

  rules:
  {
    InputB :
    {
      required :
      {
        depends : function(element) { return jQuery('#InputA').val() != "" }
      }
    }
  },

As you can see, you can change how the required method works by adding in a depends handler. Works out pretty well.

Yes I will show you how to make sure two inputs match. I swear you ask for a lot.

  rules:
  {
    Password :
    {
      equalTo : "#ConfirmPassword"
    },
  },

Couldn’t be easier unless I wrote it out for you. Wait, I did.

So here you’ve either learned a bit about jQuery validation or have just spent the last few minutes drooling uncontrollably. Either way, I’m done with this post and you’re left to do whatever it is you do, you sick f—.

Side note: I haven’t actually been to Htmlgoodies since eh college? but wow did that place sell out. How fitting that an introduction to html page now looks like it was designed by someone just starting out… in the 90s.

jQuery: Add a Pop Up Div to a Link Dynamically

So as an exercise to learn more about jQuery, I decided to redo this little gem using jQuery. Have to say though only technically XHTML compliant, it worked out much better and with less code. So the idea is to have something really easy for non programmers (You know, lesser people) to be able to have a pop up comment added to some chunk of text on a web site. What I came up with before was ok but kind of annoying since it looked like this:

<a onclick="return ShowCommentForPost('1', this, 'THIS IS SO STUPID!');" href="www.byatool.com">word.</a>

Kind of annoying since I would have to explain that ‘1’ is the name and it has to be unique for every one of these, this isn’t really understood by those people, and well it just seems more complicated then it needs to be. So what if I told you it could look like this?

<a href="http://www.byatool.com" class="showItLink" xmlns:comment="hihihi">HI</a>

Gorsh, that seems even better and it works in both IE and Firefox… which might be a first for this site and anything javascript. First let’s get the css out of the way, shall we?

    .showItLink
    {
    }

    .postComment
    {
        background-color:Gray;
        border-color:Black;
        border-style:dotted;
        border-width:thin;
        color:White;
        margin-right:3px;
        padding:3px;
        position:absolute;
        text-decoration:none;
        z-index:50;
    }

Most of the is just for looks, but like the older example I’ve called upon the power of position:absolute and z-index well that’s just pulling it in front of everything else.

Next part will be the actual code, and if you take the method from THE POSITION ABSOLUTE POST

    function SetTopAndLeft(parentContainer, elementToSet)
    {
        var containerPosition;

        containerPosition = $(parentContainer).position();
        $(elementToSet).css({ top: containerPosition.top + 10, left: containerPosition.left + 10 });
    }

and add in a simple span creation method:

    function CreateDiv(innerText, cssClass)
    {
        var spanToAdd;

        spanToAdd = document.createElement('span');
        spanToAdd.className = cssClass;
        spanToAdd.innerHTML = innerText;

        return spanToAdd;
    }

you’re ready for the actual fun part… making sure something pops up when the link is clicked.

jQuery(document).ready  //Everything inside this will load as soon as the DOM is loaded and before the page contents are loaded.*
(
    function()  //this is the start of an anonymous method
    {
        jQuery(".showItLink").click //find all things with the .showItLink class and assign the click event to the next anonymous method
        (
            function(event) //this is the start of an anonymous method for the click event
            {
                var containerPosition;
                var createdSpan;
                var comment;

                comment = jQuery(this).attr("xmlns:comment");  //Get the value from the comment attribute on the link.
                createdSpan = jQuery(this).children(".postComment"); //Find a possible span already attached to the link if it exists.  The span is of class 'postComment'

                if (createdSpan.length == 0)  //span doesn't exist
                {
                    createdSpan= CreateDiv(comment, "postComment");  //create the span
                    jQuery(this).append(createdSpan);  //Add the span to the link
                    jQuery(this).children(".postComment").hide();  //Make sure the new span is hidden
                }
                SetTopAndLeft(this, createdSpan);  //Set the position of the span
                jQuery(createdDiv).toggle();  //This will hide if it's showing, show if it's hidden... kind of nice huh?

                event.preventDefault();  //Equivalent to false.  Need this for Firefox.
            }
        );
    }
);

And boom you have something that works. Hooray.

Couple things of note:

.Hide – At first I though this would screw up my class for the span by removing the current class and adding display:none. Turns out it doesn’t harm the original class. Kind of nice.

.Toggle() – This is really nice. It will hide if it is showing and show if hidden. Stupid easy to use and is pretty effective. Just like .Hide, the class of the element is not harmed.

$ versus jQuery – Some people might notice that I am not using the short hand $ for my jQuery calls. Turns out that it might be safer this way. There are other javascript libraries that use the $ short hand like prototype. I ran into this with WordPress since it uses both jQuery and Prototype and blocks jQuery from using $ since it could conflict with other libraries. Weeeee!

JQuery, Position : Absolute, and How to Make It All Work

This is a really quick one but when I was taking my cheesy pop up and reworking it using JQuery (After Andre the Annoying wouldn’t shut up about it), I ran into a fun problem: position:absolute wasn’t working like it should. You know “absolute is positioned at the specified coordinates relative to its containing block.”. Meaning it should at worst show up within it’s container, where ever that is. Now IE is fine with that and the thing was showing up well:

absolutepositionie

Firefox? Not so much:

absolutepositionfirefox

Well… turns out JQuery pretty much does it for me. With a simple method, you can set one element’s position relative to a parent’s position:

    function SetTopAndLeft(parentContainer, elementToSet)
    {
        var containerPosition;

        containerPosition = $(parentContainer).position();
        $(elementToSet).css({ top: containerPosition.top + 10, left: containerPosition.left + 10 });
    }

Really simple, you get the position of the parent container and you set the child element’s top and left to it. Or in this case, I have it just off since hiding the parent container could be problematic. (Say if the parent container is a link AND NOW YOU CAN’T FIND IT TO CLICK ON IT AND THINGS HAPPEN BAD THINGS AND THE WORLD EXPLODES BECAUSE OF YOU!)

And boom, you can for once be a winner just like me.

Add a Pop Up Div to a Link Dynamically

Sometimes in life you have to ask “should I do this”, this is not one of those times. The idea is simple, click on a link and a div appears over the link with some kind of message in it. Kind of like being able to add a pop up note to a word. If you are absolutely amazed by that, don’t be afraid. Most likely you’ll die soon from forgetting to breathe. However, if you are just slightly curious as to why and how, keep reading.

So why did I do this? Well it started with the idea of having something simple for a blog that has multiple authors: What if other authors could add notes to someone’s post in the post. Well the idea of using some kind of text change (Like italics) sounded lame. I wanted something easy that could be replicated quickly and wouldn’t be visible unless needed. Thus the onClick idea. Now the next problem I had was the class needed for the style sheet. As you can see, when the div is shown, it doesn’t displace any of the items on the page. This is because I am using position:absolute and a high z-index. This allows for the div to lay on top of other things and not touch them. Problem with absolute is that it basicaly plants the div in relation to it’s parent container. Now that whole parent container thing seems to be up for interpretation when you are talking about browsers. Each seems to deal with it the way it sees fit.

Originally I had it as a div that would contain this new div. This was a pain in the -ss. In IE it showed up over the div, FireFox not so much. So the next thought was to create a div to hold the div that held the div. Something that isn’t exactly “user friendly” to be sure. Then it hit me, maybe I could put this in a link. After all, people who are viewing the blog would understand it’s something they can click on (Provided I don’t screw with the link styles too much) and it’s easy for non coders to copy and paste.

So on to the promised land. First I’ll just get the CSS out of the way since it’s absolutely needed but needs little explanation:

.hidePostComment
{
    visibility:hidden;
    position: absolute;
    z-index:-100;
}

.showPostComment
{
    background-color:Gray;
    border-color:Black;
    border-style:dotted;
    border-width:thin;
    color:White;
    margin-right:3px;
    padding:3px;
    position:absolute;
    text-decoration:none;
    visibility:visible;
    width:100px;
    z-index:10;
}

.hidePostComment

As you can see, I’ve screwed with the z-index, visibility, and position. Position I’ve already explained, and I think you can understand why visibility is hidden with this class. However, z-index might not be something you know about. Basically,z-index tells the browser where an item is in a vertical sense. When you look at a browser, there are actually a lot of layers regardless of the 2nd appearance. The z-index is used to bring something forward or backward. If I want the div to be behind say the text I am typing right now, it has to be at a z-index lower than the text. I used -100 in the example just to make sure it’s behind anything. It’s really an arbitrary number though. A positive number would make the div appear in front of the text (And in that case the text would not show up since it would be “behind” the div) which is what I did with the visibility class.

.showPostComment

Mostly just a bunch of visual changes like border and background color. However, you will also notice the the position is still absolute and that the z-index is now 10. (positive) The div will now effectively be “in front” of the link when it shows up giving it the pop up look. One Note: I had to add in text-decoration:none since the div is attached to the link and IE wants to drag the underline with the pop up causing the text to up with an underline. Kind of odd but no big deal.

Now for the code:

function BuildSelectableSpanForPost(spanName, parentElement, innerText)
{
    var divToAdd;
    var parentContainer;
    //check to see if the parentElement is actually an element or string.  If string, use it
    //to find the element.
    if (typeof parentElement == 'string')
    {
        parentContainer = document.getElementById(parentElement);
    }
    else
    {
        parentContainer = parentElement;
    }
    //Create the div
    //set the name (The name must unique since there could be a million "pop ups" per page
    //set the id
    //set the text for the div which is what we want to show up in the pop up
    divToAdd = document.createElement('span');
    divToAdd.setAttribute('name', spanName);
    divToAdd.id = spanName;
    divToAdd.innerHTML = innerText;

    //Add the div to whatever element that was found.  For this post it will be a link
    //but it doesn't really matter.
    parentContainer.appendChild(divToAdd);

    return divToAdd;
}

So there is the building of the pop up div. Here’s the method to be called by the onclick event:

function ShowCommentForPost(postName, parentElement, innerText)
{
    var divName;
    var createdDiv;
    var parentContainer;

    //Same as before
    if (typeof parentElement == 'string')
    {
        parentContainer = document.getElementById(parentElement);
    }
    else
    {
        parentContainer = parentElement;
    }
    //See if the pop up div  already exists.  If it does, then don't create again
    //I didn't have this before and it would create a new div everytime
    //That's what some might call a surprise feature
    divName = 'comment' + postName;
    createdDiv = document.getElementById(divName);
    //Ooops, the div didn't exist, create it and add the hide class
    if (createdDiv == null)
    {
        createdDiv = BuildSelectableSpanForPost(divName, parentContainer, innerText);
        //this is a method found on this post
        ClassHandler.AddClass(createdDiv, 'hidePostComment');
    }

    //this is a method based off this post
    //As you can guess it will show or hide depending on which class it already has.
    ShowHideElementBasedOnCss(createdDiv);

    return false;
}

To start, there is the code to create the actual div.

Now for the actual use:

<a onclick="return ShowCommentForPost('1', this, 'THIS IS SO STUPID!');" href="www.byatool.com">word.</a>

Pretty easy to actually use right? The actual location doesn’t really matter since it the method will always return false and therefore the link will never redirect. Also, you’ll see that I put 1 as the name sent in. The name sent in doesn’t matter what it is, but for every link it has to be different. If you are using this in a blog situation where there could be multiple blog posts in one page, I would suggest the name sent in would be the title and an increasing number.

If you got to this point and feel robbed of five minutes in your life, well just be happy this post robbed me of 15 minutes of mine.