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

Friday, May 15, 2009

An easy, understandable Konami Code implementation (using Javascript with JQuery)

This is just a quick post on my own Konami Code algorithm. If you haven't heard of the Konami Code, I'd like to refer you to sitepoint's article on it and Wikipedia.

My algorithm uses an array of integers, that represent the keyCodes that correspond to the Konami Code: var konamiCode = [38,38,40,40,37,39,37,39,66,65];

Furthermore it used an index: konamiIndex. This index starts at and resets to 0. If a key is pressed, the algorithm checks if that key corresponds to the konamiCode array at the position of the current index. So if the index is currently 0, a keypress will check if the keyCode is equal to konamiCode[konamiIndex] which evaluates to konamiCode[0], which is keyCode 38, which is up.

If the pressed keyCode is correct for the Konami code, the konamiIndex increments by one. If then the konamiIndex equals the length of the konami code array, we have a winner!

My code:


var konamiCode = [38,38,40,40,37,39,37,39,66,65];
var konamiIndex = 0;
$(document).keydown(function(e) {
if(e.keyCode == konamiCode[konamiIndex]) {
konamiIndex++;
if (konamiIndex == konamiCode.length) {
// You are in Konami code territory!
alert("Konami!");
konamiIndex = 0; // Reset the index
} else {
konamiIndex = 0;
}
}
});

Wednesday, August 22, 2007

Lightbox, Leightbox and my improved Leightbox

For my latest project I wanted to include a nifty 'Lightbox effect'. The original Lightbox effect however is limited to displaying images and I wanted to show HTML.. So I searched the net and came across Leightbox. Leightbox is a modification to Lightbox which allows you to easily display a piece of HTML (a DOM node actually) using a lightbox effect..

The problem with Lightbox however is the way it binds itself to click events.. You can only load a Leightbox using a click event.. I wanted to have a Leightbox appear using a timer, so I looking into the source and came up with the following:

1) change the initialize function inside the lightbox.prototype to:

initialize: function(ctrl) {
if(ctrl) {
this.content = ctrl.rel;
Event.observe(ctrl, 'click', this.activate.bindAsEventListener(this), false);
ctrl.onclick = function(){return false;};
}
},

What this does is check if the 'ctrl' variable is actually passed.. If it isn't, the function does nothing..

2) Add a new function:

initCallable: function(rel) {
this.content = rel;
},


3) You can now manually load up your Leightbox of choice by calling the following:
lb = new lightbox();
lb.initCallable('idOfDiv');
lb.activate();


Update: this technique is no longer valid or neccesary in the current Leightbox version.
New instructions:
1) Leave the lightbox.js (from leightbox) unmodified (download the latest version at: http://eight.nl/files/leightbox/)
2) Remove the class="lbOn" from your lightbox activating links
3) Create a javascript var (outside a function):
var myLightbox;

[4) Use an intialization function (i.e. body onload="initFunction"):
myLightbox = new lightbox($("IDOfActivationLink"));
(Don't forget to set the rel property of the link to the DIV's id you want to show (like you normally would with Leightbox))]

You can now use myLightbox.activate() and myLightbox.deactivate() to turn on/off the lightbox.

Tuesday, April 17, 2007

Syntax Highlighting on Blogger

Since this is a Technical Blog, concerning topics that have to do with programming mostly I wanted to add some sort of syntax highlighting library to this website. Blogger allows you do fully edit your HTML (actually XML) template, so I did the following:

  1. Looked up syntax highlighting on blogger
  2. Ended up here: http://www.sitepoint.com/blogs/2006/08/29/flickr-mysql-dba-blog/
    Note how someone states in the comments that it SHOULD be possible to add dp.SyntaxHighlighter since the template is editable.
  3. I did as instructed.. I upload the library to my personal website, and editted the template so that the files were included.
  4. I surrounded code blocks as instructed by dp.SyntaxHighligher...
The end result: I ended up with each block of code showing as one line of code, with a <br /> tag at the beginning and at the end.

What I discovered was that blogger prints a post on a SINGLE LINE. All new line are omitted (even if you didn't use 'Compose' mode, but editted the HTML directly). SyntaxHighlighter can't cope with this (expects newline characters, etc.).

Blogger, this is seriously messed up and I would REALLY appreciate native syntax highlighting support, or if that is not going to happen a way to include third party libraries and make it work properly!

Furthermore I do like to recommend dp.SyntaxHighlighter if you can't syntax highligh server side! The library is very extensive, easy to use and produces very nice syntax!

Monday, April 16, 2007

An easy way to add (web 2.0 like) tags to your posts

One of the features that is closely linked to the web 2.0 developments is the use of Tags. Tags are short phrases (/words) that describe the article they accompany. Tags are great for categorizing posts and give the reader of an article information on it's subject instantly.

You see, for Tags to be effective it would be best to minimize the variety being used. If all tags concerning programming have a tag 'programming' attached to them, we could use that tag to effectively categorize those posts. Using standard tags for posts helps us create a more structured and better organized category system. The problem however is that you can't remember all the tags you already use and you probably don't have enough room (or want for that matter) to show all the tags in a row.

Using script.aculo.us however this problem is solved very easily! First of all, if you didn't know this already, Scripaculous is an open source Javascript framework. It used the Prototype framework and it provided many graphical effects and other powerful tools to it's users. One of the things it offers is an Autocompletion class, which we are going to use to make our lives a lot easier. Basically autocompletion presents matching options while the user is typing. The user can click the options (or use his keyboard) to select an option after which the text is inserted in his input field. Go to this Scriptaculous demonstration to see what I'm talking about.

First of all we need a database that contains the tags. This database must at least contain these fields:
- id (int, primary key, auto_increment)
- tag (varchar, unique)

Then we need a table to link tags to posts:
- tag_id (int)
- post_id (int)

Next, let's set up the input page. First of all we need an INPUT field, e.g.:
<input name="tags" id="tags" value="" style="width: 300px;" type="text">

Next we need an invisible DIV that Scriptaculous will use to show it's autocompletion results, e.g.:

<div id="auto_complete" style="display: none;"></div>

Now on to the Javascript!
For the sake of easy testing, let's add a local array containing the tags that are already used on the website (the tags the autocompleter will use):
var tags = new Array('news', 'websites', 'links', 'programming', 'php', 'mysql', 'apache', 'games', 'hardware', 'holiday', 'business', 'ICT', 'music');

Be sure to add that inside a Javascript block!

Here comes the magic! Below the form field containing the tags, add the following Javascript function (inside a javascript block:
new Autocompleter.Local('tags', 'auto_complete', tags, {});

This function will add the autocompleter. It will use the INPUT field 'tags', fill the DIV 'auto_complete' with results and use Javascript array 'tags' as it's source. The {} at the end signify the options array (empty for now).

The above works! However there is a small problem with it.. It will only allow you to add one tag! After that, autocompletion won't work.. Luckily, Scriptaculous can fix that! In the empty brackets ({}) at the end, add the following: tokens: ','

Or make it like this:
new Autocompleter.Local('tags', 'auto_complete', tags,
{
tokens: ','
});

Now you can add multiple tags and seperate them using commas! How neat is that! You can also set more options (for instance partial searching, minimum characters for autocomplete to start, etc), which are described here.

Of course it's also possible to load the autocompletion tags using Ajax. I think however it would be better to render the tags array using PHP at page load, because of performance (each Ajax request takes time, while the tags won't change..).

Click here to view my demonstration page for the above!

Next is the PHP part!

I won't go into much detail here.. This part basically requires 2 steps:

  1. Split up the tags;
  2. Save each one. If they already exist in your table, only add a link from the new post to the tag, if they didn't exist add the new tag and link the post to it.
Splitting up requires a small 'heads-up': scriptaculous will allow whitespace after the seperating comma, so you need to watch out for that aswell. Here's how:

// Strips whitespace at the beginning of a string
$_POST['tags'] = ltrim($_POST['tags']);

// Splits up the tags
$tags = preg_split('/[ \t]*,[ \t]*/', $_POST['tags']);

Now all you need to to is loop through $tags and store the tags (as described in point #2). Make sure you first check if the tag already exists! If it does, only store the link from this post to the tag! If it doesn't, add the tag, then get it's id (mysql_insert_id()) and then store the post->tag link.

On great thing to do with tags is create a (Web 2.0) tag cloud!

Also be sure to check out my demonstration for the above!

Happy web 2.0'ing!

Wednesday, March 21, 2007

Gray out page with pop-up

Honestly, I don't know a better name for this technique than a page gray-out with a dialogue box pop-up (if this actually has a name, or you know a better one, please do inform me). What I'm talking about here is a technique that instantly grays-out the entire web site when you click a link, so that all your attention shifts to the pop-up that is loaded. The technique is used quite often by Web 2.0 enabled websites, so I bet that you have already seen something like it and probably thought that it was pretty cool.. That was exactly what I thought, so I tried it out and came up with a simplesolution which I want to share with you all.

A demonstration is available right here, and I suggest you load it up so you know what I am talking about! The simple (ugly) page has a neat Javascript application build in, that allows you to dynamically fill an Unordered List (UL html element). The fun part is of course the way the dialogue box is presented! After you click the link the entire page grays-out (it's not even accessible anymore) and a dialogue box pop-up is presented where you can fill in the new entry's value.

Some neat things about this solution:

  • Enter/Return key is enabled, so you don't have to (mouse) click the Add button.
  • You can press the ESCAPE button, which will close the dialogue box. If the new value field is not empty, the script will first ask for confirmation.
  • 'Focus' shifts to the pop-up (so the user can start typing right away).
  • The gray overlay always fills out the entire page, even if the resize the page later on.
  • The script is both MSIE and Firefox compatible (tested in MSIE7 and Firefox 2.0, should work in older versions as well, perhaps not IE4/IE5).
The code on the demonstration page is available for all public use, so feel free to copy it. The code itself contains plenty of documentation which should make it understandable and adaptable to your own personal needs.

Please note: this script uses the Prototype and Scriptaculous libraries, which are available for free on the respective websites.

How it is done
The most important part is the overlay. This DIV element is hidden at first, but can be made visible using Javascript. The CSS style of the element is very important:
  • position: absolute;
  • left: 0px; top: 0px;
  • width: 100%; height: 100%;
  • background-color: #666666; /* dark gray */
  • opacity: .7; filter: alpha(opacity=70); /* opacity: partly transparent */
  • z-index: 1000;
(please view the demonstration page code for more details).

The dialogue pop-up is positioned above the gray overlay, so that it is accessible and visible to the user. After the dialogue box is either submitted or closed (using the close link, or the escape button) the gray overlay and dialogue box are hidden again.