Rough Book

random musings of just another computer nerd

Tag: javascript

Doing front-end development IS such a pain

This is so true that it’s hilarious. And sad. Any time I try to do something a little nontrivial for the front-end, it goes downhill so quickly. It’s like you are at this bizarre Home Depot with a million tools and you aren’t quite sure what they do because the most of the instruction manuals are missing pages or are just completely absent. There are very few that are complete.

You went there trying to get some nails and a hammer to hang a picture at home. But the nails only come in package that includes a lava lamp, a sledgehammer that weighs 50 lbs, and 217 blocks of assorted shapes, sizes, and colors. You get a hammer that seems to be the most popular but then you read a blog post from a carpenter ninja rockstar who has come out with a new hammer-design (and a cool name: “Hamm.ür”) that everyone is raving about and is a huge improvement over the new one and has started a new company that is already building and selling it. Home Depot also just happens to have it. You decide to get the new one; the old one wasn’t that actively supported by the manufacturer anymore anyway. In fact, it was just made by one guy in his garage and no one had seen him in a year and he rarely answered his phone or responded to emails. The new hammer does also come in a package with other stuff but at this point you really just want to hang that picture because that thing has been sitting against the wall for months.

You get home and finally start to hammer in the nail but end up burning your house down because the hammer replaced the lava lamp’s power adapter with a bare copper wire that set your curtains on fire. When you complain that using bare copper is unsafe and that they shouldn’t come with hammers or replace power adapters in a lava lamp that you didn’t even want in the first place, because seriously why the hell does anyone sell lava lamps with nails, you get told “Stfu noob! Copper is like the second-best fucking conductor and it is cheaper than silver and bare copper is so much lighter than a whole stupid adapter; seriously weren’t you just complaining about not wanting extra shit with what you buy?”


I am at JavaOne! The last time I was here was in ’08, when it was run by Sun. Of course, it’s run by Oracle now. The first day has been pretty good. I attended sessions on Garbage Collection, the Nashorn JavaScript engine, writing DSLs, and about parallelization options offered by JDK 7 and 8 to leverage multicore processors. Pretty good first day!

Nashorn looks pretty interesting and I will be giving it a closer look when I come back home. They are also looking for people to help out so I am going to see if I can contribute anything useful.

Today I will be checking out a talk on Lambdas by Brian Goetz and will also be going to a talk on Big Data. Finally I also have some BOF (birds of a feather) sessions on evolutionary algorithms and writing parsers in Scala. Pretty interesting day and I’m looking forward to it!

Rendering a PDF with text-selection, using pdf.js

I have been working a project for the last few days, that deals with rendering PDF’s in-browser. Initially, I was going to parse the PDF and extract the text content, but then I ran into pdf.js, which is a library developed by Mozilla for rendering PDF’s in-browser via JavaScript. The project I am working on has a requirement that users should be able to select text within the PDF. This is possible using pdf.js. Unfortunately, the example code only shows you how to render a PDF, but not how to enable text-selection. I wasn’t able to find any API access to enable text-selection either. I finally ended up on the #pdfjs IRC channel and the friendly folks there gave me some direction. The logic for enabling text-selection was buried inside the code for Mozilla’s PDF viewer, and was heavily intertwined with the viewer code as well. I spent a few days playing around with the viewer and tracing through the code. I was stumped many times since the code was complex and I know jack about parsing PDF’s. But eventually I was able to focus on the part of the code that actually took care of enabling text-selection.

pdf.js’ approach to enabling text-selection is actually quite clever. The library overlays divs over the PDF, and these divs contain text that matches the PDF text that they are floating over. So when you select the text, you are actually selecting the text inside the overlaid divs. This was fine and dandy, but I was still stuck as far as getting this to work on my project. What I needed was a minimal example that I could adapt for my uses. After a day or two of tracing code, experimenting, debugging, and staring at the screen in frustration, I was eventually able to come up with a minimal example! To accomplish this, I extracted code that was relevant to creating the overlays out of the viewer code, into its own independent file. I also removed a lot of code that was dependent on the viewer itself. Keep in mind that this example doesn’t have functionality like text finding or matching, and that code is also heavily intertwined with the viewer code. All this example does is render a PDF with text-selection enabled. However, I think this is a good start!

If you are interested, you can check out the code on github and a working example on this fiddle.

The pertintent code is as follows (keep in mind you still require additional resources; all of that information is available on github):

window.onload = function () {
    var pdfBase64 = "..."; //base64 representing the PDF

    var scale = 1.5; //Set this to whatever you want. This is basically the "zoom" factor for the PDF.

     * Converts a base64 string into a Uint8Array
    function base64ToUint8Array(base64) {
        var raw = atob(base64); //This is a native function that decodes a base64-encoded string.
        var uint8Array = new Uint8Array(new ArrayBuffer(raw.length));
        for (var i = 0; i < raw.length; i++) {
            uint8Array&#91;i&#93; = raw.charCodeAt(i);

        return uint8Array;

    function loadPdf(pdfData) {
        PDFJS.disableWorker = true; //Not using web workers. Not disabling results in an error. This line is
        //missing in the example code for rendering a pdf.

        var pdf = PDFJS.getDocument(pdfData);

    function renderPdf(pdf) {

    function renderPage(page) {
        var viewport = page.getViewport(scale);
        var $canvas = jQuery("<canvas></canvas>");

        //Set the canvas height and width to the height and width of the viewport
        var canvas = $canvas.get(0);
        var context = canvas.getContext("2d");
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        //Append the canvas to the pdf container div
        var $pdfContainer = jQuery("#pdfContainer");
        $pdfContainer.css("height", canvas.height + "px").css("width", canvas.width + "px");

        //The following few lines of code set up scaling on the context if we are on a HiDPI display
        var outputScale = getOutputScale();
        if (outputScale.scaled) {
            var cssScale = 'scale(' + (1 / + ', ' +
                (1 / + ')';
            CustomStyle.setProp('transform', canvas, cssScale);
            CustomStyle.setProp('transformOrigin', canvas, '0% 0%');

            if ($textLayerDiv.get(0)) {
                CustomStyle.setProp('transform', $textLayerDiv.get(0), cssScale);
                CustomStyle.setProp('transformOrigin', $textLayerDiv.get(0), '0% 0%');

        context._scaleX =;
        context._scaleY =;
        if (outputScale.scaled) {

        var canvasOffset = $canvas.offset();
        var $textLayerDiv = jQuery("<div />")
            .css("height", viewport.height + "px")
            .css("width", viewport.width + "px")
                left: canvasOffset.left


        page.getTextContent().then(function (textContent) {
            var textLayer = new TextLayerBuilder($textLayerDiv.get(0), 0); //The second zero is an index identifying
            //the page. It is set to page.number - 1.

            var renderContext = {
                canvasContext: context,
                viewport: viewport,
                textLayer: textLayer


    var pdfData = base64ToUint8Array(pdfBase64);

Integrating Regula with Spring 3.0.x MVC

A little less than a year ago, I released Regula, an annotation-based form-validation written in Javascript. The source and documentation are available on GitHub. I started working on the integration on and off throughout most of last year. At the end of the year, I had a pretty good integration going, where you could annotate fields with Hibernate Validator annotations, and the corresponding Regula validation-code would be generated on the client side. Of course, I wasn’t done yet because what I had was simply a demo project and I had to figure out a good way to distribute the whole thing; I was able to finish up the packaging and distribution today. With minimal setup, you should be able to get started with Regula and Spring. You don’t need to go through this post to figure out how to use the integration. This post is mostly about how I accomplished the integration (I don’t go into all the details; just the important bits). As far as actually using it, I will make a blog post about it later.

The source for the integration is also hosted on GitHub. My approach towards translating validation constraints from the server-side to the client-side was two-fold: gather validation constraints from the object and represent it in a canonical form. Using the canonical form, generate Javascript code that uses Regula for validation. To do this, I created a service that examines a domain object and gathers all information regarding its properties and validation constraints. The service returns this information in a canonical form, that I then inserted into the model. On the client-side, I had a tag that used the canonical form and outputted Javascript that uses the Regula framework. Initially, I was calling the service explicitly from an action in the controller. Later, in an effort to make the integration less-invasive and more seamless, I used an aspect-oriented approach with interceptors. In fact, that’s where I’d like to start.
Read the rest of this entry »

Anonymous self-invoked recursive-function in Javascript

I needed to do an n-ary tree traversal recently with some Javascript code that I’m working on and I initially wrote an iterative n-ary tree-traversal algorithm (using a node stack with a while loop). I wanted to keep track of some extra (depth-dependent) data during the traversal and I didn’t like the way I was forced to do it with the iterative algorithm. I also didn’t feel like adding a new function to the namespace. Then I realized that you can create function-literals in Javascript and self-invoke them. So I ended up with the an anonymous self-invoked recursive function. Here’s the basic skeleton for an n-ary tree traversal (this one is pre-order):

for(var i = 0; i < node.children.length; i++) { console.log(; arguments.callee(node.children[i]); } }(root)); [/sourcecode] You can also do a binary tree traversal (this one is also pre-order): [sourcecode="javascript"] (function(node){ if(node != null) { console.log(; arguments.callee(node.left); arguments.callee(node.right); } }(root)); [/sourcecode] Seems very elegant and also very Lisp-like to me (must be the parentheses!)

Regula: An annotation-based form-validator written in Javascript

Regula is an annotation-based form-validation framework written in Javascript. There already exist a few frameworks that address form-validation in Javascript, but I have found them to be somewhat lacking. I have thought about writing one of my own for some time, but I honestly had no idea what form it would or should take. I knew that I wanted to make one that was easy to use, flexible, and easily extensible (custom validation rules). I finally got an idea as to the form my framework should take, when I was looking at Hibernate bean-validation. I like the fact that you can set constraints by using annotations like @NotNull or @NotEmpty. That way, when you look at the bean, you are immediately aware of the constraints attached to it. I wanted to do something similar in HTML.
Read the rest of this entry »

jQuery tip: Changing the TYPE attribute of an INPUT element

I was trying to change the type attribute (using jQuery) of an input element from submit to button when I got this error:

type property can’t be changed

Apparently, you can’t change the type attribute of an input element once it’s part of the DOM. I figured out a way to do it by cloning the old element and then changing its attribute. Since the element isn’t part of the DOM, you can change its attribute. After that, you can add it to the DOM and remove the old element:

var oldButton = jQuery("#Submit");
    var newButton = oldButton.clone();

    newButton.attr("type", "button");
    newButton.attr("id", "newSubmit");
    newButton.attr("id", "Submit");

Drop-shadows with CSS and Javascript

You have probably seen websites that have images with drop-shadows. It gives the image a three-dimensional floating effect. Usually the images are given drop-shadows with an image editing software like Photoshop. In IE, a drop-shadow is easy to achieve using the DropShadow filter. Unfortunately, this method is not standards compliant and only works on Internet Explorer 5.5 or later. For all the gripes I have against Internet Explorer, I actually like the filters on Internet Explorer and I wish that the W3C would figure out a standards-compliant way to implement filters in their CSS design.

Currently, the only way to implement drop-shadows without resorting to IE’s DropShadow filter is to have an image that was previously edited through an image-editing software, dynamically generate the drop-shadow for the image through a dynamic graphics generation tool like GD or ImageMagick, or (complicated} CSS. I have run across a number of CSS-based drop-shadow solutions on the web. I either found them to be too complicated or unsatisfactory. My major problem was that I couldn’t easily accommodate them into my site design. One major problem I had was that many of the solutions employ floated images. This was an issue for me, because I like to center my images and this is impossible to do with floated elements. In addition, I have a major case of Re-inventing The Wheel So I Can Say It’s Mine! syndrome. Anyway, I decide to muck around and come up with my own solution. I have come up with one that doesn’t look that complicated and should work… in theory. But I ran into some issues when I tried to apply it. As a result the final solution is… well, clunky. But it works for me!

My solution involves the use of two divs. The first (parent) div contains the shadow image (which I shamelessly stole from here). The child div contains the actual image for which we want to create a drop-shadow. Essentially, the layout looks like this:


Pretty simple. In HTML, the structure looks like this:

<div style = "position:relative;">

 <img id = "sh_image" src = "" />

 <div style = "position:absolute; top:-Xpx; left:-Ypx;">
  <img id = "img_image" src = "" />


You might be wondering what the Xpx and Ypx things are. Well, this is where some of the clunky parts come in. One problem I faced was that I couldn’t simply offset it by a constant amount, like 5px, for example. For some reason, the amount needs to be changed based on the dimensions of the image. I am not sure why this happens. Theoretically, the dimensions shouldn’t matter. Well, that’s one of the clunky issues. The other one has to do with Javascript. If you implement what I have so far, you’ll notice that the parent div would extend to accommodate the entire shadow image. This is obviously not what we want. My solution for this problem was to use Javascript to scale the shadow image to the size of the child image:

function dropShadow(img_name, shadowWidthExtend, shadowHeightExtend)
         var shadow = document.getElementById("sh_" + img_name);
         var img = document.getElementById("img_" + img_name);

         shadow.width = img.width + shadowWidthExtend;
         shadow.height = img.height + shadowHeightExtend;

What’s shadowWidthExtend and shadowHeightExtend you ask? Well, that’s another clunky part. So even after I set my offsets (through trial and error) as per the image dimensions, I still found that my drop-shadows didn’t look perfect. In order to make them look good, I had to “extend” the shadow image’s height and width. Yeah, not that ideal. But like I said, it works. I am not sure why these issues exist. I think it might have to do with the scaling of the shadowy parts of the shadow image (where it actually fades).

Now we can put it all together:

In your HTML file:

<div class = "shadow">

 <img id = "sh_image" src = "" />

 <div class = "image">
  <img id = "img_image" src = "" />


<script language = "Javascript">

 dropShadow("image", A, B);


In your CSS file:


    top:-Xpx;   /* determined based on image dimensions */
    left:-Ypx;  /* determined based on image dimensions */

In your Javascript file:

function dropShadow(img_name, shadowWidthExtend, shadowHeightExtend)
         var shadow = document.getElementById("sh_" + img_name);
         var img = document.getElementById("img_" + img_name);

         shadow.width = img.width + shadowWidthExtend;
         shadow.height = img.height + shadowHeightExtend;

As you can see, far from ideal. If I was only able to figure out how to make the offsets constant then this would be a pretty decent solution. If anybody knows why this is happening, please let me know. I am decently proficient in CSS and I am not a guru by any means. But I love to learn!

Oh, and as far as centering the drop-shadowed image, that’s easy to do by wrapping the whole thing in a center-aligned table with only one row and one cell.

Scrolling problems

I’m having some problems with my Javascript code when it comes to scrolling with the mouse-wheel. You have to focus out side the “content” for it to scroll properly, especially in journal entries where the content is really long.

I have an idea in mind, but it involves restructing completely. I’m thinking of removing the iframe and dumping in content directly.

Ecological Simulators and Photo Albums

I finished the “Delete Photos” page on the Photo Album Tools page… which of course, none of you can see, since it’s in the admin section. But anyway… It took me this long, because I had other stuff to take care of… namely CSE 421. I only have the “Update Photos” tool to finish… after that, I should start working on the actual photo album display page. In other news, I’m working on a JavaScript version of my Perl Ecological simulator (the one that ran wild on ASU’s general server… ohhh I’m so proud of myself). Except in this case, it’s objects that are killing each other… it should give me a lot more flexibility. My creatures even have randomly generated names like “zexoyiwub” and “xorigewor”. It’s going to be fun… once/if I finish it.

All original content on these pages is fingerprinted and certified by Digiprove
%d bloggers like this: