Thursday, 5 May 2011

Unset function in Javascript

Here's my version of an occasionally required function, Unset(). I wrote this before I found the version on phpjs.org so I thought I might as well publish it online because it's easier to make sense of than the one they wrote.

To briefly explain how it works:

There are three different things that you might want to "unset" in javascript - 1. Individual array elements, 2. a property of an object (which could be a variable, function or an object) and 3. a normal variable, which actually may hold a simple value like 1 or more complex items like an array or an object reference/definition. Each one of these different types of variable are unset in a different way:

1. myarray.splice(index,1);
myarray is the name of an array. index is the index number of the item in the array starting from 0. And the second argument (1), is the number of items to splice/cut out of the array.

2. delete myclass.myproperty;
This simply deletes the variable myproperty from the object myclass. Of course, in javascript, myproperty could contain a simple value, a method or an object.

3. myvar = undefined;
If I've previously defined a variable like so: var myvar = "hello"; then I can undefine it by setting it to the javascript equivalent of null which is "undefined". You can also unset a whole array/object using the same command.

Anyway, here's my general purpose javascript unset() function:

/**
* Unset variables, objects, array elements and object 
* properties in Javascript much like you can in PHP
* @author Ahmad Retha
* @license Public Domain
*/
function unset()
{
    for(var _i = 0; _i < unset.arguments.length; _i++){
        //where item to unset is an array element (var[index])
        if(_m = unset.arguments[_i].match(/(\w+)\[(\d+)\]/)){
            eval(_m[1] + ".splice(" + _m[2] + ", 1);");
        //where item to unset is an object item
        }else if(unset.arguments[_i].match('.')){
            eval("delete " + unset.arguments[_i] + ";");
        //where item to unset is a normal variable
        }else{
            eval(unset.arguments[_i] + " = undefined;");
        }
    }
}

You pass the names of the variables, classes, elements of arrays and object properties as strings and it removes them. You can pass as many arguments to the unset() function as you like. Usage example:

var x = 1;
var y = ['a','b','c'];
var z = {'one':1, 'two':2, 'three':3};

unset("x", "y[1]", "z.three");

Variable x is now undefined. Array y now holds two elements, a and c. Class z is now an object with two properties.

Friday, 29 April 2011

Javascript using PHP functions

Ever wanted to use functions easily available in the PHP library but with Javascript?

I found a new project called the PHP-JS project and it's pretty cool. They have covered most of the PHP functions and written some really good Javascript. The other day I needed a snippet of Javascript code to Uppercase the first letters of new words, which is the ucwords() function in PHP. Here's their code:

function ucwords (str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}

So to use it I write:

//Capitalizes the words to 'The Cat Sat On The Mat'
alert( ucwords('the cat sat on the mat') );

Nice. Visit the site at http://www.phpjs.org/.

Saturday, 23 April 2011

PHP array to Javascript array format

Just been messing around with ajax and a particular jQuery plugin... The easiest way to convert a PHP array to a Javascript array is to use the json_encode() function (PHP 5.2+).

<?php 
echo json_encode(array("One","Two","Three"));
?>

This will output the Javascript array notation:

["One","Two","Three"]

If I use an ordered map array like this:

<?php 
echo json_encode(array("1"=>"One","2"=>"Two","3"=>"Three"));
?>


It will convert it to a Javascript object:

{"1":"One","2":"Two","3":"Three"}

Monday, 4 April 2011

Bacteriophages and... introducing Virophages

Bacteriophages are viruses that infect/kill bacteria as part of their natural programming. Just like a typical viral infection may give you a sore throat, using a mechanism of infecting the cells in your throat by inserting RNA/DNA into your cells causing your body's immune system to fight back by killing the infected cells - bacteriophages infect bacteria and make them produce more of its viral clones and/or they end up killing the bacteria they infect.

We've known about bacteriophages for a long time and today we use them to insert genetically engineered fragments of DNA into cells so they start expressing the new genes. This is standard practice in genetics labs nowadays.

But up until 2 or 3 years ago we had not come across Virophages - a virus that infects another virus! How such a discovery managed to slip by silently without anyone making a big hoohah about it is crazy!

I'm only speculating that one application of gene therapy using virophages might be, and I haven't given this much thought, is to infect a genetically modified stalwart virus similar to HIV to continually produce a virus that carries a beneficial gene such as the CFTR-coding gene to help sufferers of systic fibrosis. You stick the infected virus into a human being and it starts creating the virus that carries the gene to cure the disease or at least to provide consistent and longer-lasting gene therapy.

The possibilities and applications of this discovery have great potential. Here's an article nature published a few days ago in which I first found out about virophages: http://www.nature.com/news/2011/110328/full/news.2011.188.html

As we're on the subject of microbes, I'd like to take the opportunity to publically complain about Leeds Central Library which has no books on bacteria in its catalogue! (unless they're hiding them somewhere!)

Wednesday, 2 March 2011

Donate Stem Cells today!

It seems that my knowledge concerning stem cell donation is out of date, as I discovered today. I was under the impression that you had to have a surgical operation under full general anaesthetic to extract bone marrow containing stem cells from the Iliac crest of the hip bone... not any more!

All they need to do now is give you a jab with a stimulating factor so you start releasing the stem cells into your blood stream and then they harvest them from your blood. It's almost like blood platelet donation. Saving a life just became much easier. How awesome is that?!

You can talk to someone at your local blood donation centre about donating stem cells (and blood/platelets) or get in touch with the Anthony Nolan Trust. They came to our work place today and all I had to do was fill out a form and spit in a tube so that they could get a tissue (cheek cells) sample to match against their patient database. How easy is that!

Craig Venter talks about his synthetic bacterium and future plans on TED

Sunday, 13 February 2011

How to reset/restart the position of a HTML5 audio clip

A simple google search didn't turn up with any direct results so this might be what you're looking for:

HTML:

<audio src="samples/brutaldeathmetal.mp3" id="audio" controls>


JavaScript:

var aud = document.getElementById('audio');
aud.addEventListener("ended", function(){
    this.currentTime = 0;
    this.pause();
});

What this does is it sets the playtime back to zero seconds when the audio clip ends.

Among the many javascript functions and properties of this tag you can use .play(), .pause(), .ended, .paused, and .duration to manipulate it. And you can even set the .currentTime property to a number within the range of your clip's playback duration (in seconds) to start midway through the clip if you wanted.

HTML5 Video and Fullscreen

I've just been experimenting with the HTML5 video tag and just realized that neither Google Chrome nor Opera allow you to fullscreen the video (OGG) but Mozilla Firefox does if you right-click the video and select Full Screen...

And what of Internet Explorer 8? It doesn't even render the CSS properly, let alone the video!

I found this great article that shows a code sample of how you would implement captions/subtitles/other based on the position in the video. Pretty cool no? http://randallagordon.com/blog/2009/07/19/jaraoke-html5-audio-tag-demo/

Thursday, 10 February 2011

JQuery Hover Effect on Current, Previous and Next elements

I created this simple effect with JQuery and a little bit of CSS. What is does is if you move your mouse cursor over a link it calls the .hover() function and then it applies a class style using .addClass() to the element you hovered over with the mouse and in addition to this is applies a style to its adjacent neighbours using .next() and .prev() to select the links to which to apply the style.
 

The code is really simple. First off, you use a hover function. The first argument you pass to it is what to do when the mouse hovers over the element. I use .addClass() to apply a style to the element being hovered over ($(this)). The next argument to pass to the function is what to do when the mouse moves off the element and I use .removeClass() to reset the style of the element back to how it was. I encapsulate the arguments in anonymous functions.

In order to access the elements adjacent to that being selected you can use the .next() and .prev() functions, so if, for example, I had a list of 3 items and was hovering over the second one, I can use prev() to have access to the first element and next() to access the third element. When I move the mouse to highlight the first element, there is no previous element so it doesn't select anything to the left but the next element is still there and is accessible. If I highlight the third element then there is no next element so it only has the previous element to select.


Anyway, here's the javascript code:

$(document).ready(function(){
    $('a.link').hover(
        /*Carry this out when the mouse hovers over the element*/
        function(){
             $(this).addClass('bigger');
             $(this).next().addClass('big');
             $(this).prev().addClass('big');
        },
        /*Carry this out when the mouse moves off the element*/ 
        function(){
             $(this).removeClass('bigger');
             $(this).next().removeClass('big');
             $(this).prev().removeClass('big');
        }
    )
});

Now, the CSS to align the elements when the font size got bigger was not straightforward. One would assume that you need to use a combination of vertical-align:middle and display:table-cell or display:inline-block but these didn't do what I wanted. In the end I found the best way to solve the problem was to give the container element (div) a height and then use a large line-height, a large margin-top and text-align:bottom to allow the text to get bigger and not interfere with the content above or below it:

div {height:1.2in; width:100%; border:1px solid black;}
a {margin-top:50px; vertical-align:bottom; line-height:100px; text-decoration:none;}

You can download the code here: http://www.mediafire.com/?kydzwwl4bb4ogjk

And it's under the public domain license so you're free to do what you like with it.