Javascript tests and scripts
There are 23 articles published in this category. Please try the search if you can't fint what you're looking for.

Kukk3D - Javascript 3D Engine

Thursday, April 30, 2009

I had so much fun playing around with canvas when I built the Pixastic Editor that I decided to port my really old 3D-engine, Kukk3D, to JS.

Click the image to view a demo

At the moment it's really basic even though it has support for faces (something that the old one never had) as well as lines and vectors.

You can add any type of object you like to the scene, move it around and re-render it. To animate you'd wanna do this X times per second, usually through a setTimeout.

A basic example:

<canvas id="kukk3d"></canvas>

<script type="text/javascript">
// Initiate the engine, pass in the canvas-ID and set width and height
Kukk3D.init('kukk3d', 640, 480);

// Create an object
// You can create any object you like or use one of the presets in objectSkeletons
var cube = Kukk3D.addObject(Kukk3D.objectSkeletons.cube());

// Now that the scene contains something, let's render it
// You can pass in a color-object as the only argument to render
// in order to fill the scene with a background-color
Kukk3D.render({r: 0, g: 0, b: 0, a: 1});

// To animate we simply move about the object and re-render
// the scene in a setInterval that runs every 50 ms
setInterval(function () {
    cube.rotation.y += 2;
    cube.rotation.z += 1;
}, 50); // 50 ms = 20 fps

What you reckon?

jQuery Drag to Select Plug-in

Monday, April 06, 2009

Use this plug-in to allow your visitors to select certain elements by dragging and dropping a "select box".

jQuery Drag to Select

It works very similar to how most OS:es allow you to select files and folders.

I've set up a simple demo, please check the source-code for the different options. It's still in semi-beta.

All my plug-ins will be re-released on once it's finished (right now I'm pretty much just waiting for PHP5.3 to be released).

A follow-up to "An alternative to div overlays"

Friday, February 13, 2009

"Cancel Bubble" pointed out in my previous post one thing that I hadn't thought of; users can still interact with the page behind when you don't use an actual element to cover it.

So, to solve this, but still use the same .dimmed-class on body, I simply added an empty div-element to body using JS:

.... code ...
<script type="text/javascript">
var div = document.createElement('div'); = 'body-overlay';

And styled it, too, under body.dimmed:

#body-overlay {
    background: #000;
    opacity: .8;
    z-index: 1;

    position: fixed;
    left: 0;
    top: 0;

    display: none;
    width: 100%;
    height: 100%;

body.dimmed #body-overlay {
    display: block;

Together with the .dialog-styling I still only need to switch body's class to display a centered, modal dialog on top of a (now) non-interactive, dimmed page.

IE6 won't understand position: fixed; but I'm one of those that no longer care about IE6.

An alternative to DIV overlays

Tuesday, February 10, 2009

When displaying a modal dialog it's pretty common to dim the rest of the page to focus the user's attention on the dialog in question.

A common way to solve the dimming is to overlay the entire page with a 100% wide, 100% high div-element with a little opacity and then display the dialog on top of the overlay.

Recently at work I tried a different aproach for solving the dim and it worked out quite nicely.

Instead of overlaying a semi-transparent div on top of the page I instead made the actual page semi-transparent and simply changed body's background to something a little darker.

The semi-transparent #wrapper and darker body are both styled under body.dimmed so whenever I need to dim out the page I simply give body a class of "dimmed".

The benefit here is that you don't need to play around with JS to create a div that always covers the entire viewport in every browser but instead you simply toggle a class-name on body.

Benefit number 2 is that since everything on your page (including the dialog) are contained within the body-element they too can be styled differently when body is dimmed and when it's not.

So the simple CSS turns out something like this:

/* Normal styling */
body {
    background: #369;

#wrapper {
    background: #fff;
    width: 960px;
    margin: 0 auto;

div.dialog {
    background: #fff;

    display: none;

    position: absolute;
    left: 50%;
    top: 15%;

    width: 400px;
    margin: 0 0 0 -200px;

/* Dimmed styling */
body.dimmed {
    background: #111;

body.dimmed #wrapper {
    opacity: .1;

body.dimmed div.dialog {
    display: block;

As you can see all you need to do now to display a centered dialog on top of a dimmed page is to give body a class of "dimmed". With jQuery it couldn't be easier:

$('<a href="#">toggle dialog</a>').appendTo('#content').click(function() {

Happy coding!


Live ajax search using the Google search API

Monday, May 19, 2008

I realized the bogus-search-results script from Live Ajax Search jQuery Plug-in may not have been very satisfying to you visitors, so I thought I'd show you how to use the Google search API to create a real live ajax search on your site.

This example requires PHP and if you're running any version below 5.2 you'll need Michal Migurski's JSON-class as well.

The PHP (and HTML erm..)

The Google search API is basically just a URL you pass a search-query to and it returns a JSON with results.
I won't go in to too specific details about the API, if you wish to know more please refer to the documentation.

Create a search-results.php file and put the following code in it:

require_once 'JSON.php';

# Your site URL
$site '';

# Make sure a search-query was entered
if(isset($_GET['q'])) {
# Are we on the first page?
$start = isset($_GET['start']) ? $_GET['start'] : 0;

# The URL to the Google search API
$url '' .urlencode($_GET['q']) .'%20site:' .$site .'&rsz=large&start=' .$start;

# Initiate CURL
$ch curl_init();
curl_setopt($chCURLOPT_REFERER'http://' .$site);
$body curl_exec($ch);

# Decode the JSON returned (you need the JSON-class if json_decode is undefined)
$body json_decode($body);

# Build array
$i    0;
$search_results = array();

# Loop through all results
foreach($body->responseData->results as $r) {
$search_results['results'][$i]['title'] = $r->title;
$search_results['results'][$i]['url'] = $r->url;
$search_results['results'][$i]['content'] = $r->content;

# Loop through all the pages of results
if(isset($body->responseData->cursor->pages)) {
$body->responseData->cursor->pages as $p) {
$search_results['pages'][] = $p->start;

# Make sure some results were returned
if(isset($search_results['results'])) {
        <h2>Search results for &quot;<?php echo @$_GET['q']; ?>&quot;</h2>

        <ol<?php echo @$_GET['start'] > ' start="' .($_GET['start'] + 1) .'"' '' ?>>
        <?php foreach($search_results['results'] as $sr) { ?>
                <h3><a href="<?php echo $sr['url']; ?>"><?php echo $sr['title']; ?></a></h3>

                <p><?php echo $sr['content']; ?><br /><a href="<?php echo $sr['url']; ?>">Read more</a></p>
        <?php ?>

        <?php if(isset($search_results['pages'])) { ?>
            <?php $i 0; foreach($search_results['pages'] as $p) { $i++; ?>
                    <?php if((!isset($_GET['start']) && $p == 0) || (@$_GET['start'] == $p)) { ?>
                        <strong><?php echo $i?></strong>
                    <?php } else { ?>
                        <a href="/search/?q=<?php echo @$_GET['q']; ?>&amp;start=<?php echo $p?>"><?php echo $i?></a>
                    <?php ?>
            <?php ?>
        <?php ?>
    else {
            <p><strong>Sorry, there were no results</strong></p>

As the search-results.php-file doesn't contain any DOCTYPE, html, head or body-elements it is obviously not valid HTML. How you implement the search-results on your own site differs depending on what type of site-structure you've got set up. Regardless you should probably be able to figure it out.

If you do include some sort of head/foot-templates in the search-results make sure not to include them if it's an ajax-call (isset($SERVER['HTTPXREQUESTEDWITH'])).

I'm going to assume the search-results.php will be included from a search.php-file in the root of your site. So visiting /search.php would display the search-results (provided a query is set) along with whatever else your site consists of, but visiting just /search-results.php will only output the results.

The HTML form

Now all you need to do is set up a form that submits a get-request to search.php:

<form method="get" action="/search.php">

        <label for="q">Search</label> 
        <input type="text" name="q" id="q" /> 
        <input type="submit" value="Find" />


The Ajax-magic

And now hijax that form:

<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript">
    $('#q').liveSearch({ajaxURL: '/search-results.php?q='});


I've set up an example-page and you can also download the example-files.



Seems curl_init isn't available from my host (bummer). The example should still work for you locally though,and hopefully live as well (unless you suffer from the same limitations).

jQuery Live Ajax Search Plug-in

Friday, May 16, 2008

Use this plug-in on an input[type="text"] and it will display search-results based on the input's contents on key-up.

The search-results box is fully customizable using CSS and its contents is completely up to you.

I've set up a simple example with some bogus search-results.

You use it like:

$('input[name="q"]').liveSearch({ajaxURL: 'my-search-results.php?q='});

The ajaxURL-parameter should point to your back-end search-results. Whatever you see when you visit that address in your browser will be put in the search-results div.
If you don't use $_GET['q'] for the search-query you need to change the "?q="-part to, for example, "?searchTerm=".

The bogus-search-results.php-file used in the example looks like this, but yours can look however you want.

<h2>Search results for &quot;<?php echo @$_GET['q']; ?>&quot;</h2>

    <?php for($i 0$i 10$i++) { ?>
            <h3><a href="#">Lorem ipsum <strong><?php echo @$_GET['q']; ?></strong> lorem</a></h3>

            <p>Lorem ipsum dolor sit amet lorem <strong><?php echo @$_GET['q']; ?></strong> ro the lorem in lipsum dolor sitamus <strong><?php echo @$_GET['q']; ?></strong> lorem ipsum?<br /><a href="#">Read more &raquo;</a></p>
    <?php ?>

You can as usual get the code and the default styling from google code. Have fun. Oh, and it requires dimensions.

Numeric DLs jQuery Plug-in

Monday, March 31, 2008

This little plug-in will add numbers to definition-descriptions (<dd>) if there are more than one for a term (<dt>).

Take this code for example:

    <dd>A small pitcher.</dd>
    <dd>Vulgar Slang. A woman's breasts.</dd>
    <dd>The animal of the skies</dd>

Using the plug-in (like so: $.numericDLs();) would result in the following output:

(1) A small pitcher.
(2) Vulgar Slang. A woman's breasts.

The animal of the skies

Perhaps this could be done with pure CSS? Counters and generated content perhaps..

You can as usual get the code from my Google Code repository. Have fun!


Tobias mentions a CSS-solution in the comments and after some playing around I managed to make it identical to the JS-one:

dl dt {
    counter-reset: i;

dl dd + dd, 
dl dd ~ dd:not(:last-child) {
    counter-increment: i;

dl dd + dd:before, 
dl dd ~ dd:not(:last-child):before {
    content: "(" counter(i) ") ";

Only real browsers though obviously.

jQuery Vibrate Plug-in

Thursday, March 27, 2008

This simple plug-in makes elements on the page vibrate.

I built it for a project at work and to be frank I think this sort of stuff is no better than the 90s blink-element but perhaps someone will find it useful.

Use it like:


Get the code here

Enjoy.... or not..

jQuery external link favicons plugin

Wednesday, February 27, 2008

Inspired by "the CSS Guy's" Hyperlink Cues with Favicons I created a jQuery plug-in that does the same.

What it does is appends favicon-images (if there is one, else a default image will be used) to all external links on the site.

It's mega-tiny (like 20 lines of code (less than a k unpacked) and you use it like:


You can check it out in action here and get the code from my google code SVN repository .


jQuery Image Zoom Plug-in

Monday, February 11, 2008

Inspired by Cabel Sasser's FancyZoom I created my own version for jQuery.

It's pretty much the same only I skipped the shadows for incapable browsers (completely relying on box-shadow) but in contrast it's only about 90 lines of code (compared to a whoppin 761+318 that is FancyZoom), and it hopefully won't mess with your other JS as it's all wrapped in the jQuery-object and doesn't use any global vars. Imgzoom also validates in JSLint, so compression isn't be a problem (around 1k compressed).

Instead of the typical $('selector').plugIn()-jquery-plugin this one is run through $.imgzoom(); and, like imgbox and FancyZoom, applies to all links that points to images.

You can not, however, avoid zooming images using the rel-attribute, as you can with FancyZoom, and imgzoom does not group images or add any type of navigation the way imgbox does.

Imgzoom uses event bubbling rather than "hard-coded" events on anchors. This way dynamically inserted images (ajax or not) will also open in the imgzoom plug-in.

Have a look at the example-page and get the source here. Imgzoom requires the dimensions plug-in for jQuery.
The default styling for imgzoom can be found here and you'll need this icon as well:
Close imgzoom


Javascript compression PHP class

Monday, January 21, 2008

In addition to my CSS compressor and constants parser I've also written a very simple Javascript compressor class that uses Nicolas Martin's PHP port of Dean Edward's Javascript packer.

It works in exactly the same way as the CSS-compressor. Create a new instance, pass the directory(ies) you want to look for .js-files in and then call the pack-method.

$jsc = new JSCompressor('js/');
echo $jsc->pack();

Reducing the number of HTTP requests the browser needs to make is essential for performance. Together with full packing of all the code, file-size is often reduced by up to 70% and the number of HTTP requests always down to 1.

Download the demo and have fun!

jQuery Imgbox Plug-In

Monday, November 26, 2007

I'm working on a new version of this which will eventually show up on - In the mean time, please check out my image zoom plug-in. The code for the imgbox has been removed.

This plug-in will make any link pointing to an image (png, gif, jpg or bmp) open in the "Imgbox". The Imgbox centers on screen and displays whatever image the link was pointing to, together with the link's title, the image'a alt-attribute and a list of all other images in the same scope.

This way you can use imgbox to create "albums" of images by simply applying the imgbox to different sections of your site.
Say for example you have "Random Images" and "Holiday Pictures"-sections on your site, each wrapped in its own div, then you can use the imgbox to group each set of images like this:

$('#holiday-photos, #random-images').imgbox();

Do not target the links themselves as imgbox looks for links inside the element you tell it to.

It requires jQuery and my center plugin for jQuery and you can get the code here. The default styling of the imgbox can be found here but it's very easy to apply your own styling using the default as a guide.

jQuery Color Picker Plug-In

Friday, November 23, 2007

A simple colour-picker plug-in for jQuery. Use it like this: $('select[name="colour"]').colourPicker();

Where the XHTML looks like this:

<form method="post" action="">
        <label>Select a Colour<br />
            <select name="colour">
                <option value="ff0000">Red</option>
                <option value="00ff00">Green</option>
                <option value="0000ff">Blue</option>

And the colourPicker plug-in will turn the select in to a normal input[type="text"] and add a colour-picker icon to the right of it. Clicking the icon will bring up a dialog box allowing you to select any of the colours that were present in the select-element.

You can check it out in action here.

It requires jQuery and you can get the code here. The default styling of the colour-picker can be found here but it's very easy to apply your own styling using the default as a guide.

And as a bonus, here's a little PHP-function that will generate a list of "web-safe" colours:

function gwsc() {
$cs = array('00''33''66''99''CC''FF');

$i=0$i<6$i++) {
$j=0$j<6$j++) {
$k=0$k<6$k++) {
$c $cs[$i] .$cs[$j] .$cs[$k];
"<option value="$c">#$c</option>n";

Use it like this:

<select name="colour">
<?php gwsc(); ?>

Enjoy, and do leave some feedback.

jQuery Center Plugin

Tuesday, November 20, 2007

Here's a simple plugin you can use to center elements on the page.
To center an element you go: $('#my-div').center();

As center() uses position: fixed; to center elements there is no IE6 support.

Get the code here
As usual it requires jQuery.


jQuery Equal Height Elements Plugin

Sunday, November 11, 2007

This plug-in will make every matched element equal height by adjusting their min-height properties. Any padding/border will be taken in to account but this plug-in is not compatible with IE6 as it lacks support for min-height.

To make #content and #sub-content equal height you simply go: $('#content, #sub-content').equalHeight();
It's best to run equalHeight() on window.onload rather than $(document).ready() so that all images are loaded before the height is calculated.

It requires jQuery and you can get the code here.


jQuery Full Width Navigation Plug-in

Friday, November 09, 2007

In the (not so distant, hopefully) future, creating full width navigations will be a piece of cake using display: table, table-row and table-cell, but until certain browsers get up to speed with CSS here's a plug-in you can use to make any navigation created with the HTML-elements ul li and a full width.

Full Width Navigation jQuery Plugin

A Lot Going On

Tuesday, October 30, 2007

You may notice it's been kind of quiet here for a while.
That's because during the past few weeks I've been busy moving from Stockholm (and Web Guide Partner) to London (and Yahoo!).

I've also been working quite a bit on the site, both back-end, front-end and on a new design.

Green Twigs

Ajax/Hijax Rating Exempel

Wednesday, April 18, 2007

jQuery Image Viewer Plugin

Wednesday, February 28, 2007

Please check out the improved version of this plugin, "imgbox". The code for the ImageViewer has been removed.

Here's a simple "image-viewer" for jQuery.
It's quite similar to lightbox only probably not half as advanced.

Usage is quite simple, simply go $('#image-container').ImageViewer(); and all images that are children to #image-container will now "pop-up" in the image viewer.

All images in the same scope (in this example the #image-container div(?)) will be navigatable from the image-viewer.

There may be plenty of bugs and ways to optimize, but it works ok and i'm fed up wiv working on it for now.

Check our the example page for source code and... examples.


I've created a tiny version of the image-viewer that's not as buggy as the big one. The previous one had problems in everything but FF it seems, but this one's been tested in FF, Opera and IE6 (should prolly work fine in 7 as well).

The new version does not include any image-navigation though, and is triggered on anchor-elements with a class of "pop-up".

Check out the example page for the code...

Update 2

Well, i fixed the original, "big" version. It's been tested in Opera, FF and IE6. For some weird reason it doesn't work properly in Opera when used on my site. On the example-page it works fine though, so it must be some other JS i'm using that's fucking with it.

Anyway, check it out.

Content Flipper Javascript Function

Wednesday, February 28, 2007

Note: This code was outdated and quite shit so I've removed the example page. Check out my jQuery Paginate Plugin instead.

Created this at work recently.
It's a function you can use to add a navigation bar to the bottom of a div, containing other divs, and with it you can navigate through the divs with back and forward buttons.

It's very similar to normal tabs, only instead of tabs there's a nav-bar.

Completely Unobtrusive jQuery Tabs

Monday, February 26, 2007

As i've mentioned before i've started using quite a lot of jQuery, and some of its plugins.
Among them the Tabs-plugin by Klaus Hartl.

It's an amazing plugin that is extremely easy to use and works very well. What annoyed me a bit was the fact that it requires you to put an unordered list at the top of all you tab-content, with links pointing to all the tab-content-containers.
To me it seemed that list was completely unnecessary if javascript was disabled (i mean, it's not like people don't know how to use the scroll).
So i though, fuck, I'll generate the list from javascript.

So here you have it, a completely unobtrusive tabs-plugin (that uses the normal tabs()-plugin).

The titles in the tabs are generated from:

  1. The title-attribute of the div it is pointing to
  2. Or, the first heading in the div
  3. Or, the id of the div, str-replaced so it looks a bit nicer (this asumes you use foo-bar syntax for naming IDs and classnames)

The list is automatically inserted before the FIRST tab-content (the first div).

Check out the example and have a look at the source for the erm.... source.

Oh yea, the main reason i created this is cus i've been thinkin about tabbing my sub-content in future designs, and now i can do that without having to change the XHTML. Luvely Jubbely.

Update: If you don't want to add title-attributes to all your divs in your (x)html-code, you can very easily use javascript to do it instead.
Before executing the AutoTabs() function, do something like this:
$('#id-of-div').attr('title', 'Whatever you want the tab to say');

Fade an Entire Design Using jQuery

Saturday, February 17, 2007

I've been using jQuery lately at work to create some pretty cool effects and tabs, and I must say I'm starting to like it more and more.

I had an idea to morph a website's design from one to another, so i created this little test (Click anywhere on the page to fade to the other design).
It didn't turn out exactly as cool as I first had hoped, because all I really do is fade out body, change its class and fade it back in.
You could however potentially animate every CSS attribute that differs in the two design, and create a really fuckin neat morph.
I could not be arsed though, cus that would mean putting all the CSS in the js-file.

Also the fade is a bit sketchy. I don't understand why the "Round" design jumps up and down like that, but i guess it's something i have to live with.

I can't use this on my style-switcher though, because changing a style on my site not only changes CSS attributes, but includes other JS-files etc.
And also i can't be arsed to go through every design i've made and put a in front of every selector.

Anyhoo, check it out.

Edit: i just realized that instead of changing the class of the body (and having to use in the CSS) one could simply change the href attribute of the link element with media "screen".
I can't be bothered to change the example though.

Ajax Scan

Tuesday, October 03, 2006

Ajax-Scan is a php/javascript (ajax) directory-listing script. It works like "explorer"on windows.

Ajax-Scan is still a bit under construction, but when i'm happy with it i'll release the code.


Post It

From June 02 to April 23

  1. Mogrify is what you're looking for if you want to convert multiple images to multiple other images in ImageMagick
  2. Tommorrow, finally, the inFamous demo will be friggin availble on PSN!! Suweeeeeeeeet
  3. Fuck canvas is cool, I've started playing around with old 3D-shit again :)

February 2016

1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29

Recent Comments

  1. Vlad on A follow-up to "An alternative to div overlays":
    I'll try this.....
  2. Steve on jQuery Live Ajax Search Plug-in:
    This is a great script but I've got...
  3. Frank on jQuery Live Ajax Search Plug-in:
    Hey, sounds like a great plugin! I ...
  4. Andreas on jQuery Drag to Select Plug-in:
    @Paul - I didn't take into account ...

Style Switcher

The style switcher allows you to change the look and feel of
Only CSS and JavaScript are changed. The XHTML stays the same.

For more information about the styles, check the styles page.


Random Quote

T minus 10... 11 - The Dean

Random Images

Answer This!

Do you find the "scroll-pagination" annoying? (If you don't know what it is, scroll to the bottom of the first-page)

Blog Roll