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

Tuesday, May 20, 2008

jui lightning talk: jFormino

This is my jFormino lightning talk for JUI conference. It's a very nice experience to meet those JavaScript hackers in Japan, and around the world. I'm hoping such javascript conference in Taiwan. Thanks to Kawasaki-san and RECRUIT for hosting such great event, thanks for Paul Bakaus for sharing us those jQuery UI internals. Thanks to amachang for telling us about s6. My eyes are opened. :)

Friday, May 16, 2008

JavaScript::Writer fun

The talk for my "JavaScript::Writer fun" topic. The slide is an XUL, you need Firefox browser to see it. So go get firefox.

Slide: JavaScript::Writer fun

Sunday, April 13, 2008

OSDC.tw 圓滿結束

以下是我在這 2008 年 OSDC.tw 裡演講所用的投影片。首先是「網頁程式還可以怎麼設計」

然後是 lightning talk 的部份。我總覺得我好像比較適合做 lightning talk。

Tuesday, April 08, 2008

"alert here" in Emacs.

When debugging javascript, sometimes it's quite helpful to put alerts. Here's a function for Emacs to insert an alert that shows current file name and line number:

(defun js-insert-alert-at-here ()
  (interactive)
  (insert (concat "alert(\""
                  (buffer-name)
                  ": "
                  (number-to-string (line-number-at-pos))
                  "\");")))

Saturday, March 29, 2008

HappyDesigner Meetup #3

我在這第三次 HappyDesigner 聚會的講題是 "SPA, JavaScript::Writer, pQuery",投影片如下,歡迎參考:

下次會在 OSDC.tw 的場子上演講「網頁程式還可以怎麼設計」,OSDC 的日期是 4 月 12、13 日。內容大概會跟這次有一小部份相關吧。會涵蓋過去幾次做網頁程式設計的一些經驗與心得。

Sunday, February 03, 2008

JavaScript::Writer + Template::Declare

I spent last 24 hours figured out a nice way to play JavaScript::Writer with Template::Declare. It was super neat. Download the this zip and check out the source code. It depends on an future version of JavaScript::Writer module that had not been released to CPAN yet, so it won't work for you. But you can see the source code in lib/JT/View.pm, line 141:

  link_to(
      "Hello",
      href => "http://google.com",
      onclick => ajax_replace( "#area", "data/hello.html" )
  );
And line 109, for the definition of ajax_replace:
  sub ajax_replace {
      my ( $target, $uri ) = @_;
      return sub {
          jQuery("#loading")->fadeIn(
              sub {
                  jQuery("#area")->load($uri)->show(
                      sub {
                          jQuery("#loading")->fadeOut();
                      }
                  );
              }
          );
          js->append("return false;");
      };
  }
It returns a Perl sub, and eventually converted to a Javascript function that work as the onclick handler. One nice feature is, although the A tag and onclick handlers are put together in Perl code, they are seperated in HTML code. All generated javascript are put to the end of body. A elements get an auto-generated ID for latter reference. And it's all kept in perl so programmer worries nothing. Now it works great with CGI::Minimal, no model code in this spike. I want to somehow make a better integration of such concept into Jifty, or Catalyst. That feels like an assignment to myself in the coming OSDC.tw and YAPC::Asia

How do a script find itself.

I admit it that I do not really dislike the idea of putting script tags directly inside body. That means I am not a xhtml strict person. But I can't understand that why it isn't put into the design (or implementation) to locate current script node easily.

What I'm try to solve can be described with this code snippet:

<p>
<script type="text/javascript">
    var this_node = get_this_node();

    var p = this_node.parentNode; // get the <p> node.
</script>
</p>

Turns out the only way around is to assign an element id to the script tag:

<p>
<script id='the-script' type="text/javascript">
    var this_node = document.getElementById('the-script');

    var p = this_node.parentNode; // get the <p> node.
</script>
</p>

This is only OK when everything is generated. Which is what I'm trying to do recently with my JavaScript::Writer perl module.

Saturday, February 02, 2008

Getting the coordination of a node in DOM.

This is a function that takes a DOM node, and returns the offset of that node. What's the "offset" ? It's the ordinal number in its siblings, the number "n" of node.parentNode.childNodes[n]. Sadly there's no easy way to do this with DOM API, basically it's just iterating over all its siblings and keep counting.

getNodeOffset = function(node) {
    var p = node.parentNode;
    if (p == null) return;
    for (var i = 0, l = p.childNodes.length; i < l ; i++ ) {
        if (p.childNodes[i] == node) break;+    }
    return i;
}

Here's one other interesting function, I called it "getNodeCoordination". Since each node must have a parent node, it can always be traced all the way up to document.body. This forms a simple coordination system. You can use a list of numbers like:

[3,0,0,1]

To uniquely locate a node. The example above can be translated into this horrible English: "The 1st child of the 0th child of the 0th child of the 3rd child of document.body". Or this elegant XPath representation:

//body/*[4]/*[1]/*[1]/*[2]

Those numbers are offset by one for obvious reason. Here's the code of that "getNodeCoordation" function.

getNodeCoordination = function(node, baseNode) {
    if (baseNode == null) baseNode = window.document.body;
    var coord = [];
    var p = node;
    while (p != baseNode) {
        var offset = getNodeOffset(p);
        if (offset == null) break;
        coord.unshift(offset);
        p = p.parentNode;
    }
    if (p != baseNode) return null;
    return coord;
}

Obviously the return value is very fragile against DOM change. Any DOM modification can invalid a previously stored coordination value. However, If you ever need to bookmark the location of a node and serialize it for storage, this is one approach.

ps. This is a cross-post from handlino.com

Saturday, December 29, 2007

jquery way to limit image size.

Find all images under current box, and limit their width to at most the same as current box.

        var w = $(this).width();
        $(this).find("img").each(function() {
            if ( $(this).width() > w ) {
                $(this).width("100%");
            }
        });

This is something similar to always wrap a div around an image. Only it's a piece of un-obstructive javascript instead of over-augmented-semantic-hack-sorting-out-bad-css-box-model.

This generally works good on Firefox, IE7. Didn't try others.

Monday, November 05, 2007

A simple javascript log console...

With jquery, it's easy to create a PRE element on-the-fly and use that for showing debugging messages. Pretty much like using alert(), only less annoying.

Setup:

    $(function() {
        $("<pre id='debug'></pre>").appendTo(document.body)
        .css({
            position: 'absolute', bottom: 0, right: 0,
            background: 'red', color: '#fff'
        });
    });

Use:

    $("#debug").text("Some debugging message here...");

Tuesday, October 02, 2007

JavaScript::Writer talk at Shibuya.pm

我在 Shibuya.pm Tech Talk #8 的場子上講了最近所寫的 JavaScript::Writer。在 ustream.tv 上有錄影(http://ustream.tv/yappo/videos/PR2xPU.f0uaa9ZCbUf56gg)。 只花了一個晚上就整理完畢,真是辛苦 Shibuya.pm 的工作人員了。這場 Tech Talk 也很有意思,天南地北的主題都有。每位講者都有各別的錄影影片。( http://ustream.tv/search/recorded/tag/shibuya.pm )

Friday, September 28, 2007

Padding zero in Javascript

To display a number x in 2 digits with padding zero in the front, here's the snippet to do so:

String("0" + x).slice(-2);

To display 5 digits with padding zeros, it'll be:

String("0000" + x).slice(-5);

The number of zero can be parameterized, of course:

var padding_zero = function(x, n) {
 var zeros = repeat("0", n);
 return String(zeros + x).slice(-1 * n)
}

The function repeat is the string repeater defined in here.

But these definitions doesn't check the original number if it's longer then n digits. Calling padding_zero(357, 2) will give you 57. Neither does it check if its parameters are numbers or not. (Easy and may not be a big issue depends on what you want.)

And of course, you can pad something other than zero. For example, you can pad up to 5 number of before . They are just two different img strings anyway:

// pad up to n Ys before X.
var pad = function(x, n, y) {
   var zeros = repeat(y, n);
   return String(zeros + x).slice(-1 * n);
}

So the code to generate a line of 5 rating stars may just looks like:

pad("111", 5, "0).replace(/1/g, star_img).replace(/0/g, empty_star_img);

The idea here is to generate something like "11100" first, then replace them with img tags.

All these functions assumes x,y variables are only one character to work properly because I use slice() function on String classes. To make it more general, should probably use Array.

Saturday, September 22, 2007

String repeat in JavaScript, and as a jQuery extension.

Repeating a string multiple times isn't as easy as in Perl that you say $str x 3. str * 3 simply gives you a NaN. So I wrote this textbook-code-example-like repeat() funciton, that takes a String and a Number, returns a new String.

function repeat(str, i) {
   if (isNaN(i) || i <= 0) return "";
   return str + repeat(str, i-1);
}
Putting it down as a jquery extension, it becomes this snippet:
(function($){
    $.extend({
        repeat: function(str, i) {
            if (isNaN(i) || i == 0) return "";
            return str + $.repeat(str, i-1);
        }
    })
})(jQuery);
It's used like this:
var rating = 3;
var star = "<img src='star.gif'>";

// Show some number of stars based on rating.
$("#rating").html( $.repeat(star, rating) )

Saturday, August 11, 2007

幾種偵錯 javascript 的方式

Firebug
這大概是在 Firefox 上的首選。主要的特點有:
  1. 以瀏灠器外掛方式的存在,可以對「任何」網站進行偵錯。
  2. 顯示的方式可以是同一視窗,也可以在不同視窗。同時用兩個螢幕寫程式時更加方便。
  3. 定義了 "console.log", "console.info" 等方法,用來印出訊息
  4. 有可設中斷點﹑步進的偵錯器
  5. 有命令列可以立刻執行任意的 javascript 運算
  6. 也可以顯示 DOM 與 CSS 的資訊
另外還有一個 Firebug Lite,是要開發人員自行在 HTML head 裡面加入 <script> 的。在 Firefox﹑IE﹑Safari 上都可以用。但不如外掛版來得方便。而且,顯示方面偶爾會有問題。
Javascript Shell
是在 Firefox 上的 Bookmarklet,要拖到工具列上使用,會彈出新的視窗。新的視窗可執行任意的javascript運算。
Javascript Shell on IE
前述 Javascript Shell 的 IE 版本。有一陣子這是我唯一能夠使用的 javascript 偵錯工具 。
IE Developer Toolbar
微軟官方出的 IE 工具列。這個其實沒有辨法拿來偵錯 Javascript,只能拿來觀察目前的 DOM 而已。就算是這樣也算是不錯的用處。
Safari Debug Menu
把 Safari 的 Debug Menu 打開之後,可以看到裡面有個 Javascript Console。上面會顯示出在 javascript 程式碼中呼叫 console.log﹑console.info 所印出來的訊息,印訊息的函式與 Firebug 相容。但只有訊息。簡單的說就是只能用 print 來 debug 的方式。(其實這也是一種不錯的方式啦)。
Jash
最近才發現的另一套 Javascript Shell。功能跟 Firefug 一般完整。並且是以 Bookmarklet 形式使用。最棒的是,可同時在 Firefox 與 IE 上使用,還可以在 Safari 3 上面使用。這一套的 javascript console 做得也很完整,可以執行 javascript 運算式。而且跳出來的視窗可以隨意拖放。比起 Firebug lite 來說,我會選用這個。
ExtJS
ExtJS 是一套非常完整的 UI 函式庫。其中有附一套精美的 Javascript Console,與 Firebug 相容。在 IE 上也可以使用。如果說有專案會用到 ExtJS 的話,就可以用它進行偵錯。

基本上,如果沒有 Jash 的出現,最難進行偵錯的環境是 IE 瀏灠器。有一陣子我甚至是使用 alert() 來找出錯誤發生的點。此外,在 IE 上要進行偵錯的話,把所有用到的 javascript 全部包成一個檔案會比較方便。為何?因為 IE 本身所提供的錯誤訊息,雖然帶有行號,但是沒有告訴你是哪一個 javascript 檔案。而且,那行號跟實際發生錯誤的行號差一。把全部的 javascript 都包成一個檔案的話,這個資訊才有用。當然,使用如 Jash 這般好工具的話,便可以輕鬆多了。

你問我為什麼要在 IE 上進行偵錯?因為有一堆問題只在 IE 上發生,這世間就是這麼殘忍阿(笑)。

Sunday, August 05, 2007

jsmin

My ~/bin/jsmin:

#!/usr/bin/env perl
use JavaScript::Minifier qw(minify);
undef $/;
print minify(input => <>);

JavaScript::Minifier works pretty well. This is used when I'm making opcafe website, I minimized the js lib like this:

opcafe-lib.js: jemplates.js
cat Jemplate.js JSAN.js DOM/Utils.js jemplates.js jquery.js interface.js jquery.rotate.js | jsmin > $@

Sunday, March 18, 2007

How I Shopping with javscript shell bookmarklet

HeyShopping produce this I'm a Mac T-shirt for a while and now I decide to buy one. However, when I click the "Add to cart" item, it pops me this javascript error:

Error: missing ) after argument list
Source File: javascript:add_to_cart('3729','I'm a Mac (XL%E8%99%9F)','399',myform.buy_number_3729_2)
Line: 1, Column: 22
Source Code:
add_to_cart('3729','I'm a Mac (XL號)','399',myform.buy_number_3729_2)

Ok... looks like somebody doesn't handle string quoting at all. So what should I do now ? Contact them to fix this bug ? No. I hit the "shell bookmarklet" that has always been there on my Firefox personal toolbar, and type:

add_to_cart('3729',"I'm a Mac (XL號)",'399',myform.buy_number_3729_2)

Right, just change the bad string in the second argument to use double quote, and call that function. Alrighty, now the T-shirt is in my cart!

Ponder, didn't they ever wondering why the T-shirt doesn't sell as well as it should be ?

Saturday, March 17, 2007

Widget.Lightbox 0.09 hits JSAN.

Widget.Lightbox 0.09 released..

Widget.Lightbox is an objective re-implementation of Lightbox JS (http://www.huddletogether.com/projects/lightbox/). It has several nice features:

  • Requires no extra image files
  • Requires no extra CSS files and rules
  • Optionally supports script.aculo.us effects library.
  • Optionally supports JSAN effects library.
  • Works on IE, Firefox, and Safari.

It's loaddable by JSAN, but not necessary. You can install this library following standard JSAN distribution installation.

Additional nice features:

  • Reentrant prevention. Friendly to programmers.
  • Customizable background color and opacity
  • Customizable callback when the box is shown / hidden
  • Can create necessary HTML on-the-fly, or using existing ones in the document.

Tuesday, March 13, 2007

Blogger's Markdown User-script

hlb這個作品修改了一下,接上showdown,效果不錯。原本就熟悉 markdown 的人,於是可以使用 markdown 來在 blogger 上寫文章了:hlb's blogger markdown

不過這東西需要使用 GreaseMonkey,也就是需要 Firefox 才可以使用。

使用 Safari的人,雖然可以裝 CreamMonkey來替代 GreaseMonkey,不過實際試過之後,無法成功地在 Blogger 寫文章的畫面中看見 toMakrdown 的連結,也就是說,不管用。

My Bicycle Rides