Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Saturday, June 04, 2011

Javascript Binary Heap

Saturday morning javascript exercise - a binary heap in array and tree implementations. The tree implementation is faster as expected when you shove a lot of data as it as the array implementation must occasionally re-size the backing array. A demo or visualization would be nice but that takes more time than this Saturday morning allows. Code:



Monday, February 01, 2010

jQuery Shell Google Chrome Extension

I've written a handy Google Chrome extension for jQuery developers. The extension allows you to bring up a console window and run Javascript and jQuery commands against the current web page. It is great for learning or experimenting with jQuery. I call the extension the jQuery Shell and it can be found here. The source code can be found here. Here is a screen shot for your viewing pleasure:


Google Chrome has a really nice extension framework.

A couple of other useful Javascript tools (not Chrome extensions) I've discovered on the web lately are http://jsfiddle.net and http://jsbin.com/.

Friday, July 03, 2009

No Peeking in the Javascript Deque

Another (previous) take on the Javascript Deque with more of a Crockford creation style preventing messing with the Deque's internals. Create one without using new - "var d = deque();", enjoy:

Wednesday, July 01, 2009

Javascript Deque

Doubly ended queue code is just a whole lot cleaner if you go with dummy head and tail nodes to avoid special cases. I put together this Javascript example: A Javascript array has the methods available (push(), pop(), shift(), unshift()) to be used as a deque but of course being an array you shouldn't be adding and removing from anywhere but the tail end if you need top performance. The following provides for a comparison between my deque and a regular Javascript array for adding and removing items from the head or tail of the data structure.
Items:
array dequeue
head tail

Tuesday, May 05, 2009

Some Core Javascript Functions

I recently worked on two different projects that involved a fair amount of Javascript centering around using the Google Maps API. In doing so I began to factor out some of the components to be reusable in a general Google Maps project. While I usually use the excellent Prototype Javascript library I didn't want to leak Prototype code into these reusable components. This led me to using these functions, borrowed / evolved from various places, as the core functions to support the components:



I think these functions are a pretty good representation of the baseline support you will want in many Javascript projects.

Monday, April 13, 2009

Javascript Puzzler

Invoking an anonymous JavaScript function is a handy technique for avoiding namespace collisions in JavaScript code. The following two code snippets show the definition of a top level function followed by the invocation of an anonymous function. One of them, however, has a (easily fixed) problem (at least on Firefox 3.0.8). Can you spot what it is? Try figuring it out without running the code - don't cheat! Put your answer in the comments.

Snippet one:



Snippet two:



Surprising behavior. I'd be interested to find out if different browsers / JavaScript engines treat these code snippets in the same way.

Saturday, March 28, 2009

Display Google Docs Spreadsheet Data on Your Website

The Google Spreadsheet API makes it pretty painless to display spreadsheet data on your own web pages using only client side technologies. You might use this, for example, to display your terrible stock investments on one of your web pages to remind you why you have to go to work everyday.

The first thing you need to do is to make a Google Doc Spreadsheet. The second thing you need to do is to "Publish" the spreadsheet. This will make your spreadsheet available for anyone to view and is required if you are going to consume this data with unauthenticated Javascript running in a web page (so you probably don't want to do this with a sheet that contains your world domination secrets). To publish your spreadsheet, click on Share -> Publish as a Web Page -> Publish Now. Depending on the data you may also wish to check "Automatically re-publish when changes are made." For my example you certainly want to do this because the spreadsheet contains stock symbol lookup functions where the numbers will change as your stock investments go lower and lower.

After you have published your spreadsheet you need to get two pieces of information about the spreadsheet - the spreadsheet identifier and the identifier of the individual worksheet within the spreadsheet that you want to snarf the data off of. While it is possible to get at this information by pulling down meta-feeds about your spreadsheet documents it is probably easier if you just navigate to your published spreadsheet and choose View -> Source from your browser. In the source look for a link tag with rel="alternate". This tag will have an href that contains both the spreadsheet and worksheet identifier. An example looks like this:



In that href the "pBYwcZBFkvxZycw-gNxPCIw" is the spreadsheet identifier and the "od6" is the worksheet identifier. With these pieces of information you are now ready to write some code to pull the spreadsheet data back to your web page.

There are two different feeds that you can get to pull that data back to your site. They are identified as "list" and "cells" feeds. This basically breaks down to whether you get the data back as a series of rows or a series of cells. I believe in most cases you are going to want to work with a series of rows so you will use the "list" feed, however, check the API if you believe the "cells" feed may work better for you. The code below shows the feed URL being used to cause a callback to the function processStocks:



I won't go overboard explaining this code here - I think you can figure most of it out. It merely iterates through the returned result set from the spreadsheet, adding each stock value as to an unordered list in the page. It also keeps a running count of the total in a variable called bindex - the Burger Index. The way the cell entries are referenced is a little awkward and corresponds to the column headers - as seen in my example entry.gsx$symbol.$t and entry.gsx$price.$t. Part of this awkwardness comes from the format being a translation of the alternate XML format.

Currently you can see this code in action on my github page as well as list and cells feeds examples here.

Monday, February 16, 2009

Greasemonkey Hawaii State Library Lookup

John Udell wrote a Greasemonkey script called LibraryLookup several years ago that I modified to work with the University Of Hawaii's library system. LibraryLookup works in the background when you visit pages on Amazon.com and puts up an indicator if your local library has the book you are browsing.

Later, I attempted to get this script to work with the Hawaii State Public Library System (HSPLS). I quickly found out that the HSPLS was using an ipac system (good! that is on the supported list) but for some reason they have turned off searching by ISBN (are you kidding me!?). I sent someone in their IT staff an email at the time and they responded by saying it was something they would be turning back on soon. A couple years later I checked and still no ISBN search. I sent another email and the response was something about upgrading to a different catalog system. John's script worked by looking for the ISBN, and while I could see ways to get it to work by Title and Author, I never took the time to actually adapt it to do so - until now. My script does an initial search by "Author Keywords" and "Title Keywords" and then looks at the content of the resulting page for an ISBN match. Here is the code:



So to use the code download it to your computer and name it something like hspls.user.js. Then, if you have Greasemonkey installed and open the file with your browser, it should ask you if you want to install the script. After installing the script, whenever you visit a book's page on amazon.com the script will check the HSPLS's site to determine if they have the book. When it finishes this lookup it will append a link to the Amazon page right after the book's title. The link will contain either the text HSPLS(Yes) or HSPLS(No:#). In the case of Yes, an exact ISBN match was found. In the case of No, the ISBN was not found and the # will contain the number of books that were found given the search term that was submitted. The following screen shot shows an example where the lookup failed but indicated 6 possible fuzzy matches:



Ok, that was a bad example! One of the fuzzy matches is the actual book under a different ISBN, oh well. Did I just spend 2 hours of my day off polishing up that script? Yes, I guess I did.

Wednesday, February 11, 2009

Javascript HTML Select Again

Just a short follow up to yesterday's post with set value and get value functions that will work with both single and multiple select HTML elements. The code expects that you will correctly pass a single value / array value when calling against the select element:



Probably only the set part of this code is of interest to you if you are using Prototype as prototype will give you the correct result with Form.element.getValue or $F.

Tuesday, February 10, 2009

Javascript HTML Select - Multiple Select

Simple Javascript code to set multiple selections in an HTML Select element - The first step is that the select must be set up to allow multiple selections, that is it must have the attribute multiple="multiple". Second, we need some supporting code to find the position of a value in an array - if you are using Prototype or limiting your usage to newer browsers you may not have to roll your own here as indexOf will be a method of the Array object. Otherwise you are going to need this:



Now the code to set the selections. You pass in the select element, an array of selections, and an optional boolean. The boolean defaults to false and indicates whether or not to invert the selection:



Now for a little demo:



Monday, December 29, 2008

Javascript Event Bubbling with Prototype

Update: After I wrote this post I remembered that change events don't bubble in IE6 for select elements and thus likely don't bubble for check boxes either. After an investigation I found out that no - they don't bubble. So this code won't work correctly for IE 6 which still commands a 20% + share of the market. Please STOP IE6 NOW...and on with the post.

Bubbling is a good thing...and no I'm not talking about the fact that it might help you to locate a turtle. Javascript events bubble from the source element outward. This gives you a couple of important benefits when attaching event handlers to elements:

  • reduced resource usage - one global handler instead of a handler on each element
  • simpler wiring with dynamic content - instead of adding handlers to new elements inserted into the page, the parent element already has the lone handler


The following example shows some code where a div element with an id of "overlay-entries" contains a number of, well, overlay entries in which each overlay entry has an checkbox element that allows that overlay to be shown or hidden. Instead of wiring up a handler for the "change" event for each checkbox we can merely catch the events as they bubble to the containing div with the id "overlay-entries." With prototype Event objects are normalized to make sure that the .element() method returns the element that the event actually originated on. In my situation it is enough to check that the event fired on a checkbox to allow the corresponding event to fire:

Monday, December 22, 2008

Send HTML to Javascript Functions from Rails Partials

Many Javascript libraries, such as ExtJS, allow you to pass HTML to functions. A good example of this is the Ext.Msg.alert call which accepts a a title and a message where the message string can have HTML markup in it to form the content of the alert popup. When this message is a large block of HTML, for example a large disclaimer that you have to stick up in the face of your customer, it becomes very awkward to include this HTML text in the same page that shows the popup. It bloats the page and mixes together what would be better edited by a "subject matter expert." What you really want to do is to put this disclaimer into its own partial but then you have to figure out how to render the string so that newlines and other content don't break the Javascript. How do you do that? Here are two ways that work:

Saturday, November 15, 2008

Merb Javascript Delete link_to with Prototype.js

I got on the elevator to go home from work the other day and this other guy in the elevator says to me "Those look like comfortable shoes." Huh? Did I just step in the world of Forest Gump? What is that all about?

Currently there is quite a pissing match going on in the world of Rails with fronts against Zed Shaw and Merb - see here and here. I hope all this energy can be channeled to improving frameworks and not just spewing internet bile.

Anyway, did a little playing around with Merb - just wanted to see what it would take to set up a resource, a restful controller, and how it would compare to Rails. I came away impressed, Merb appears to be another great Ruby web framework. Right now it would appear the biggest deficiency in the project is documentation. Merb is currently woefully lacking in documentation compared to Rails.

Among a bunch of small difference the url helpers are on of the biggest differences. The Merb way is demonstrated here. The last thing I needed to figure out was how to get Merb to generate a delete link that uses javascript to post back to the controller - you know something like this in Rails:



After looking a Merb's link_to documentation for a while I realized - "ah, Merb is Javascript library agnostic and also wants to be unobtrusive." So, instead of looking for someone else's canned solution I cooked up my own using Prototype. Just add a class to your link:



and then hook in your events with some prototype:



The url(:delete_xxx, @xxx) in Merb actually creates a link to /xxx/:id/delete where you can place an "Are you sure?" form for users with Javascript turned off. The above code will bypass that if Javascript is enabled.

Ok, enough playing around with Merb for now, time to look at Sinatra - only 1576 LOC!

Wednesday, October 01, 2008

Raphael Bakes a Nice Pie

Raphaël is a very cool Javascript library that provides an abstraction over the the vector graphics capabilities built into today's browsers. I cooked up a little example that demonstrates the usage of Raphael to make a pie chart component:



This example seems to work well on all modern browsers and will even work on IE back to at least version 6. It uses SVG on most browsers and VML on the IE line - this is some very impressive work by Dmitry Baranovskiy.

So what is so good about SVG and VML over a regular canvas? Events my friend, events!

Saturday, September 27, 2008

Ext JS Custom TreeNodeUI

I wrote this some time ago and then noticed that Blogger blasted the indentation in the code snippets so I'm only posting it now.

Hey, this should be a good dump - I needed an Ext JS tree with a custom TreeNodeUI. In addition to the usual text, I wanted each TreeNode to feature a select box that would allow a selection (and Ajax saving of the selection) to be made for each node. While the Ext JS API Documentation is pretty good, it doesn't always provide the information needed when trying to "step outside the box." (This framework is just dying for someone to write a book about it...) After just a little head scratching I found writing such a custom TreeNodeUI to be fairly straight forward.

The first thing I needed to do was to define my SelectNodeUI having it call its parent constructor on instantiation:



After that, I needed to extend my SelectNodeUI, inheriting from the standard TreeNodeUI, while overriding the renderElements and onSelectChange methods. The renderElements method is overridden to add the select box (look for the sel variable). The onSelectChange method is overriden to prevent the normal focus change which would unfortunately cause the select box to close immediately when first selected. This looks like a lot of code but is primarily a copy of the TreeNodeUI renderElements method with the rendering of the select box added. I've marked the parts I've added / changed with // DJB: comments:



Take special note of the building of the selectHtml string from the COMMAND_HIERARCHY_TYPE_ARRAY which has been written into the page in the format of [["label text", id], ...] and how the correct option is selected after the selectHTML has been rendered into a select box DOM node.

Now that the custom tree node is defined and ready to use the loader for the TreePanel needs to be informed about which UI providers are available. This is done by setting the uiProviders property of the loader property of the TreePanel:



With this code in place, a mapping has been defined between the string "select" and the SelectNodeUI. If the JSON for a tree node comes back with the value uiProvider: "select", the SelectNodeUI will be used to render that tree node, otherwise, it will fall back to using a regular TreeNodeUI. Keep in mind that such a tree node will also need a typeId property so that the proper option can be selected in the select box. With Rails the JSON for these tree nodes might be rendered with a method like this:



Unfortunately, as the comment says in the code, Internet Exploder does not bubble change events. Thus each select node has its own change listener that calls selectChange (otherwise I could have wired up a single change listener at a level above these tree nodes in the DOM tree). selectChange is a fairly straight forward function which uses an Ajax call to save the new state for the tree node's underlying model:



Finally, the select boxes are slightly taller than the normal content held at a tree node and thus mess up the lines that are drawn connecting the + / - expanders along the left side of the tree. Instead of fixing this up to look write I would recommend just turning the tree lines off. This can be done with by setting up the TreePanel with either the lines: false or useArrows: true properties. With lines: false the tree will render with the same old + / - expanders but won't render the lines. With useArrows: true the tree will render with a look that is supposed to emulate "Vista," using small triangles and drawing no lines. I'm not sure what this "Vista" thing is and I couldn't seem sudo apt-get install it ;-).

Sunday, September 21, 2008

Generating Combinations in Ruby and Javascript

Hey, time to dust off your discrete math text! (The one I used is Discrete Mathematics and Its Applications by Kenneth H. Rosen). The number of combinations of r items that can be selected from n items is given by the formula = n!/r!(n - r)! (note to self, render this with MathML). The following three code blocks show how to return those combinations in Ruby, Javascript, and Javascript with Prototype. Note that these functions yield (in Ruby) or do a callback with (Javascript) each combination. These could easily be modified to return an array of the combinations. After the three code snippets is a live example of the Javascript code. First the Ruby: Now the Javascript: And finally Javascript with Prototype (wow, now like Ruby): Wow, if that doesn't make you want to learn Prototype using Prototype and script.aculo.us: You Never Knew JavaScript Could Do This! then nothing will.

[ combinations ]

Saturday, September 13, 2008

method_missing in Javascript

method_missing in Javascript? Well not yet -- but you might be surprised to learn that some Javascript implementations already feature this functionality. For example, it appears that Mozilla based browsers have had __noSuchMethod__ since at least Javascript version 1.5. Also, it looks like this feature is quite possible to become a standard feature of Javascript in the future although not likely for 3.1. Look here for a couple of threads discussing this feature.

What might you do with a feature like this? If you found this page I imagine you already have a few ideas in mind but if not the Ruby on Rails framework contains many examples of this technique. Ruby on Rails uses Ruby's method_missing for all sorts of "meta-programming" magic like dynamic finders such as ActiveRecord::Base#find_by_login_and_password('bob', 'cheese').

So I can't leave you without an example...If your browser is so inclined, the following text box will allow you to enter any call you like against the "example" object and will use __noSuchMethod__ to spit back information about the call.






The code that sets up the "example" instance looks like this:




I, for one, would really like to see a feature like this become a Javascript standard.

Hey, if you are interested in learning more about Javascript I would recommend the following books: Javascript: The Definitive Guide, Pro Javascript Techniques, and Prototype and script.aculo.us: You Never Knew JavaScript Could Do This!

Oh yeah, one last thing - since Javascript objects are pretty much just hashes this type of method missing technique really only needs hashes to be extended to allow a default value to be specified like you can do with a Ruby Hash. This would result in the possibility of writing code like this:



I'm not sure what type of syntax could be offered if the object didn't begin its life as a Hash.

Thursday, September 11, 2008

Javascript - Change your Stylesheet not your Style

Most Javascript code that interacts with the CSS of a document does it by interacting with the individual elements on the page. For example, a Prototype script to change the background color of a specific element on the page might look like this:



While this works well, in some cases you may be wanting to apply the same style to 100s of elements. Recently I ran into this problem when coding a Prototype version of the Flickr Photo Demo. (Hey, sorry this might be foobar on IE, I just haven't had time to take a look at cross browser issues for IE on this demo.) The demo has a slider in the upper right corner that changes the size of the displayed images. My first cut at the demo can be found here. On a fast modern computer, this works pretty well, however, given the loops that are needed to apply new pixel sizes to the images and the divs that contain them, the slider can be jumpy on an average system. This demo only displays 20 images at a time, so it is easy to see how this problem could get very noticeable when more elements are involved. The key code applying the styling changes looks like this:



This had me thinking of ways to get the slider to work more smoothly. The first solution I thought of was to use different classes for the containing "#content div" which would result in the needed style changes to the contained div and img tags. The new code looked like this:



Look mom! No loops. The new code is fast and the slider operates very smoothly. As the astute reader may have figured out, however, this required me to have a very large stylesheet for this page. The reason is that the class for the "#content div" is being changed to sizeXXXpx where XXX can be any number from 50 to 250. How big is the stylesheet? Well picture 402 lines of this kind of stuff:



This version of the Flickr Photo Demo can be found here.

Without my emacs fu this file would have been a pain to create - but no matter what its still ugly. This got me thinking about another solution - surely Javascript will let you modify the rules in the stylesheet dynamically, right? After a little googling I found out it is possible but it doesn't seem like it is a very popular technique. I quickly hacked together the following general function for modifying the rules of a stylesheet:



On thing to keep in mind about this code is that it stops searching for the rule to change once it finds the first matching selector that it runs into. This is of course going to be a problem if you have the same selector defining css rules at multiple places in your stylesheets. You may need to adjust the above function if you don't have control over how your stylesheets have been defined.

This allowed me to change my slider code to the following:



Wow, it works, no loops, fast, and my stylesheet is back to being slim and sexy. This version of the Flickr Photo Demo can be found here.

This got me to wondering how cross browser this technique would be. To test this out I made this page which implements the most bare bones demonstration of this technique and tried it out on a few different browsers. It worked fine on all the browsers I tried it on. I wanted to do one last test that targets more browsers so I made this page and submitted it to Browsershots. (Browsershots is cool, you submit it a page and tell which browsers to take screenshots for - then sit back and wait for the results to roll in). This final test put the stylesheet modifying code in the window.onload event and changed the background from red to green. This would make the browser shot screenshots show in green on a browser that handles the technique and show in red on a browser that trips up on it. It worked in every browser I asked Browsershots to test it on.

So there you have it, you apparently can dynamically change the rules in stylesheets rather than changing the styles on individual DOM elements. So now I'm wondering, why is the usage of this technique not more prevalent?

Tuesday, September 09, 2008

Flickr Photo Demo the new Hello World of Web Client Frameworks

Hello World

It looks like the "Flickr Photo Demo" might become the "hello world" of web client frameworks. First the 280 North team released the Cappuccino framework and published their Flickr Photo Demo. Then the broken digits blog released a version written with the help of jQuery.

I've been wanting to improve my Prototype and Scriptaculous skills so I took the broken digits example and replaced the jQuery code with Prototype and Scripty code (yes, I borrowed all heavy lifting on the HTML and CSS work from broken digits). My version can be found here.

If you are interested in learning Prototype and Scripty I strongly recommend the book Prototype and script.aculo.us: You Never Knew JavaScript Could Do This!. It is very well written and will help you understand not only the frameworks but will also give you a deeper understanding of the Javascript language as well.

If you are interested in arguing the future of these frameworks...bah, I'm going to sleep.

Wednesday, June 11, 2008

Javascript Closure

I think most people writing a lot of javascript eventually run into a misunderstanding about closures. Take a look at the code below. The code dynamically creates three buttons that show an alert box when clicked upon. What do you think will happen when you click each button?






The problem is that the animal variable used in the button's onclick event is changed in the loop and thus the event will use the value that was last assigned to the variable. In order to get the onclick event to use the value of the variable at the time the onclick is defined you will need to define an execution context which will capture this value. This can be done using a function. While this can be done with a regular function here is a nifty little example of doing this with an anonymous function:






Here is a slightly different (possibly simpler) way to create the function closure: