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.

Sunday, 6 February 2011

Drupal error - warning: Cannot modify header information

Upon uploading my site from the local to the remote server an error (warning) was received when attempting to run update.php. If I ignored the warning and continued using the site I would get a blank white page every now and again on the administration pages although it did carry out the requested operation. I was having none of it and it was something that needed to be solved.

The error message I got:

warning: Cannot modify header information - headers already sent by (output started at /home/{username}/public_html/drupal/sites/all/modules/{modulename}/{modulename}.module:1) in /home/{username}/public_html/drupal/includes/common.inc on line 148.

It took a while to figure out what the problem was. The first thing to say is that the line and file number it says is causing the problem usually is the file and line number causing the problem. So I opened up the custom module I'd written and here was what it had in the first two lines:

<?php
// $Id$

Nothing strange about that. And there was no white space preceding the opening of the php code tag.

To cut a very boring story short, the problem turned out to be that I'd saved the file as UTF-8 and before the opening tag the text-editor had stuck in an invisible UTF-8 marker character which was being sent to the browser before the headers and thus causing the error.

The solution is to change the text file to ASCII (or ANSI as some text-editors call it) or find another way to remove that preceding character(s?) and if any preceding characters show up in the ASCII file then delete them and save the file.