' % }
{ % assign _code = _code | replace: '', ' ' % }
{ % endif % }
The above code looks for the pre class="lineno" element, and does a search and replace on the HTML where required. To use, wrap your Liquid highlight include like so:
{ % capture _code % }{ % highlight plaintext linenos=table % }
{ % endhighlight % }{ % endcapture % }{ % include fixlinenos.html % }{ { _code } }
And there you have it, valid AMP HTML coming from Rouge. Just remember to add the required CSS back into your standard stylesheet.
Note: I have added spaces around the liquid tags to stop Jekyll getting confused when compiling. Remove these spaces when you add them to your build.
Final thoughts
AMP is fairly simple to implement, although it does come with a strict set of functional restrictions which you will need to work with for your pages to validate. There's an extensive range of components that can be used today, with more being developed and tested all the time. Time will tell on whether the extra development effort is worth it in terms of performance and usability. I've defiantly noticed a speed increase of the site on a mobile when loading over a 3G connection (although I haven't timed it to be 100% sure it isn't a placebo). I will be monitoring my analytics data closely over the coming weeks, to see if there's any data that can support a case for overall improvement. But is it the future of the mobile Web? Ask me again in 5 years and I'll tell you! It is certainly an interesting approach that you should consider investigating if you want to increase your mobile user base.
--- End: Accelerated Mobile Pages (AMP)
--- Start: Implementing a Service Worker
Published on: 22 July 2016
https://nooshu.com/blog/2016/07/22/implementing-a-service-worker/
Main Content:
I recently had the pleasure of attending FullStack 2016, an excellent three day conference hosted in London (just around the corner from where I work, which is handy). The event had five presentation streams being held at the concurrently, which guaranteed a few interesting talks for everyone. If you get a chance to attend in 2017, I highly recommend it.
The main theme I noticed running over the three days was a new development technique emerging called Progressive Web Apps (PWA). A Progressive Web App uses the latest browser technologies to bring a native look and feel to your web application. Imagine being able create a web application that performs like a native application and looks like a native application but is built on web technologies. Sounds too good to be true! No need to create multiple native applications, one for each OS; build one web application and then allow the user to "install" it so it looks and performs like it is native.
The features of a PWA include:
Add to home screen functionality
Push notifications
Responsive so flexes to any screen size
Background data synchronisation
Instant loading with the use of Service Workers
Secure loading through HTTPS (this is required for a service worker to function)
The final two bullet points touch on the key technology powering PWA's: Service Workers.
What is a service worker?
A service worker is essentially a proxy that sits between the browser and the network. It allows us as developers to intercept network requests, manipulate and respond to them in a way that is advantageous to our application.
The big difference between a native application and a web application is that a native application is primarily based offline. If there's no network, the experience may be very limited depending on the app developer choices, and you may not get the most up-to-date data, but you still get some sort of experience. However if you have no network connection with a web application...well you have no web application. You will most likely just get a blank error screen saying no network available. A very poor experience for the user.
This is where a service worker can help us, allowing us to create an offline experience by caching key assets that can still be accessed by the application. Once configured a service worker will step through to following stages:
Register - Register a service worker with the browser, it doesn't do anything yet but it is now available for configuration
Install - On install the service worker can pre-cache any assets required for the offline experience
Activate - With the service worker now active it can begin to monitor network activity and manage the cache state
Fetch - The fetch event is fired every time a request is made. Here we can manipulate responses and hook into the pre-cache from the install event
Offline-first
This is where we as developers need to start thinking "offline-first". Ask yourself, If your web application suddenly disconnected from the network, but you still had access to online assets, what functionality would be useful to the user? Some thoughts I've had around this are:
Latest x number of blog posts or press releases
Contact information and map to your office location
A simple game to keep the user occupied
A promotional, or just entertaining video (depending on size)
If the site is down, pull in a status feed from Twitter for example
A simple offline page mentioning they have connectivity issues
The list of creative uses for an offline page is endless, it really depends on your user demographic and the time you are willing to spend crafting them.
Think performance
Service workers don't only improve a users offline experience, they can also improve their online experience too by way of performance. The fetch event gives a developer the power to monitor requests and craft custom responses back to the browser. What this allows us to do is look to see if a particular file is in the cache, and if it is serve it back from disk. If it isn't in the cache it will request it from the network as per usual. Serving an asset from disk will always be quicker than a network request, so if you choose your assets wisely you can minimise the amount of new data being fetched on each page load. Just think of it as a browser cache that we have complete control over!
I've implemented a very simple service worker on this blog. If you open your browser developer console you will see a console info message stating that the service worker has been registered (assuming your browser supports them). To see it in action try disconnecting from your network and refresh the page. You should see a very basic offline page stating you have network connectivity issues. If you want to drill down into the inner workings of the service worker you will need Chrome Canary (version 54 at the time of writing). This version will give you a brand new application tab where you can view the active service worker and its cache.
Implementation
If you want to take a look at the full service worker JavaScript I've used it is available here. The script borrowed heavily from the following resources:
Service Worker Sample: Custom Offline Page Sample
A simple ServiceWorker app
I've split the script down into the separate stages below with a brief set of comments for explanation.
Register
Add the following code to your HTML pages.
// check see if your browser supports service workers
if ('serviceWorker' in navigator) {
navigator.serviceWorker
// register the service worker script
.register('/sw.js')
// using promises tell us if successful or there was an error
.then(reg => {console.info('Service Worker registration successful: ', reg)})
.catch(err => {console.warn('Service Worker setup failed: ', err)});
}
Install
The code sections below sit inside the service worker JavaScript file (sw.js).
self.addEventListener('install', (event) => {
// extend the events lifetime until the promise resolves
// SW won't be considered installed until all caching is complete
event.waitUntil(
// resolve the cache object that matches the name
// it is created if it doesn't exist
// return a Promise once resolved
caches.open(cacheNameStatic)
.then((cache) => {
// add all the following resources to the cache
return cache.addAll([
OFFLINE_URL,
FOUR_OH_FOUR_URL,
'/css/styles.css',
'/css/styles.min.css',
'/images/bubble.svg',
'/images/cloud-r.svg',
'/images/fox-bg.png',
'/images/grid.png',
'/images/iceburg.svg',
'/images/lines.png',
'/images/narwhals-bg.jpg',
'/images/whale.svg'
]);
})
);
});
Activate
self.addEventListener('activate', (event) => {
// extend the events lifetime until the promise resolves
event.waitUntil(
// return a Promise that resolves to an array of cache names
caches.keys()
.then((cacheNames) => {
// passes an array of values from all the promises in the iterable object
return Promise.all(
// map over the cacheNames array
cacheNames.map((cacheName) => {
// if any existing caches don't match the current used cache, delete them
if (currentCacheNames.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
Fetch
// NOTE: the fetch event is triggered for every request on the page. So for every individual CSS, JS and image file.
self.addEventListener('fetch', (event) => {
// only respond if navigating for a HTML page
// see https://googlechrome.github.io/samples/service-worker/custom-offline-page/ for more details
if (event.request.mode === 'navigate' ||
(event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
event.respondWith(
// make sure the request we are making isn't in the cache
fetch(createCacheBustedRequest(event.request.url))
.then((response) =>{
// if the response has a 404 code, serve the 404 page
if(response.status === 404){
return caches.match(FOUR_OH_FOUR_URL);
} else {
// check see if the response is in the cache, if not fetch it from the network
return caches.match(event.request)
.then((response) => response || fetch(event.request));
}
})
// If catch is triggered fetch has thrown an exception meaning the server is most likely unreachable
.catch((error) => caches.match(OFFLINE_URL))
);
} else {
// respond to all the other fetch events
event.respondWith(
caches.match(event.request)
// if the request is in the cache, send back the cached response. If not fetch from the network
.then((response) => response || fetch(event.request))
);
}
});
Learning Resources
There are some great resources around the web if you want to learn more about service workers, I have listed a few below (remember to check out the two links above too):
Introduction to Service Worker
Service Worker API
Service workers explained
Video - Instant-loading Offline-first (Progressive Web App Summit 2016)
Video - An introduction to Service Workers (FullStack 2016)
Video - Thinking offline (FullStack 2016)
Course - Offline Web Applications
I hope this post gave you a little insight into the potential of the service worker, and the Offline-first era we are about to enter into! If you know of any others resources, get in touch and I will add them to the list.
--- End: Implementing a Service Worker
--- Start: HTML Email Countdown
Published on: 24 June 2016
https://nooshu.com/blog/2016/06/24/html-email-countdown/
Main Content:
Now I must admit I don't get excited about HTML emails very often. After years (and years) of having to painstakingly build them, and weeping over the horrible quirks of email rendering engines (Lotus Notes anyone?), it is easy to understand why. But an email landed in my email account the other day that I was quite impressed with.
A large company here in the UK sent me an email promoting one of its soon to be released products. All perfectly normal, but then over to the right hand side I saw an animated clock that was counting down the number of days until launch. This was intriguing to say the least as HTML emails are very primitive beasts. Usually laid out using tables, CSS support has its quirks, and JavaScript... not a chance! So how exactly was the countdown clock working?
After a minute or so digging around in DevTools I could quickly see what they were doing. Using their server (via a proxy) running PHP they were passing a set of URL parameters, which in turn was generating an animated gif on the fly, and serving it back to the email inside an image src attribute. Very interesting technique, as it actually produces an accurate countdown clock every time you reload the email. Here's an example of the URL they were using:
https://www.foo-bar.co.uk/clock/index.php?time=2016-06-13+23:00&width=400&bg=f00000&shadow=f00000&font=000
The parameters being sent are pretty self-explanatory. The fact that the company can change the date and the colours means they can use the same technique over and over again for different products with different email designs. It got me thinking; I wonder if I can create something similar using node.js? After a little bit of research I found a few tools I could use to mock something up:
Moment.js
Node-canvas
GifEncoder
Moment.js is the go-to library if you want to do any form of date / time manipulation in JavaScript. Super simple API, very well tested, and comes with an excellent set of documentation. Node-canvas is a canvas implementation in node, using Cairo. It allows us to draw whatever we like to the canvas and use it as a frame in our Gif animation. The final piece of the puzzle is GifEncoder. It takes our canvas frames, ties them all together as an animation and encodes them into a Gif image we can view. Setup was all quite simple. I only ran into one issue where my version Cairo was out-of-date leading to all the characters being squashed together. After updating to the latest version using homebrew, and a quick npm install everything worked as expected.
Below you can see the final result of what I wrote. A simple animated countdown gif generated on the fly using node.js.
It is worth noting that as we are generating and manipulating raw pixel data, the more pixels you have, the slower it is to create the gif files. Larger gifs with more frames can take over 2 seconds to generate, which isn't great in terms of performance. But it does the job, and I enjoyed building it so win-win.
You can view the code on GitHub, and see a live demo on Heroku. The GitHub readme file has an explanation as to what options are available, as well as the methods of how to retrieve the generated gif.
Note: I am on the free Heroku plan which shuts down after 30 minutes of inactivity, so it may take a second or so to spin back up once requested.
--- End: HTML Email Countdown
--- Start: Reasons to be Bashful
Published on: 13 April 2016
https://nooshu.com/blog/2016/04/13/reasons-to-be-bashful/
Main Content:
There's been some big news in the past week or so, Bash is coming to Windows 10. Now I have to admit, this has got me pretty excited to say the least. For those who don't know, Bash is an acronym for "Bourne-again shell", an interactive-shell that is used on UNIX bases operating systems.
Over the past 3 years I've moved away from developing on a Windows machine purely to developing on Mac. One of the main reasons for this is due to the terminal. Tooling for Interface Development has become heavily invested in Bash; with tools like Grunt, Gulp, npm, and Vagrant becoming a major part of and Interface Developers workflow; including mine. So much so I have no idea how I lived without them.
The primary reason I am excited about the move towards Bash by Microsoft is due to the way window management works on OSX… I basically find it clunky to use. Maybe it's just me, but navigating and moving files around is just a real pain. Navigating between windows is also very hit and miss. For example if I have multiple windows open for Chrome, if I CMD + Tab onto Chrome, how do I get to the other windows, not just the last one used? I know pressing the alt key at the same time brings a minimised window to the front, but it just isn't intuitive†. So the fact that in the future I will be able to use Windows window management and Bash together is perfect!
So what can Bash be used for? Anything and everything would be an accurate answer. If you want do dig down into the inner workings of your computer, Bash is the way to go (NOTE: be very careful with the commands you run. It is quite easy to kill your machine by copying commands from a random forum if you don't know what they do!).
Here's a very small selection of what the Bash prompt can do for you:
Move / copy files and directories around your machine
Remove files and directories (very powerful, be careful!)
Open files listed files in your favourite editor
Find files using the find command, look inside files using the grep command
Edit file permissions
Piping one commands output to another commands input
Administer your computer as well as remote machines
Combine all of the above with its own scripting language
Honestly, the list above is just an incredibly small selection of what you can do with Bash. I've been using it for a few years and Im only just scratching the surface of what is possible. It certainly is a powerful tool to have in your toolkit.
My Setup
So I thought I'd give you a small rundown of what I use Bash for, and a set of tweaks & tools I use to make Interface Development a little easier. I'm always interested in hearing how to improve my workflow, so if there's anything I'm missing let me know!
Dotfiles
There's no need to stick with the standard Bash setup, you can customise the way bash works by modifying a set of config files (.bashrc, .bash_profile etc). These are known as dotfiles and are usually found in you user profiles home folder. You can modify the look and feel, as well as add custom aliases of commands you frequently use to speed up your workflow. A very useful technique I have used is to store all my dotfiles in a single directory, then symlink them to the correct place in my home directory. Add this single directory to git and hey presto; if your computer dies you can easily restore your Bash profile setup. A very in-depth tutorial on how to do this can be found here.
If you are interested in seeing what other developers do with their dotfiles I highly recommend you check out https://dotfiles.github.io/. Here you will find a huge list of dotfile setups from all over GitHub. It is a real treasure trove of useful commands and potential workflow timesavers all in one place!
ZSH
Once you discover zsh you will never go back to a standard Bash setup. Zsh can be thought of as an extension to the Bourne shell. It comes with a whole heap of improvements and features from other interactive shells. The zsh website is a little bare, so I'd recommend you take a look at the oh-my-zsh GitHub page. It is a community-driven framework for your zsh configuration. It includes plugins, themes and other handy additions to improve your shell.
I personally use the powerlevel9k for my theme (seen above) with the git, vagrant, and npm plugins enabled. It is recommended you only enable the plugins you actually need as having too many enabled could slow down your overall shell experience.
As you can see the prompt looks very different to the standard Bash prompt, incorporating things like the time the command was run, where the command sits in the history, and many additions to make working with git easier. These are all customisable of course by editing your dotfiles.
Aliases
Now I must admit I don't have many custom aliases (you will see the reason why later in the blog post). Here are just a couple of examples of how you can use aliases to speed up your workflow:
alias ipa="ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'"
This command stands for "IP Address", and it will give me the current IP address of my machine (or multiple if on multiple networks).
alias vus="vagrant up && vagrant ssh"
I use Vagrant on most of my projects, so I often find myself having to bring up boxes and halt them. This alias just allows you to bring a machine up then SSH into it quickly.
alias opens='open -a Sublime\ Text'
I'm primarily a WebStorm user, but whenever I want to quickly edit a file from the shell in a GUI I use the opens command: opens [filename]. Of course you could also use nano or vim if you wanted to just stick to the terminal.
Fasd
o here's one of the reasons why I don't have many custom aliases. When I first started using the terminal I found I had quite a few aliases related jumping in and out of specific directories around my machine. This is where Fasd comes in.
It is a productivity booster that keeps track of files and directories you have used recently. It even tracks how often you use them and ranks them accordingly. Very handy if you often edit the same set of files. Here are some example commands you could use:
f scss list recent files matching the string "scss"
d website list recent directories matching the string "website"
a script list files and directories matching the string "script"
z images cd into the most recently used "images" directory
If you are using it with zsh there is a little bit of additional setup to get it all up and running, but once it is you will wonder how you lived without it.
SCM Breeze
Here's the second reason I don't have many custom aliases: SCM Breeze.
When it comes to Git, the terminal is my first port of call. I've tried GUI's in the past but have always reverted back to the terminal. Once you get your head around the basic commands it is fairly simple to use, and I also find it helps you understand the inner workings of Git a little more.
Now as much as I love typing, any way to speed up the process is big plus with me. This is where SCM Breeze comes in. It is a set of shell scripts that speed up your interaction with Git massively by adding a whole heap of useful shortcuts. From adding files to the staging area all the way down to branching and rebasing. For example:
$ gb - show a list of local branches ordered with corresponding number
$ gco 2 - check out branch number 2 from the list
$ gs - look at local staging status, files ordered with corresponding number
$ ga 1-5 - add files 1 to 5 to the staging area
$ c - commit the staged files, asks for a commit message
$ gps - push your branch to the remote
As you can see the above workflow is much quicker to type than with the standard git commands. For a full list of aliases available you can use the list_aliases git command.
Tig
One of the main advantages of using a GUI with Git is the ability to quickly look over all the commits across various branches to see what has been changed and by who. You can prettify the standard git log command which helps, but even that is still lacking. For a more comprehensive tool you should look at Tig.
Tig is a text-mode interface for Git. Its primary usage is as a git repository browser, but it can be used for so much more. I've really only scratched the surface of what Tig can do as I mainly use it for a quick glance at commit diffs. I highly recommend you take a look at the user manual to see what else it can do for you.
iTerm2
So the standard terminal that comes with OSX is okay. It does the job, but there's so much more you can do with it to improve your workflow. The tabs feature is handy, but it is still missing something. This is where iTerm2 blows the standard terminal out of the water. You can see an example of iTerm2 above.
iTerm2 comes with a huge set of features and improvements like autocomplete, search, paste history, and the hotkey window. But by far my favourite feature is the ability to have a set of split panels either horizontally or vertically. Once setup you can have multiple sessions visible at the same time. Great if you need to work on a project as well as SSHing into a remote machine at the same time. Multi-tasking win!
Learning Bash
So if you've never used the Bash prompt before, not to worry! There are plenty of resources on the internet to help you learn. Here are just a few that I have used in the past to get you started:
Learn Enough Command Line to Be Dangerous
The Bash Academy
Bash Scripting Tutorial
The Linux Command Line Book - Not Free
How to Be a Terminal Pro Screencast - Not Free
Advanced Command Line Techniques - Not Free
Command Line for Non-Techies - Not Free
Hopefully you found some of my bashful ramblings useful! Let me know if there's some essential terminal related tool or technique I'm missing, I'd love to hear about it.
†Maybe I'm doing it all wrong? Please contact me if there are some secrets or helper tools I'm missing out on, I'd love to give them a try!
Update
I recently stumbled across this blog post by Jilles Soeters from 2014. Both our lists are almost identical (which is quite reassuring), but there was a small addition that caught my eye. zsh-syntax-highlighting is an plug-in for Zsh that I had no idea existed. It highlights commands while you type them, green if they are recognised, red if not. Very useful indeed! I've now installed it and it works perfectly, so thanks to Jilles for the tip, and I highly recommend you take a read through his blog post too.
--- End: Reasons to be Bashful
--- Start: Keyframe animations and media queries
Published on: 12 March 2016
https://nooshu.com/blog/2016/03/12/media-query-keyframes/
Main Content:
Recently I re-developed my website (I hope you noticed!?). I'm going to be putting together a couple of short blog posts on what I learned in the process. One interesting issue I stumbled across was related to how IE 9, 10, & 11 handle @keyframe rule's inside media queries.
As I was cross-browser testing the site across various browsers I noticed that non of the animations were working in IE. As I'd been using the excellent postCSS autoprefixer in my build process I was quite surprised by this. A quick check of caniuse.com confirmed that IE 9-11 supported 2D transforms (although IE9 requires the -ms prefix). So what was happening?
After a little bit of head scratching I finally discovered what the issue was. My @keyframe animations were sitting inside of a media query definition! I'd included the media query as I only wanted animations to render on tablet / desktop devices. Every other browser rendered the animation as you would expect, it was only IE that had the issue.
Since I was using Sass I thought I'd try wrapping the keyframe rule in an @at-root{} directive (introduced in Sass 3.3); but it was no help. The directive will only return you to the root of the media query block, not the root of the CSS (as you would expect). Anyway it was a simple fix. Just move the @keyframe rule outside of the media query block, then all browsers are happy. You can still apply the animation to the devices you want by wrapping the animation property in a media query should you wish.
Take a look at the example below and try it out in various browsers. You will notice the top cloud doesn't animate in IE 10 - 11, but the bottom one does. You will be able to see why from the CSS tab.
This could be an easy issue to slip into if you are including any animations using mixins, as you don't always know where they are going to be included, so worth keeping in mind.
--- End: Keyframe animations and media queries
--- Start: Using Wordpress with Foundation Interchange
Published on: 14 January 2014
https://nooshu.com/blog/2014/01/14/wordpress-foundation-interchange/
Main Content:
I recently created a blog / portfolio website for a friend based around Wordpress and the fantastic Foundation front-end responsive framework. Foundation comes with with a excellent set of components and utilities to help you build a responsive site that works across all devices. One of my favorites is called Interchange, and is how Foundation handles responsive images.
The way you handle your images on a responsive build is key to its success. You don't want huge images loading on a mobile device as it is a waste of bandwidth. On the opposite side of the spectrum you don't want really small images loading on desktop as they will look very pixelated and ruin the design. Interchange allows you to get the best of both worlds. It even comes with a no JavaScript fallback.
The way it works is fairly self-explanatory. On load the JavaScript looks at the current device width (and pixel density), and swaps out the image source for the correct one listed in the data-interchange data attribute.
When it come to using Interchange with Wordpress I wanted to make it as simple as possible for the user to upload images. The key was to make Wordpress do the work of creating the different sizes and outputting the required HTML onto the page. To do this I hooked into the native gallery functionality Wordpress comes bundled with. It allows a user to assign a set of media to a specific post, which is then displayed in a gallery on the page.
Below you will see a breakdown of what I added to the theme (mainly to the functions.php file), and a brief explanation of what is going on. Note: The tags have been added to fix the syntax highlighting in Jekyll (startinline option didn't work), you don't need to include them.
// functions.php
Now we have the basics setup for the theme, we want to create a function that renders the correct HTML for use with Foundation Interchange.
// functions.php
';
$html .= ' ';
// return the final HTML
return $html;
}
?>
Time to create the HTML that will be rendered when using the custom gallery shortcode [custom-gallery].
// functions.php
'ASC',
'orderby' => 'menu_order ID',
'id' => $post ? $post->ID : 0,
'size' => 'responsive-small'
), $attr, 'custom-gallery'));
// get the image ID
$id = intval($id);
// get the post thumbnail ID
$post_thumbnail_id = get_post_thumbnail_id();
// get the attachments in the post
$attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
// you will need to customise this surrounding HTML depending on the layout required
$output = "";
// using the Foundation grid for a simple stacked
$output .= "
";
// loop through each image ID generating the required HTML
foreach ( $attachments as $id => $attachment ) {
// skip if we are looking at the post thumbnail image
if ($id == $post_thumbnail_id)
continue; // Don't show the thumbnail
$imagehtml = generate_responsive_image_tag($id);
$output .= "$imagehtml";
}
// close the tags and return the gallery HTML
$output .= "
";
$output .= "
";
return $output;
}
?>
The last thing we need to do is include the gallery in the page. Now we can either do this manually using the [custom-gallery] shortcode; or in my case I wanted every portfolio post to automatically add the gallery of images associated with it.
// single-portfolio.php
And that's it. On a portfolio page you can now upload a set of images (using the 'Add Media' button) and Wordpress will create the different sizes and output the correct HTML for Interchange automatically. Just make sure you are uploading the highest resolution image possible as you don't want Wordpress to be up-scaling small images.
One last addition I added was the ability to add responsive images in a standard blog post. Again you insert an image into a standard blog post and the responsive Interchange compatible HTML is returned to the editor. Responsive images all over the place!
// functions.php
I hope you found this little bit of Wordpress / Foundation integration helpful. If there are any improvements that can be made feel free to contact me via the contact form.
--- End: Using Wordpress with Foundation Interchange
--- Start: Site update using Zurb Foundation 4
Published on: 28 August 2013
https://nooshu.com/blog/2013/08/28/site-update-using-zurb-foundation-4/
Main Content:
So last Wednesday I returned from Australia after two years of work and travelling; it's gone so quick! I guess time flies when you are having fun and building websites! In that time one reoccurring word I've come across is "responsive". When I left the UK responsive design and responsive development was an emerging methodology; but that's all changed and now everybody wants a responsive website!
The responsive dust has now settled, and, as always happens in development two prominent responsive frameworks have emerged. Bootstrap, originally developed by two developers at Twitter and Foundation by Zurb. Now I've had previous experience with Bootstrap (which uses LESS) but only passing experience with Foundation (which uses Sass). I've been meaning to make the website responsive for quite a while, so I may as well kill two birds with one stone; learn something new and responsivise (is that a word?) the website, so Foundation looks to be the obvious choice.
Foundation has just reached version 4 and I must say you can really tell. It's a very mature framework with an excellent set of documentation. As a bonus if you need to get up to speed quickly and have a spare bit of cash lying around they even offer training sessions once a month where you get to ask the original developers questions. What a fantastic way to learn a new framework!
There are a whole set of pre-built JavaScript add-ons available for developers to use, all responsive by nature and easily customisable if needed. Each is independent of each other so you only need to include the ones you need. From a CSS point of view the framework is built upon Sass (Syntactically Awesome Stylesheets) and it offers a whole heap of cool functionality like variables, mixins and nested rules. Using a command line tool these .scss files compile down to regular CSS. Awesome!
I've updated the site today with the basic functionality I need but I have a few issues I still need to resolve:
Responsive images using the interchange.js add-on. The add-on works really well but it's figuring out how best to generate the different images automatically using WordPress that is the issue.
Adding a "medium" grid layout to target tablet size devices. Version 4.2 has an experimental version that works, but has a few quirks.
Working with Sass is fantastic but I'm sure there are a few optimisation that I can make to my workflow when using it Sublime Text 2. SublimeOnSaveBuild looks like a handy plug-in but unfortunately it doesn't seem to be working for me at the moment.
There we have it, converting a standard website to a responsive layout is quick and easy with Zurb Foundation. I'm looking forward to learning lots more about this excellent framework in the future. I may even have to sign up to their online training too!
--- End: Site update using Zurb Foundation 4
--- Start: Marker Cluster Calculator for Google Maps v3
Published on: 03 October 2012
https://nooshu.com/blog/2012/10/03/marker-cluster-calculator-for-google-maps-v3/
Main Content:
If you've ever worked with the Google Maps API for a large number of markers I'd say you've run into this issue; how do you manage hundreds of markers on the map without killing your browser? Now admittedly over the past few years browsers have improved massively (thanks to the "browser wars 2.0"), but handling a large number of markers is a sure-fire way to make even modern browsers fall over.
So what's the answer? Thankfully there are helper libraries that allow you to cluster markers together, so the browser only has to draw one icon, rather than fifty. An excellent article on the subject was written in 2010 by Luke Mahe and Chris Broadfoot of Google. In it they go into great detail on what the problem is, and how to solve it with a sprinkle of JavaScript magic.
For a recent project I required marker clustering, as there were 500+ markers to be rendered on the map. I decided to use the MarkerClusterer library to do the job. It applies grid-based clustering, each marker is added to its closest cluster group within the set bounds. Everything worked perfectly until the client requested a change to how many cluster groups there were. Luckily there is a setCalculator() method that allows you to modify how clusters are defined and influence the styling, but looking around the net I saw very little explanation of what exactly this calculator function was doing, so I've created a small demo and heavily commented the setCalculator function for future users.
/**
* Set our own custom marker cluster calculator
* It's important to remember that this function runs for EACH
* cluster individually.
* @param {Array} markers Set of markers for this cluster.
* @param {Number} numStyles Number of styles we have to play with (set in mcOptions).
*/
markerCluster.setCalculator(function(markers, numStyles){
//create an index for icon styles
var index = 0,
//Count the total number of markers in this cluster
count = markers.length,
//Set total to loop through (starts at total number)
total = count;
/**
* While we still have markers, divide by a set number and
* increase the index. Cluster moves up to a new style.
*
* The bigger the index, the more markers the cluster contains,
* so the bigger the cluster.
*/
while (total !== 0) {
//Create a new total by dividing by a set number
total = parseInt(total / 5, 10);
//Increase the index and move up to the next style
index++;
}
/**
* Make sure we always return a valid index. E.g. If we only have
* 5 styles, but the index is 8, this will make sure we return
* 5. Returning an index of 8 wouldn't have a marker style.
*/
index = Math.min(index, numStyles);
//Tell MarkerCluster this clusters details (and how to style it)
return {
text: count + " ("+ index + ")",
index: index
};
});
Hopefully it's all self-explanatory as to what the method is doing. Each cluster has its own index, this defines what icon is used. You can modify these icons and add your own, and also change how many cluster levels there will be.
You can view the simple demo here, here's a direct link to the map JavaScript file.
--- End: Marker Cluster Calculator for Google Maps v3
--- Start: Auto-spacing input field text
Published on: 25 March 2012
https://nooshu.com/blog/2012/03/25/auto-spacing-input-field-text/
Main Content:
On a recent project, a set of wireframes landed on my desk which contained some "interesting" ideas, particularly when it came to form fields. One that really stood out was having a credit card number auto-space as the user types it into a single input box. This of course would depend completely on what type of card they are entering, as different cards have different layouts. American Express for example have a [4, 6, 5] layout, where as Visa use a [4, 4, 4, 4] number layout.
Thankfully this functionality was eventually removed from the UI specifications after concerns from myself and others were raised. Just to make this perfectly clear; I think this is a bad idea, and here is why:
Users are very wary when it comes entering their credit card details. Spaces magically appearing in their credit card number could freak a few of them out.
Most e-commerce website I've ever used ask for the credit card number as one long string of numbers with no spaces. Auto-spacing goes against this convention, so a user may actually go back and try to remove the spaces (I know I would).
Validation scripts for credit card numbers usually ask for the input to have no spaces, or will remove any spaces on submit.
If you do want to space out the credit card number, why not use different input boxes for each set of numbers? It looks cleaner and is simpler to implement. Just have your JavaScript automatically jump between boxes as the user types.
Even though this functionality was removed, I decided to build a prototype of it in action because... well because I can and I was bored. :) Please, (please!), whatever you do don't use this code in production. I created it as an experiment and should be treated that way. It's very simple to get around the auto-spacing and then all hell breaks loose! (not really, but it is easy to break).
The spacing is implemented by counting the length of the string inside the input field, but you could also monitor the current position of the cursor. Anyone wishing to do this see this excellent set of answers on Stackoverflow.
You can see the prototype here. Remember, don't use it. It's not big and it's not clever :)
--- End: Auto-spacing input field text
--- Start: HTML5 date input type on mobile
Published on: 06 March 2012
https://nooshu.com/blog/2012/03/06/html5-date-input-type-on-mobile/
Main Content:
Whilst developing a new mobile only website, the UX team specified in the wireframes that a datepicker was needed for an input field; but nowhere else on the site was a datepicker used, so I really wanted to avoid using a JavaScript heavy solution. I couldn't justify including so much extra JavaScript, CSS and images for so little usage. So what other options do we have?
Well there is a jQuery plug-in called Mobiscroll which is around 16KB is size and works on iOS and Android devices. Unfortunately there's no mention of Windows-based mobiles which is a real shame, as it's almost a perfect solution. The other option we have is to take advantage of some cutting edge HTML5 form input types; the date input type. Support is nowhere near 100% yet, but if you approach its usage from a progressive enhancement standpoint, it works well. On mobile browsers that support it, the user gets a fancy datepicker that's very intuitive; browsers that don't simply drop back to a standard text input. It's worth noting that Modernizr can't detect that date inputs create a datepicker, since Modernizr can't do it I assume it isn't possible. Damn!
Once I'd decided on how the date picker was going to work (HTML5) it was time to implement it and test it across my available mobile browsers. Implementation was dead simple:
Where things got a little tricky (and annoying) was the client-side validation of the input. Since the wireframes contained lots of forms with a varying range of input types and requirements, I decided to go with quite a heavyweight validation script (around 21KB minified). This turned out to be a very good decision in the end, as there are a few quirks to the date input element.
First thing I had to consider was how were users going to input the date when they don't have the fancy datepicker? The most intuitive way (at least for me) is they simply enter in the format dd/mm/yyyy. Great, that's sorted! And guess what, when a user uses the fancy datepicker it also returns a value of dd/mm/yyyy... no, no it doesn't! It looks like that's the value that will be returned as that's how it is displayed, but no, it's never that easy. Webkit actually returns the date in the format yyyy-mm-dd, not quite what I was expecting! Unfortunately this breaks our validation as it is looking for a format of dd/mm/yyyy!
So what's the fix? Well you could take the easy route and make your non-fancy datepicker users enter the date in the yyyy-mm-dd format; but that just feels wrong. No user is going to expect to enter a date like that, it's completely unintuitive! No I'm afraid it's going to take a little hack to fix this issue. The hack involves using a second input field of type "text"; when a user interacts with the fancy datepicker or enters in the date manually, the date is "cleaned up" and passed along to the second input field. You then do your form validation against this second field. You can see an example of this working here.
/**
* iOS input type="date" returns a value of yyyy-mm-dd even when
* it displays dd/mm/yyyy. This breaks validation. Fix for this using a second input.
* Keyup event for testing in a browser, not needed for mobile.
*/
$("input[type='date']").on("blur keyup", function(e){
var $this = $(this),
value = $this.val();
//Does the input have "-", if so it is from the webkit datepicker, fix it
if(value.indexOf("-") !== -1){
var cleanDateArray = value.split('-');
value = cleanDateArray[2] + "/" + cleanDateArray[1] + "/" + cleanDateArray[0];
}
//Set the hidden value to validate on, trigger the blur and keyup event for validation as you type
$("#hiddenDateField").val(value).trigger("blur").trigger("keyup");
});
A couple of points to note about using this method. Even though we aren't validating the datepicker input, we still have to set "date: false" in the validation rules. This is because the validation plug-in automatically tries to validate date inputs. Validation fails because it doesn't like the dd/mm/yyyy format. I've also used the dateITA method to validate the date on the "hidden" input (you can find this in the additional-methods.min.js file). This additional method is more robust than the plug-ins standard date validation. A minor pitfall with this hack is that setting the second input to type "hidden" will stop its validation; this is due to the validation plug-in ignoring hidden inputs. So to hide the input you can set "display: none" in the CSS (urghh I know, I feel dirty too!).
So there you have it, that's how I solved validating a date input on mobile with fancy datepicker and standard text fallback. It's not ideal by any means, but it works. Another solution would be writing a validator Regex that accepts both dd/mm/yyyy and yyyy-mm-dd date formats, but this means returning both types of dates to the server on submit. Due to server-side constraints with the project, this isn't an option (boo!). Is there a much simpler method that I'm completely missing? If so please leave a comment! :)
--- End: HTML5 date input type on mobile
--- Start: Sublime Text 2, a truly sublime text editor
Published on: 01 March 2012
https://nooshu.com/blog/2012/03/01/sublime-text-2-a-truly-sublime-text-editor/
Main Content:
I'm always on a quest to find that one perfect editor, I've been hunting for it for many years. Having been an UltraEdit, Notepad++, Eclipse, Aptana and Komoddo user in the past, they all had their pro's and cons. Eclipse and Aptana (built on Eclipse) were very feature rich (and very slow!). UltraEdit and Notepad++ were quick but didn't quite fulfil what I was looking for in an editor (maybe that has changed in newer versions). Komoddo I was very impressed with, but it had a few bugs that just became annoying after a while (like tabbing code blocks). None of them were quite right.
Upon starting my new job a couple of months ago, a colleague, Anton Mills, introduced me to Sublime Text 2 and I haven't opened another editor since!
There are a few key features I look for in an editor. They are:
Speed: It needs to be responsive and quick to load. There is nothing more frustrating than an editor that freezes all the time and takes 5 minutes to load.
Regular updates: If there is a bug it's nice to know it will be fixed soon(ish).
Plugins: It may not be possible for an editor to have everything you need in the core, so a good plug-in interface is essential.
Community: The author may not be on hand to answer all questions so having a helpful community is a plus.
Thankfully, Sublime meets all of these criteria. Development builds are released every week or so and there is a vibrant community on hand to answer any questions. As I'm in a list making mood, here's a few plug-ins I'd encourage any Front-end Developer install:
Package Control: Before you do anything, install this plug-in! It makes installing all other plug-ins a breeze.
SublimeCodeIntel: An excellent code auto-complete plug-in that's been ported from Komoddo.
Zen Coding: If you haven't heard of Zen Coding take a look at my previous blog post. You will wonder how you ever survived without it.
SFTP: Making changes and uploading them directly from the editor can be a godsend at times, but use with caution! Paid plug-in but you get a free trial.
DocBlockr: Makes documenting your code quick and easy (supports JavaScript and PHP).
A few of the key features to look out for when you try it are the full screen and distraction free mode, multi columned editor (see image above), multiple cursors (this one I love!), code mini-map and the command palette. Those are just a few I've noted but I'm discovering more every day. Checkout this informative post by Nettuts+ for more awesome features.
Now it's not perfect, there are a cons. Automatic tag closing isn't working for me at the moment and the project panel needs a little work (being able to drag and drop files would be nice), but the pros far outweigh the cons, so I'm willing to overlook them. If you have a suggestion or find a bug the place to report them is here. As you can see there are lots of feature requests already and the author actually implements (some) of them!
Big thank you to the author Jon Skinner, a fellow Sydney resident for developing such an excellent editor! Download it here.
--- End: Sublime Text 2, a truly sublime text editor
--- Start: New country, new job!
Published on: 27 February 2012
https://nooshu.com/blog/2012/02/27/new-country-new-job/
Main Content:
Boy, it's been a while since my last blog post! Over the past two months I've discovered how hard it can be to get a broadband connection in Australia! I'd been "refused" by three different companies before I was finally connected on Saturday. Lesson to be learned: check which company owns your local exchange; If you don't you will be refused (but they won't really tell you why!).
I've also started a new job at an excellent Australian digital agency called Visual Jazz Isobar (I know, it's a bit long-winded isn't it). VJ have an excellent set of clients and the agency is producing some outstanding work. We've also just become part of the Isobar group which have offices all over the globe. With over 2500+ employees, the group is producing some world-class work. It's a very exciting time to be at Visual Jazz!
Above you can see my custom VJ avatar. Everyone at VJ gets one and, as I'm a huge F1 fan I decided to incorporate it into my design. The crash helmet I'm holding is that of my childhood hero Nigel Mansell; winner of the 1992 F1 Season. I remember being on Club Corner, Silverstone in 1991 as a 10 year old, watching Mansell giving Senna a lift back to the pits as his McLaren had run out of fuel. Ahh the good old days!
--- End: New country, new job!
--- Start: Writing efficient CSS selectors
Published on: 08 December 2011
https://nooshu.com/blog/2011/12/08/writing-efficient-css-selectors/
Main Content:
With modern browsers getting quicker with every new version number it's easy to fall into the trap of writing inefficient code. A page will run super quick on the latest version on Chrome or Firefox, but you also have to consider older browsers and mobile devices. That shiny new web application that uses some super fancy CSS selectors may be unusable on certain devices due to its limited hardware. That's not to say you shouldn't be using super fancy selectors; you just have to be careful to consider your target audience, and use them in the most efficient way possible.
The first thing to note about CSS selectors is they don't work in the way you'd expect. In the west we read a page from left to right. Reading a CSS selector, you'd expect that's what the browser does as well. Wrong! The browser actually reads a selector from right to left (in Mozilla's case anyway, and most likely in others too). So take the following CSS as an example:
body #wrapper .article ul.meta li a {
font-weight: 700;
text-decoration: none;
font-family: Arial;
}
The browser first looks for all the anchor tags (called the 'key' as it's the rightmost selector), then looks at the list items, it evaluates those and throws away the results that don't match. Next the browser moves onto elements with a class of 'meta', throwing out results that don't match and so on... you get the idea! There's so much redundancy in the above selector, it could easily be cut down to:
.meta a {
font-weight: 700;
text-decoration: none;
font-family: Arial;
}
This example is much more efficient. There are less rules for the browser to evaluate, it's much easier to read and if you apply minimal selectors across your whole stylesheet you will notice a big difference in file size. The key to writing efficient selectors is to be as specific as possible. Whatever you do don't write this:
body * {
margin: 0;
padding: 0;
}
The universal selector(*) is bad (even body isn't needed)! You are targeting every single element in the DOM and setting it's padding and margin to zero. For a large page that could easily be thousands of elements!
I actually inspected the stylesheet for this website and went over it with a fine tooth comb. I found many additional selectors that just weren't needed. The size of my stylesheet went from 18.3kB down to 16.5kB, a saving of 1.8kB. It doesn't sound a lot in terms of file size, but that's a whole lot of selectors the browser no longer has to evaluate to render the page.
Luckily there are tools available that can help you make your CSS more efficient, as well as many other areas of your website too. The first tool I'd recommend is called Page Speed, created by Google. The Page Speed extension is available on both Chrome and Firefox. Once installed you have the option to run it on any page; it will give you an overall score for that page and recommendations on how to improve it.
The second tool I'd recommend is Opera's Dragonfly. Dragonfly (similar to Firebug, in name at least) is Opera's developer toolkit, much like Web Inspector for Chrome. An awesome feature that Dragonfly has, that other toolkits don't is 'style recalculation'. Style recalculation gives you a breakdown of all the selectors that were run on the page, how long they took to evaluate and how many elements they hit along the way (hits).
If you look closely at the results in the image above, you will see that the selectors with the most number of hits are the ones involving the universal selector(*), as you would expect. You may also notice that most of the timings say 0.0ms which isn't very helpful. This is due to the fact that the size of the DOM being tested is very small, and timing to 1 decimal place isn't accurate enough to show the actual time it took to evaluate. If you were to run this test on a huge page, say the HTML5 Specification for example, you would really be able see the difference in CSS selector efficiency.
This feature of Dragonfly is very new and is still in testing. There are a few issues still to be ironed out in future releases but it's definitely a tool to keep in your bookmarks.
A word of warning when it comes to writing efficient selectors. I found myself trying to make the selectors so efficient it was becoming quite hard to pin-point where exactly on the site they were being used. If you have a very specific area of a site you are trying to target, it is easier to read if you have the selectors starting with an ID reflecting that area. You then know for certain that the changes you make won't affect other parts of the site. Also remember that removing 'unused' selectors will affect the specificity of the rule. You could end up breaking something, as what you thought was an unused selector was actually used in overriding another rule.
Having too many descendent selectors is something that Page Speed frowns upon, but as with all things in life it's a case of finding that happy medium. In this case it's between efficient selectors and CSS that is easy to read and maintain (for you and other developers).
--- End: Writing efficient CSS selectors
--- Start: Design for Developers
Published on: 30 November 2011
https://nooshu.com/blog/2011/11/30/design-for-developers/
Main Content:
As a developer I must admit I find design hard! Open up a blank PSD in Photoshop and I come out in a cold sweat. More often than not a developer will quickly construct an application, get it working and dump everything on a page. The application works, but it's horrible to look at and is very unintuitive to use. Thankfully, a designer by the name of Johan Ronsse has put together a presentation aimed at developers who are looking to improve their design skills.
The presentation has some excellent content on what you should (and shouldn't) do with an interface design. Basics on fonts, colours, shadows and icons are all explained in a clear and concise way. For those wishing to continue with their new-found design skills, slide number 179 has a long list of links and books to read. My personal favourite is the simple, yet effective [Grid Calculator](http://www.29digital.net/grid/) tool. I've read many articles on the grid system, but have never used it. This handy website does all the mundane maths for you, allowing you to get back to making your application look pretty!
Big thank you to Johan for the presentation, every developer should read it at least once (or bookmark it to read later)!
--- End: Design for Developers
--- Start: Embracing Git for version control
Published on: 29 November 2011
https://nooshu.com/blog/2011/11/29/embracing-git-for-version-control/
Main Content:
For many years I've been using Subversion (SVN) as my version control of choice. It's been a part of my deployment process, all of my work is in Subversion, even the small demos I've created are in a repository. It's a good feeling to know that if your laptop dies (or is stolen), all your work is backed up on a remote server.
Recently I've heard many developers raving about Git, and I've looked at libraries and code snippets that are using it, so I thought I'd check it out and see what all the fuss is about. After a couple of hours reading up and watching a few tutorials I'm genuinely excited about using it in future projects. It really is that good! So, what's so good about it then you may ask? Well here are a few points that stood out for me:
Easy to install and start using (Windows has a simple installer)
Distributed version control, so no need for a central server
Runs on your local machine, no need to connected to the internet to commit(!)
Very clean, it only creates one git directory for the whole repository (no hidden .svn's everywhere)
Incredibly easy to branch and merge your code (this is a big plus!)
It's simple to use Git with SVN, no need to abandon your SVN repositories. Git can pull & push directly into an existing SVN repository!
I'd heard developers saying how easy it was to branch and merge your code using Git, I assumed they were exaggerating. But no, it really is simple:
#create a new branch in my repository
git branch my_new_branch
#move to the new branch for commits etc
git checkout my_new_branch
#finished with the branch, so lets merge it back into master
git merge my_new_branch
One of the most amazing parts of Git that blew me away: when you jump between branches it automatically updates your file structure accordingly! So lets say you have a new set of files in a new branch, and you need to jump back to master (trunk) to make some changes. Simply run 'git checkout master', the new branch files will be 'removed' and stored away until you are back on the new branch where they were added. Amazing!
The feature that really sold Git to me was the stash command. So many times I've been working on a project and got half way through some changes, only to have to fix a bug in the original version. So you copy the modified files somewhere, undo all your changes, fix the bug, copy the files over and start where you left off. Not fun! Git and the stash command come to the rescue:
#store your current changes in a 'clipboard' so they can be seen again later
git stash
#you are now working on the unmodified version of the branch
#after you've fixed the issue, start from where you left off by applying the stash
git stash apply
Another huge advantage Git has is how simple it is to share code between developers. It only takes a couple of commands to clone another repository. Once you have a local copy (clone), you can change whatever you like. Make the project better (or break it horribly, it's up to you). For an example of how powerful social coding is take a look at Github. The 3D JavaScript library three.js for example has over 4000 people watching and 400+ people have forked (cloned) the repository. If your version adds a cool new feature or fixes a bug, it can easily be merged back into the original project!
If you are interested in learning how to use Git there are some superb resources available. For people who like screencasts I highly recommend watching the one created by Peepcode. It's only $9 (US), 1 hour-long and will get you up and running with Git in no time at all! Here are some other resources I found useful:
Git-SVN - A Crash Course
A successful Git branching model
NetTuts - Easy Version Control with Git
Github help documents
Right, I'm off to start committing to a repository while travelling on a train to work when I don't have an internet connection (warm fuzzy feeling enabled)!
--- End: Embracing Git for version control
--- Start: Remote Loading HTML5 Elements with jQuery
Published on: 18 November 2011
https://nooshu.com/blog/2011/11/18/remote-loading-html5-elements-with-jquery/
Main Content:
I ran into a rather annoying problem a few months ago while developing my travel blog; the problem of course was involving Internet Explorer. I'm used to working with WordPress as I use it all the time, but I wanted to get away from the standard pagination you find on a blog. So I decided to use jQuery 1.6.4 to pull in articles from other pages (blogname.com/page/2, blogname.com/page/3 etc). Now this is all fairly simple using the handy jQuery .load() method; point it to a URL, pull in the page, pick the bits you need and reinsert into the page. Simple! Unfortunately once I got a prototype working in 'good' browsers, IE8 and below was having non of it!
After a little head scratching to work out what was failing, I worked out it was because I was using HTML5 elements such as 'article', 'header' and 'footer'. There was no problem displaying them on the page, as I'd used Remy Sharps excellent HTML5 Shiv script. It only failed when trying to pull in these 'new' elements via Ajax.
Note: Before you read on you'll be happy to hear that this issue no longer occurs in jQuery 1.7.0. Horray!
If you can't upgrade, for whatever reason, I hashed together a little work-around for browsers IE8 and below, so read on. I admit the work around isn't pretty, but it works. I tried for a few hours to get IE8- to recognise the 'new' elements after an Ajax request, but to no avail. Eventually I had to wrap the HTML5 tags in a div using conditionals:
H2 wrapped in a header element
The div is added for browsers IE8 and below, you can then use it as a hook to pull in the elements inside the div. I was hoping that wrapping the HTML5 elements in a standard div would be the end of it, I'm afraid not. The .load() method still didn't work, IE just ignored the elements it didn't recognise. I used jQuerys much more customisable .ajax() method to fix the issue in IE6, 7 and 8:
//IE8- work around to load HTML5 elements into a page
$("#loadHTML5LinkOld").click(function(){
$.ajax({
url: "page_to_load.html",
cache: false,
success: function(html){
var HTML;
//Clear before load
$("#html5LoadHolder").empty();
//IE: Look for the hacky wrapper before insertion
HTML = $(html).filter("div#ieHackContainer").html();
//If HTML var is empty assume using newer browsers
if(!HTML){
HTML = $(html).filter("#html5Content").html();
}
//Append to page
$("#html5LoadHolder").append(HTML);
}
});
return false;
});
This method works in all browsers I've tested in as I've added a fall back (or should that be forward?) for newer browsers. The solution isn't ideal (I really hate the conditional comments), but older versions of IE aren't going away any time soon, and it works. Maybe there's a more obvious solution that I missed? Leave a comment if there is, I'd love to know!
You can see a working example here. The page I'm loading from is here and the JavaScript in full here.
--- End: Remote Loading HTML5 Elements with jQuery
--- Start: Back to my desk (down under)
Published on: 13 November 2011
https://nooshu.com/blog/2011/11/13/back-to-my-desk-down-under/
Main Content:
Well that was a quick three months! Travelling around south-east Asia was incredible! So many memories and stories to take away from the experience. Unfortunately all good things have to come to an end, so back to work it is. Actually I've been looking forward to getting back to work for a couple of weeks, itching to start using the latest technologies the web has to offer.
A lot can change on the web in three months; so in order to get my head around what's new, I've compiled a list of exciting developments and changes in the Web Developer community (in no particular order).
Browsers
Thankfully the browser war has started again (this time for the better) and it certainly hasn't slowed down in the last three months!
Some amazing news first; Has Internet Explorers browser market share finally dropped below 50%? Well according to Statcounter it has (oh please let it be true!). As with all statistics you have to be careful how you interpret the data. A more important statistic would be how that 50% is broken down. How many users are still using IE6? If corporations are still sticking with IE6 due to internal tools and upgrade cost, that value won't be changing any time soon (boo!).
WebGL is the big thing on the web at the moment. Incredible graphics rendered directly in the browser (no Flash required!). Of course Microsoft being Microsoft, they aren't going to support it. To be fair they do give a good excuse; the specification isn't 100% set, so they aren't going to implement it (but when has that ever stopped them before?). Luckily for developers a small team in Russia have decided to add it themselves by creating a plug-in for IE (for non-commercial use) called IEWebGL. It's not ideal but it's better than nothing!
There's been big changes at Firefox over the past three months. The Firefox team have now adopted a six week release schedule just like Chrome. So while I've been away we've had version 6,7 and 8. There's even talk of Aurora 10 (a.k.a. Firefox 10) on the horizon. Mozilla also seem to have adopted the 'channel' route for deployment, where by you can join the stable, beta or nightly channel depending on how brave you are. You can receive a new version of Firefox every few days (or sometimes a broken version) if you so wish. I'm hoping they also adopt the 'delta' update strategy that Chrome uses; no need to download the whole installer every time, only the parts that have changed. On a side note, Firefox now gets 100% on the Acid3 test, so well done to Mozilla for achieving that (if that type of browser comparison floats your boat).
I love this little addition; in the latest nightly versions of Firefox, Mozilla has added support for the draft JoystickAPI. What an incredibly simple idea, it never even occurred to me! The API allows a browser to communicate directly with a joystick / gamepad, meaning you can control that snazzy HTML5 game you've written just like you would on a games console. There's a breakdown of what is supported on the API page including handy code examples. All you need is a joystick that's supported by your PC or Mac. It looks like a standard Xbox360 controller will work, and they're fairly cheap to buy. I May just have to add that to my Christmas list this year and give it a whirl!
With the IE browser market share (apparently) going below 50%, it looks like Chrome could be set to take number 2 spot from Firefox very soon. I must admit, I'm not too bothered about who's in second place; as long as all browser vendors keep improving their products I'm a very happy developer. More competition equals better browsers for all. When one of the 'good' browsers gets to number one, then I will celebrate.
At the start of October Google unveiled their new Dart programming language which is supposed to replace JavaScript as the working language on open web platforms. Dart will compile to ECMAScript 3 on the fly for non-Dart compatible browsers. There's even a simple IDE so you can start playing around with a bit of Dart right now. Will it catch on? Who knows, only time will tell.
Last but not least the browser that everyone forgets about (but it's actually an excellent browser), Opera. At the start of October they released Opera 12 alpha, which finally supports WebGL! Great news for Opera and WebGL. As it looks like WebGL is here to stay, maybe it's time the IE team reconsidered its position? Let's hope they do.
JavaScript
The big event (in Europe at least) that happened while I was away was JSConf.eu, a 2 day conference dedicated to the JavaScript programming language. This year it was held in Berlin, Germany, somewhere I've never been (but have heard many great things about). I wish I could have been there, a couple of the talks I'd loved to have seen include “Magic Wand for surface generation – Voxels with JS” and “Connecting the real world to node“. Luckily for those of us who couldn't be there videos of most of the talks are available online.
Talking of Node, the development team has been bug fixing and adding lots of lovely new features to the code base, and it is now up to version 0.6.0. A point that really caught my attention was the work regarding Windows support. Being a Windows user myself it's always nice to know the Windows platform is being considered in future development. Looking at the performance statistics in the 0.6.0 blog post, the team have made huge improvements by supporting native APIs (rather than through Cygwin).
Note: As I was writing this blog post Node 0.6.1 was released and it now comes with a Windows installer (MSI).
jQuery
For users of jQuery (myself included) it's been a very busy three months. There have been three new versions released (not including betas and RC's), 1.6.3, 1.6.4 and 1.7. Here are some of the key features that caught my eye in each version:
1.6.3: requestAnimationFrame API has been removed for animations due to strange goings on when animated tabs are hidden from view. The team plans to re-implement it in a later version.
1.6.4: Minor bug fix release.
1.7: Big changes in the way events are bound (and unbound) to elements. There's a whole new .on(), .off() event API which aims to unify all the ways of attaching events in jQuery. Also, as mentioned on the jQuery blog they are shorter to type!
For version 1.8 the jQuery team is planning on slimming down the library to reduce it's overall gzipped file size. They are asking for feedback from the community as to what should be removed and offloaded into a separate plug-in, or maybe even removed all together. There are now so many methods available to a developer, a lot of which are probably never used; I can see why they are looking to slim it down. Maintaining rarely used code is never fun.
I personally would like to see the animations offloaded to a separate plug-in, as for most projects I never use them. I'd happily add the animation plug-in back in if and when needed. Maybe this could be the start of a more modular version of jQuery; by that I mean something along the lines of the MooTools core builder. Creating a custom jQuery build, with only the parts you need really would be a great option. I'm sure lots of other jQuery developers would be against it, but each to their own.
Last in the jQuery news is the announcement that there will be a jQuery conference in Oxford, UK in 2012. It's the first jQuery conference in the UK, and of course I'm now in Australia. Typical! Oh well, maybe next time.
Three.js
The three.js community has been busy beavering away with lots of cool new demos. It's incredible how this superb JavaScript library has taken off since mr.doob unleashed it on the web.
I've noticed from the Git repository for three.js that the number of updates has really slowed down. Maybe there are things in the pipe line that have yet to be rolled into the Git repository; or maybe it's a sign of the three.js API stabilising.
One of the major problems I found while working on a few personal projects was the lack of documentation. It really was a case of diving into the library and examples and having a play (fun, but not ideal). Stability will allow the documentation to catch up with the current release, and in turn allow the wider community to develop lots more interesting 3D demos.
Speaking of interesting demos, here's one that's been released by HelloEnjoy called Lights – An interactive music experience. I can't say I've heard of Ellie Goulding (I know, I'm old), but it's a catchy tune and kudos to her record company for pushing the music video envelope. Is interactivity the future of music videos? I hope so!
Demos
One thing I really missed while I was away was how all this new technology is being applied on the web. It's always interesting to see how other developers apply technology to problems they encounter. Creating demos is a fun way to learn something new.
First on the list is a bit of face detection using HTML5 and JavaScript. This technique is used in various webcam applications, where you can add things like glasses and masks to your face in real-time. Hours of fun for kids (and developers too). The demo makes use of the CCV JavaScript Face Detection library and HTML5 canvas element. Awesome stuff by @wesbos, and as a bonus there's a whole blog post with commented code on how he did it.
What do you get when you combine Google maps and WebGL? That's right, you get MapsGL! Google has enabled the option to view its maps complete with 3D buildings, in the browser, no plug-ins required! Superb news for WebGL as there is no bigger name you want behind you to push the technology into the mainstream. It's still a little rough around the edges but it looks very promising! You can enable and view a demo here.
Mozilla developer Michael Bebenita has created and released a JavaScript-based H.264 decoder that will run natively in the browser… wow! Nicknamed Broadway, it is based on the open-source decoder that Google uses in the Android OS. Yet another example of how powerful the JavaScript programming language is. To test it you will need a nightly version of Firefox, or you can always view a video from Brendan Eich's talk at ACM's annual OOPSLA conference, where he shows it in action. Amazing!
Do you want to help a computer beat a Grandmaster at chess using JavaScript? Well now you can thanks to the Chess@home project. Developers at Joshfire created a project prototype at this years 48 hour Node Knockout contest. It utilises lots of cutting edge technologies. Starting with the Web Workers API in the browser, to Socket.io for communication and a Node.js – MongoDB combination for storing the results. It works by using the spare CPU cycles of browsing users to calculate the best next move. By adding a small Chess@home widget to your website you can help the project defeat a Grandmaster. By making use of the Web Worker API, visitors to your website won't even notice the difference (users can disable the widget via a check box if they so wish).
As you can see the Web Development community has been busy over the past few months! Hopefully I picked out most of the important changes. If you think there's anything I've missed that's a worthy addition, please leave a comment, I'd love to hear about it.
--- End: Back to my desk (down under)
--- Start: Hanging up my Web Dev boots (for three months)
Published on: 06 August 2011
https://nooshu.com/blog/2011/08/06/hanging-up-my-web-dev-boots-for-three-months/
Main Content:
As of tomorrow evening I will no longer be a resident of this great land called England as I'm setting off to travel the globe for approximately eighteen months (in total). I'll be spending three months in south-east Asia; as well as having a grandstand seat at the Singapore Grand Prix (yay!).
I land in Sydney, Australia early November and will be looking for Freelance work (for 12 months) when I land. So if there are and Australian agencies looking for an Interface Developer let me know.
I'll be travelling with my wonderful girlfriend (who will also be Freelancing in Oz). If you're interested you can follow our progress on our travel blog. We are also on twitter.
BBQ on the beach here we come!
--- End: Hanging up my Web Dev boots (for three months)
--- Start: There ain't no party like a DemoJS party
Published on: 06 July 2011
https://nooshu.com/blog/2011/07/06/there-aint-no-party-like-a-demojs-party/
Main Content:
Another day, another website that makes my jaw drop to my desk. This time it's the results from the latest Mozilla Labs DemoJS party. Hosted in Paris, France over the weekend, it had many coders and artists attending hoping to win big prizes by creating interesting demo's using the latest web technologies. I may not understand French but I'd have still attended just to see all the demos on show; some extremely inspiring coding going on.
The competition was split into two sections; 1k and freestyle. I find both interesting but as I've mentioned before in previous blog posts I'm always amazed at what can be done with 1k of code.
The video above is of a demo created by Silexars that came in second place. A live demo can be viewed here. All created with less than 1k of code! WebGL really is starting to come of age. As with any of these demo's it's so easy to copy / paste, modify and learn from them. View source is a wonderful tool.
Another demo that caught my eye was by p01 (who I've blogged about before. This time he created Quaternion Julia Fractal in only 550 bytes of JavaScript and GLSL! It came in third place.
From the freestyle section the Particles.js by basecode has completely killed my productivity today!
Nice work guys and gals! If you have a spare few minutes (hours) check out the rest of the DemoJS results, you won't be disappointed.
--- End: There ain't no party like a DemoJS party
--- Start: WordPress 3.2, auto update fail
Published on: 05 July 2011
https://nooshu.com/blog/2011/07/05/wordpress-3-2-auto-update-fail/
Main Content:
Today, while on my lunch hour, I decided to auto update my blog to WordPress 3.2. Usually it goes without a hitch; unfortunately today it didn't. I'm not quite sure what happened but it failed within a couple of seconds. Damn it! It may be a Dreamhost issue as I've seen reports of other users having similar issues, or it could be just bad luck.
If you have a similar issue the first thing you may notice, when trying to get to your site is that maintenance mode is "enabled". To disable this connect to hosting server via FTP (or SSH) and delete the file '.maintenance'. The file may be hidden so you may have to enable viewing hidden files in your FTP client. Once deleted you should once again be able to see your site (fingers crossed!).
The next issue I had was not being able to log into my site admin panel. Navigating to the page gave me a horrible fatal PHP error; a sure sign that something was very broken. Not to worry there's a (fairly) simple fix.
While logged onto your server via FTP or SSH, delete the 'wp-admin' and the 'wp-includes' folder. Make sure you don't delete the 'wp-content' folder! Once that's done download a copy of WordPress 3.2, unzip it and upload the unzipped 'wp-admin' and the 'wp-includes' folders to your server. Once complete you should be able to see your WordPress login page again! Yay!
You may be asked to update your database, go ahead and click the update button and login. Now take in all the goodness that is version 3.2 of WordPress! The guys have done a superb job with the admin panel, love the new design. Glad to hear they have also dropped IE6 support too. About bloody time!
So a quick summary for the tr;dr's out there:
Maintenance mode on? Delete '.maintenance'.
Delete 'wp-admin' and the 'wp-includes' folders (Not 'wp-content'!)
Download a copy of WordPress and unzip it.
Upload the unzipped 'wp-admin' and the 'wp-includes' folders.
Navigate to the admin page, update database and login.
Extra: In some cases you may also need to upload the wp-settings.php file then navigate to the admin page.
Phew, crisis averted! Now's a good time to reiterate what is mentioned on the updates page. Always remember to back-up your database and files before you run an update. If something does break with the auto update you can always revert to your backup!
--- End: WordPress 3.2, auto update fail
--- Start: Aloha Editor and WordPress
Published on: 09 June 2011
https://nooshu.com/blog/2011/06/09/aloha-editor-and-wordpress/
Main Content:
This is a short update on a post I wrote back in August 2010: Aloha Editor, content editing the HTML5 way. When I last looked at the project there were some excellent examples of it working on static pages but no real integration into back-end systems had taken place. As with any open-source project things progress quickly; on the 5th June a plug-in called Front-end Editor for WordPress was updated to include Aloha Editor! You can now edit blog posts directly in the page rather than through the administration panel. The plug-in is a joint effort from authors Jotschi and Scribu, excellent work guys.
Now I'd love to show you a picture of it working in my blog template, but that would be too easy wouldn't it. :) Unfortunately the plug-in doesn't work with my custom theme, I'm yet to figure out the reason why. Boo! I know it isn't a plug-in issue as it works with the default WordPress theme. This could be an issue for others wanting to use the plug-in, so as soon as I figure out why I'll post an update.
One issue I did notice was Aloha likes to use its own version of jQuery; manually including it in your theme will cause Aloha to throw an error. A quick workaround is to wrap a WordPress conditional tag around the jQuery script element like so:
Since you need to be logged in for Aloha to be initialised this will fix the error and allow you to use the latest version of jQuery in your theme.
As soon as I fix Front-End Editor for my current theme I'm sure it will be one of my favourite plug-ins. Last but not least a big thank you to the Aloha Editor team, I'm looking forward to seeing how the project progresses.
--- End: Aloha Editor and WordPress
--- Start: A little bit of MicroJS
Published on: 29 May 2011
https://nooshu.com/blog/2011/05/29/a-little-bit-of-microjs/
Main Content:
Recently there was a flurry of talk around a little something called MicroJS, mainly thanks to a website of the same name created by Thomas Fuchs, author of the script.aculo.us user interface library. I'm not sure if Thomas coined the term "MicroJS" or if it's been in use for a while, but it describes the micro-framework methodology perfectly. So what is a micro-framework? The best way to answer that is to first ask what is a JavaScript framework?
JavaScript frameworks have been around since around 2005 (looking at the Prototype and jQuery history); their purpose is to allow developers to easily add interactivity to a page by creating a JavaScript abstraction layer to build from. The library takes care of any cross browser issues and quirks, allowing developers to focus on the "cool" stuff, building websites. As a developer I can't thank all the library authors enough; without them my working life would be so much more stressful (and my hair would be even grayer than it is now!).
Once you know what a JavaScript framework is, it doesn't take a genius to guess what a micro-framework is. Where as a full framework will have many tools (methods) a developer can use, a micro-framework only focuses on a very specific set of functions. I like the knife analogy: a full-framework like Dojo would be a Swiss Army knife where as a micro-framework could be considered a small pen knife. So which do you use in a project? This completely depends on the project in hand. I've put together a small list of pros and cons for each (let me know if you have any others):
Full Framework
Pros
Extensive set of features to cater for most eventualities.
Consistent API across features.
Large user base with lots of community support.
Huge number of working examples available.
Many developers to fix bugs and add additional functionality.
Single point of reference of documentation.
Cons
Large code base could be very daunting to new users.
Large page footprint.
Many features of the library may not be needed.
Micro-Framework
Pros
Small page weight, usually less than 5K.
Small set of features so very quick to pick up and use.
Main focus on a very specific set of functionality.
No feature creep or excess code.
Use the right tool for the right job.
Cons
Small number of developers, bugs and issues may take a while to be fixed.
Development of the framework may stop completely.
May be very little support from the author and the community.
Fellow developers in your team may not be familiar with the framework.
Mixing micro-frameworks could conflict if badly coded.
Multiple frameworks could mean multiple HTTP requests.
Multiple points of reference for API docs.
Multiple frameworks could lead to an overlap in functionality.
Many of the cons for micro-frameworks stem from using more than one at a time, but if you only plan on using one then they can be ignored.
Micro-frameworks caught my eye recently due to a couple of small projects I'd been working on. The projects all used vanilla JavaScript as there was no need for a helper library. I later realised I needed to attach a few events and manipulate the DOM but I wanted to avoid including jQuery in the project as I only needed a small fraction of its functionality. Luckily the MicroJS website came to the rescue.
The examples below are taken from Query, Bonzo, Events.js and Bean. As you can see the usage for each is pretty self-explanatory with lots more functionality is available from each library's website. If you're a jQuery user the syntax will look very familiar.
CSS selector and DOM utility
/*
Query - Dustin Diaz
https://github.com/ded/qwery
CSS selector engine
*/
query("#myid");
query(".myclass");
query("#myid .myclass div a");
query("a, div, strong");
/*
Query Paired with Bonzo - Dustin Diaz
https://github.com/ded/bonzo
DOM utility
*/
query("#myid").show();
query(".myclass").offset(50, 100);
query("#myid .myclass div a").addClass("anchorClass");
query("a, div, strong").remove();
Events
/*
Events.js - James Brumond
https://github.com/kbjr/Events.js
Event handler library
*/
Events.bind(window, 'load', function(e) {
//Page loaded, do something
});
//Invoke the page load event
Events.invoke(window, 'load');
//Mouse click event
Events.bind(selectedElements, 'click', function(e) {
//Mouse has been clicked
});
//Very handy keystroke event
Events.bind(document, 'keystroke.Ctrl+Shift+Alt+S', function(e) {
saveMySlices();
});
/*
Bean - Dustin Diaz
https://github.com/fat/bean
Event handler library
*/
bean.add(selectedElements, 'click', function (e) {
//Mouse has been clicked
});
//DOM has loaded
bean.add(document, 'DOMContentLoaded', function(e){
//Page loaded, do something
});
//Invoke an event on an element
bean.fire(selectedElement, 'click');
//Remove the event from an element
bean.remove(selectedElement, 'click');
I'll be trying out a few more of these micro-frameworks for my personal projects in the future as the ability to select only the functionality you need really appeals to me. Are there any other micro-frameworks you've used that you'd recommend? Leave me a comment and I'll check them out.
Update: It just so happens that a handy library website has emerged inspired by the MicroJS website called EveryJS. The website lists all library's rather than just micro versions. Not all are listed but I'm sure they will be added soon so it's one to keep your eye on.
--- End: A little bit of MicroJS
--- Start: Chrome Developer Tools at Google IO 2011
Published on: 18 May 2011
https://nooshu.com/blog/2011/05/18/chrome-developer-tools-at-google-io-2011/
Main Content:
I've been a long time user of Firefox's magnificent Firebug extension; I honestly cannot remember how I used to develop websites without it (can you?). Changing web pages on the fly and debugging issues in seconds rather than minutes, we really are spoiled. I thought it would be hard for any other debugging tool to come close to Firebug in terms of ease of use and available tool set. Oh how I was wrong!
Paul Irish and Pavel Feldman hosted a talk at this years Google I/O about Chrome Dev Tools and what's new in the world of debugging in Chrome. I must admit, there were a number of jaw dropping moments in the video where it dawned on me how powerful the tools actually are. Here are a few of my favourite points:
7:11: Chrome monitoring the changes to the style sheets and letting you know what has changed.
7:55: Ability to revert back to different CSS versions. The Dev Tools automatically creates a new version as you change code.
21:02: A whole host of JavaScript debugging tools. Edit the script in the browser (with code colouring.. nice) rather than edit in IDE, upload, test, repeat...
30:31: My favourite part, the remote debugging feature. Chrome can act as a server meaning you can connect too and edit pages remotely. At first you may think "well, what's the point?". As this is being done at the WebKit level it will soon be available for all WebKit browsers including mobile devices. Debug mobiles browser directly from your desktop. Wow!
I'm definitely going to have to wean myself off Firebug and give the Chrome Dev Tools a blast. As mentioned in the video, the tools are being developed all the time with new features landing daily (on dev channel). Looks like Firebug has some serious competition! If you're a developer with 43 minutes to spare, watch the video, you won't regret it.
A few helpful links mentioned in the video:
Lea Verous CSS3 pattern gallery
Full documentation for Dev Tools
The slides – Chrome Dev Tools: Reloaded
--- End: Chrome Developer Tools at Google IO 2011
--- Start: WordPress Stats broken? Grab yourself a Jetpack!
Published on: 22 March 2011
https://nooshu.com/blog/2011/03/22/wordpress-stats-broken-grab-yourself-a-jetpack/
Main Content:
Last week one of my favourite WordPress plug-ins broke: WordPress Stats. For anyone who doesn't use this fantastic plug-in it's a very clean and simple way of viewing visitor statistics directly on your dashboard. It isn't as extensive as Google Analytics and for that I'm grateful as it doesn't need to be. I first thought it was a hosting issue but that turned out to be incorrect. The plug-in, in it's current form has been discontinued as it has been rolled into a compilation of useful WordPress tools called Jetpack.
So what do you get in Jetpack? Well here are three of my favourites:
WordPress.com Stats: exactly what it says on the tin...
Shortcode Embeds: easily add media from YouTube, Vimeo and Slideshare.
LaTeX: need equations in a blog post? This ones for you then.
There are eight plug-ins currently available with more coming soon.
The last plug-in I mentioned, LaTeX may sound like it's come straight from a .xxx domain name but bare with me; under that slightly suspect name is a powerful tool for anyone who needs to format equations in a post. Here's a small demonstration:
Note: LaTeX support now disabled since moving to Jekyll. See here for information on how to enable it.
LaTeX has allowed me to embed one of the most beautiful equations in all of mathematics; Euler's Equation directly into my blog post. It links Real Numbers, Euler's Number, Imaginary Numbers and Pi in a staggeringly simple equation. There's a mass of information on LaTeX here with everything you'd ever need pretty much covered.
So if you're looking to give your WordPress blog a bit of a boost (horrible pun I know), give Jetpack a whirl!
--- End: WordPress Stats broken? Grab yourself a Jetpack!
--- Start: Fractal magic with WebGL
Published on: 16 March 2011
https://nooshu.com/blog/2011/03/16/fractal-magic-with-webgl/
Main Content:
I've been so busy recently I haven't had chance to work on any personal projects (bar a small amount of node.js, but that's a future blog post); so I thought I do a quick post on a very impressive project that caught my eye last week: Fractal Lab.
Fractal Lab, as the name suggests, is a fractal rendering tool using OpenGL Shading Language (GLSL) by a very talented programmer called Tom Beddard. Now I'm not going to lie to you, the mathematics behind all this goes way over my head! OpenGL on the other hand is something I've read about with increasing frequency recently due to the WebGL explosion happening on the 'net at the moment. Big thanks to all the developers of Firefox, Chrome (Webkit) and Opera for that! Internet Explorer 9 on the other hand isn't planning on supporting it. Hopefully that will change in the future.
Fractal Lab allows you to render out 2D & 3D fractals directly to your browser and navigate through them in real time! Be warned though, this will push your browser and graphics card really hard. It mentions this on the site; it's possible to lock-up your GPU with certain GLSL fractal shaders, so be careful (my poor laptops on-board graphics card did exactly that, so he's not lying) :)
There's hours of fun and experimentation to be had with this superb example or WebGL. Thank you to Tom for developing it.
--- End: Fractal magic with WebGL
--- Start: The developing WebGL demoscene
Published on: 07 March 2011
https://nooshu.com/blog/2011/03/07/the-developing-webgl-demoscene/
Main Content:
One of my key memories from playing a friends Amiga oh so many years ago (apart from Cannon Fodder) is the cool intro demos created by the demoscene. These were usually found on, cough, slightly dodgy versions of games that were "acquired" from various sources :)
What's always amazed me about these demos is the amount of space the programmers had to play with and the hardware available at the time; both extremely limited. While the space and hardware limitations are no longer an issue, people are still developing these amazing demos. One reason for this is due to an exciting area in Web Development that's currently flourishing: WebGL. The technical specification was finalised last week and developers have started to take notice of this very powerful visual programming language. Developing demos in the browser environment is a new limitation and programmers are looking at WebGL to push the boundaries.
The demo above has been converted into WebGL by a very talented programmer called Per-Olov Jernberg (Possan). You can even take a look at the source on Github if your that way inclined! You can view the original from April 2000 here.
With modern browsers like Chrome, Firefox 4 and now Opera adding WebGL support and improving their JavaScript engines, there's never been a better time for Web Developers to get involved in this new demoscene. All that's needed is some JavaScript, Canvas and a little creativity. I genuinely look forward to seeing all the old school programmers diving into WebGL. I personally know very little about this new language so I'll be able to learn so much by doing a quick "view source".
There's already a WebGL competition in progress called gl64k where programmers have to create an interesting visual demo with only 64k (65,536 bytes) at their disposal. Awesome stuff will be emerging from this new technology in the next couple of years and I for one can't wait to see what!
--- End: The developing WebGL demoscene
--- Start: Human History in 100 Seconds
Published on: 26 February 2011
https://nooshu.com/blog/2011/02/26/human-history-in-100-seconds/
Main Content:
Reddit is a great place to look when you're searching for inspiration. Occasionally a gem will emerge from the background noise that will blow you away; and I often find it's the simplest ideas that have the most impact. For example: take 424,000 Wikipedia articles and cross-reference their date and location and you get "A History of the World in 100 Seconds". A simple idea with inspiring results.
The visualisation starts off slowly but around 1400AD there's an explosion of activity. It's interesting to see that there's one little island in the middle of it all where a high percentage of the activity occurs. You may be able to guess its name, but if not, it is of course the United Kingdom. By the end of the video you can clearly see a map of the world and it's even possible to pinpoint many individual countries.
I'd love to see a version that only focuses on Europe; there are so many references to it in the data but the visualisation zoom level doesn't do it justice. The authors Gareth Lloyd and Tom Martin have done a fantastic job of making a staggering amount of data into an interesting visual work of art.
--- End: Human History in 100 Seconds
--- Start: Auto-resize a Facebook Application iframe
Published on: 25 February 2011
https://nooshu.com/blog/2011/02/25/auto-resize-a-facebook-application-iframe/
Main Content:
Huzzah! The end of another busy week full of lots of (mostly) enjoyable work; mainly involving Facebook in some way or another. Lots of clients have really jumped on Facebook recently and the demand for their own "apps" has increased dramatically.
Setting up an app inside an iframe is easy, but one thing you don't want is scroll bars as they look damn ugly! You can set an iframes height using the setSize() method but what about if the iframe varies in size between pages and user interactions (accordions, show / hides etc); you need some way of automating this. Luckily Facebook has already added this functionality to the JavaScript SDK, you just need to enable it. The API docs for this seemed a little flaky, with quite a few comments from people who couldn't get it to work; so here's a solution that worked for me:
Copy and paste this into the body of your iframe and you're halfway there. The last thing to do is check your application settings, under one of the advanced settings pages you will find an auto resize check box that you will need to enable (sorry I can't remember exactly which page!). Once enabled your iframe should resize automatically depending on the page content. There are a few parameters you can tweak with the setAutoResize() method, they are documented here. Fingers crossed it works for you too!
Important Update: One thing I just noticed with the code, it didn't work in IE! Not great. Luckily there was a quick fix. Change script type="application/javascript" to type="text/javascript". IE doesn't like application/javascript!
--- End: Auto-resize a Facebook Application iframe
--- Start: Google Fractalmaps
Published on: 01 February 2011
https://nooshu.com/blog/2011/02/01/google-fractalmaps/
Main Content:
I've been a fan of Google for quite a while now. What with their superb Chrome browser, Gmail service, extensive API's and most importantly their motto, "Don't be evil" what's not to like! Only time will tell on the last point so fingers crossed. While browsing the Google Research Blog I spotted a very interesting article: Julia Meets HTML5.
Julia of course refers to Julia fractals rather than a person called Julia. Named after Gaston Julia, a French mathematician who studied them in the 1920's. His works were largely forgotten until Benoît Mandelbrot mentioned them in his now famous works on fractals.
Google Labs have created an extremely slick way of navigating around various types of fractals. From the plain old boring(!), Mandelbrot and it's many variations to the Julia and Newton fractal. Select a fractal and colour scheme then zoom and drag just like a standard Google Map.
According to the article the demo uses the Google Maps API; I guess it may use it loosely in it's user interface but there are an infinite number of zoom levels with fractals. When you zoom into a coastline on a Google Maps you will eventually reach a limit where you will be presented with a fuzzy image (or a blank tile); this will never happen on the Julia Map. The 'tile' information isn't downloaded from a server like Google Maps, it's calculated on the fly by the browsers JavaScript engine. The faster the JavaScript Engine the better. If you have a browser that supports the new Web Workers API you will notice a huge difference in performance, as the CPU intensive fractal calculation will be offloaded to separate worker threads rather than the single main UI thread.
I could spend hours investigating the infinite mathematical landscape of the Julia Map, why not try it out for yourself and post your results on Twitter under hashtag #juliamap.
--- End: Google Fractalmaps
--- Start: Monitoring a value change on an input element
Published on: 15 January 2011
https://nooshu.com/blog/2011/01/15/monitoring-a-value-change-on-an-input-element/
Main Content:
For a recent project I ran into a slight issue with the jQuery change event. It's not an issue with jQuery, but I was quite surprised when it didn't work as I expected. I'd set up a selection of form inputs that a user could change; once changed various calculations would be made and the values outputted to a second set of disabled input elements (demo). The inputs are disabled as they are to be calculated rather than entered manually.
I'd attached the jQuery change event to the output elements like so:
$("#outputs").find("input:text").bind("change", function(){
$(this).highlightFade('red');
});
So the plan was, once an input value had been changed using the jQuery().val() method the change event would fire and it would quickly colour in and out the element (using highlightFade) to notify the user that it's value had changed. Unfortunately the change event wasn't firing, so I had to find another way to monitor the output elements.
What I ended up doing was using an array to hold the previous values of the input elements then checking to see if they had changed in the calculation. If changed then fire the event:
//Array to store the old values
var oldValues = [];
//Push these values into an array which is checked on calculation
$("#valueOutput input:text").each(function(i){
var thisValue = $(this).val();
//If the old value is different to the new, change the colour
if(oldValues[i] !== thisValue){
$(this).highlightFade('red');
}
//Push the new value into the array
oldValues[i] = thisValue;
});
It's quite hard to explain exactly what's happening so I've put together a small demo. Try changing one of the top input fields then tab (or click out) of the input element to recalculate. Is there an easier (or better) way to do this? Comment below.
--- End: Monitoring a value change on an input element
--- Start: A three.js community on Reddit
Published on: 30 December 2010
https://nooshu.com/blog/2010/12/30/a-three-js-community-on-reddit/
Main Content:
Well 2011 is nearly upon us; which leaves me thinking... where did 2010 go! I hope I'm not the only one who thinks this year has gone quick! One big web application that died in 2010 was digg.com. I used to use it every day for the latest technology and funny videos, but then they changed it. The design became very blue and digg seemed to change from a simple community driven link aggregator to a, well, I'm not sure what it changed to in all honesty. So it was time to find an alternative.
Luckily for me (and all digg users) there's already a well established alternative: reddit.com. It may not look as flashy as digg, but it makes up for it with ease of use and functionality. Need to set up a community for your web application, current technology, interest or well, just about anything really; then reddit is the place for you.
So that's exactly what I've done for Mr. doobs three.js JavaScript library. I created a Threejs community that anyone can submit links to relating to three.js. Over the past few weeks I've been adding a couple of links a day, there really are a great selection of examples out there if you take the time to hunt then down.
So if you've created a cool new example using three.js or any other link relating to this excellent JavaScript library submit it here. Digg is dead. Long live reddit.com!
--- End: A three.js community on Reddit
--- Start: Alteredq: A WebGL Ninja
Published on: 10 December 2010
https://nooshu.com/blog/2010/12/10/alteredq-a-webgl-ninja/
Main Content:
Anyone who's been following the progress of the Three.js 3D JavaScript engine will know of alteredq, as he's been helping with its development along-side Mr. doob. His latest demo using Three.js really impressed me:
The demo uses Three.js, WebGL and Web Workers; so that pretty much ticks every box for me. The model is from AMD's MeshMapper which is no longer supported. I can't say I've ever heard / used it before but it's certainly on my to-do list to try out.
To view the demo see here; be warned though you will need an up to date browser that supports WebGL and Web Workers. Grab a recent version of Chrome and enable WebGL and it should work.
If you really want to push the boundaries you could try the latest Canary Build of Chrome (10.0.605.0 at time of writing) which now has an optimised version of V8, called "Crankshaft". It uses runtime information to see which code will benefit from the most optimisation and is 2 times quicker in some tests! The Canary Build release channel of Chrome is meant for developers / early adopters who want to try out the latest features. Unlike the dev and beta release channels the Canary Build is installed independently, so it won't overwrite your current chrome settings.
Bring on the revolution; to paraphrase a well known mobile company: The future's bright, the future's WebGL.
--- End: Alteredq: A WebGL Ninja
--- Start: Game On London 2010
Published on: 07 December 2010
https://nooshu.com/blog/2010/12/07/game-on-london-2010/
Main Content:
Yesterday evening I had the pleasure of attending the Open Web Gaming event #gameon10 hosted by Mozilla Labs and Six to Start. The evening involved five short main talks and numerous lightning talks by various attendees.
There were an interesting mix of speakers, from the big name companies like Google and Mozilla, down to start-ups and independents:
Christian Heilmann: Very interesting talk on why developers should be developing using new open web technologies. He had some very interesting ideas for Angry Birds too (see below).
Ernesto Jimenez: A hands on talk on the Do's and Don'ts when developing with the HTML5 canvas element. Mainly about things he'd learnt the hard way.
Rob Hawkes: Rawkets is a simple shooter game Rob developed for a University project that's really taken off. It uses various open technologies including node.js and Web Sockets on the server side.
Rik Lomas: Is the line between TV and computer entertainment bluring? With the help of Picklive it certainly is. A fantasy football game played in real time, built on Javascript, jQuery, Strophe and XMPP.
Paul Truong: Paul's talk didn't quite go to plan with a couple of teething problems with the demonstrations, but it was still very informative. I had no idea MacBook Pro's had a built in accelerometer, and using it for gaming is a stroke of genius (although I can't see many people tipping their MacBook Pro, it's a tad heavy for a controller). With the iPad you're on to a winner.
I particularly liked Christian Heilmann's talk as he had some great ideas for Angry Birds if it was built on open web technology. You could very easily allow people to build their own levels, add multi-player support, add a frustration rating for levels and user comments. Adding the social level building aspect to the game takes a bulk of the development time off the game developers; this is exactly what Media Molecule have done with Little Big Planet and they now have 1 million+ levels! As an extra you could setup level building competitions and bring out a version of the Angry Birds based purely on the best custom built levels. Everyone's a winner!
The evening was great fun and all the speakers were brilliant. My only criticism would be that the talks seemed very rushed. Making the talks fifteen minutes instead of ten would have allowed for a slightly slower pace with a few more demos. Big thank you to Mozilla Labs, Six to Start and all the speakers.
--- End: Game On London 2010
--- Start: Periodic Mashup
Published on: 01 December 2010
https://nooshu.com/blog/2010/12/01/periodic-mashup/
Main Content:
Every so often I stop work and stick my head above the parapet and see what the rest of the Web Developer community is doing, and every time I do I'm amazed by some of the ideas and applications that are being built. They aren't always useful but who cares; the technology is available so why not try it and push the boundaries a little.

The first application I really like is Mashupbreakdown by developer Benjamin Rahn. Mashupbreakdown is a visual representation of the samples used in the latest album by Girl Talk called "All Day". That in itself is very cool, but where does it get the sample information from? Well that's the really clever part; it gets it from Wikipedia.
Wikipedia has a page for the "All Day" album that contains all the sample information used in each track. Mashupbreakdown scrapes this page and and visualises it. Since Wikipedia can be edited by anyone, if you spot a mistake / new sample you can easily update the page information and the application with change accordingly!
At the moment it only shows one album but there's no reason the application can't be adapted to handle more albums. Benjamin has a post on his blog appealing for more breakdowns so I'll be checking back with the site now and then to see if any other breakdowns have appeared. Great work Benjamin.
The second application that really caught by eye is the Periodic Table of Elements by developer Josh Duck. When I find a site I like, I immediately do a "view source" (don't all Web Develepers?) to see how it's been built. The Periodic Table of Elements takes any URL you pass it and tells you what HTML elements were used on the page. It's basically a prettified / simplified version of view source! The application may not be that useful but kudos to Josh for taking the time to build it. Definitely one of those ideas that I wish I'd thought of!
--- End: Periodic Mashup
--- Start: Nasty Canvas Image Data Error
Published on: 23 November 2010
https://nooshu.com/blog/2010/11/23/nasty-canvas-image-data-error/
Main Content:
Last night I decided to revisit an experiment I wrote earlier in the year: Using Image Data Inside the HTML5 Canvas Element. It involved loading 2 - 3 images and swapping out the image data depending on the mouse position. I ran into a slight issue though, it wasn't working:
uncaught exception: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIDOMCanvasRenderingContext2D.drawImage]" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: /lab/experiments/canvas-image-data/js/ci.js :: anonymous :: line 27" data: no]
Not good! I double checked the code on my local machine and it worked. Very odd! I noticed that it wasn't working when you first hit the page but was on page reload. Then it struck me; it must be a caching issue. I was correct.
It turns out that the JavaScript was firing before all the images had fully loaded.
context.drawImage(lakeImage, 0, 0);
var originalLakeImageData = context.getImageData(0,0, iWidth, iHeight);
The above lines were trying to access ImageData that didn't exist yet and the browser was falling over because of it. Doh! Luckily I'd used jQuery for a couple of functions in the experiment so I quickly wrapped the code in a load method, problem solved!
$(window).load(function(){
//Your code here
});
This method waits until the whole page has loaded (including images) before the code inside it is fired, guaranteeing the image data is there to be manipulated when needed. View the updated demo.
--- End: Nasty Canvas Image Data Error
--- Start: Full Frontal 2010
Published on: 17 November 2010
https://nooshu.com/blog/2010/11/17/full-frontal-2010/
Main Content:
Last Friday I had the pleasure of attending Full Frontal 2010 which was held at the Duke of York's cinema, Brighton. A super venue for an extremely informative and entertaining 1 day JavaScript conference. After attending in 2009 I didn't want to miss out this year. If you've never been to the Duke of York's cinema it's well worth a visit; be warned though, the seats are very comfy and it's quite hard to stay awake at times!
There were some truly excellent talks, ranging from IE6 and ChromeFrame to the latest developments in HTML5 and the mobile web. Big thank you to all the speakers they did a superb job:
Alex Russell: Excellent talk on ChromeFrame, an IE browser plug-in that replaces the IE render engine with that of Chrome (if enabled via a meta tag). He didn't have many kind words to say about IE but then again who does.
Jan Lehnardt: Very informative talk on the mobile web, specifically some of the issues surrounding it. He then switched to CouchDB and how it could be used on a mobile device. CouchDB is a very powerful document-oriented database that can be accessed from anywhere that allows HTTP requests.
Paul Rouget: My favourite talk of the day. Paul is a development guru who works for Mozilla and his talk was on a few of the features we should look out for in Firefox 4. This included the Audio Data API, FileAPI and WebGL. WebGL looks, well, amazing!
Paul Bakaus: Who would have thought you could use JavaScript and the DOM to create a powerful gaming platform. Well Paul showed us you can by demoing his latest prototype using the Aves Engine to create a “Sims” like game… in JavaScript!
Dan Webb: Dan works or Twitter as a Front End Engineer. His talk was on how to get around the pesky same-origin problem when pulling in data from other sites. We have JSON-P sure, but there are other methods too; like postMessage, CORS and that old favourite the iframe.
Brian LeRoux: Brian is a developer on a product called PhoneGap which aims to plug the gaps for mobile developers and encourage handset creators into providing better API's.
Seb Lee-Delisle: Seb is a very well known Flash developer but he also has many other skill sets up his sleeve. His talk ranged from 2D particles all the way to the Unity 3D Game Development tool. Incredibly inspirational talk with stunning demos. The future looks very exciting indeed!
The highlight for me was defiantly Paul Rougets talk on "Batshit crazy stuff you'll be able to do in browsers". He demonstrated a selection of custom builds of Firefox 4 and left everyone gob smacked with what HTML5 has in store. Using WebGL and the Audio Data API to create a 3D scene that reacts to the music as well as illustrating how useful the new Drag and Drop File API can be. As a bonus he even patched a version of Firefox to interface directly with his web-cam and take a photo and manipulated it via the browser; no plug-ins required! Just wow!
Big thank you to Remy and Julie for taking the time to organise this years event; hopefully I get to go again in 2011.
--- End: Full Frontal 2010
--- Start: Internet Explorer 9 Preview 6, we have a winner
Published on: 08 November 2010
https://nooshu.com/blog/2010/11/08/internet-explorer-9-preview-6-we-have-a-winner/
Main Content:
No you aren't dreaming; winner and Internet Explorer (IE) have been mentioned in the same sentence. I know it's hard to believe, but the browser that has been the bane of every Web Developer's life since 2001 has finally grown up and accepted web standards. According to the W3C HTML5 Test Suite released last week, IE9 p6 is the most compliant browser. Now before the huge (geek) party and dancing on the grave of IE6 starts, there are a couple of major points to note:
IE9 is still only a preview release, not a complete browser.
When released IE9 will only work on Vista and Windows 7.
Point 2 is unfortunately a big party pooper. Windows XP is the operating system that refuses to die, 48% of users who visited W3schools in October were on XP. That's a large percentage of people who are excluded from installing IE9. We can always hope that these users are using a standards compliant browser from another company (Firefox, Chrome, Safari, Opera) but that may be a little optimistic.
So, even though IE9 is a huge step forward by Microsoft, it doesn't look like older versions of IE are going to die out any time soon. Luckily the UK government are forward thinkers... wait, no, that's a lie. So the browser that's been crippling the web for the best part of a decade looks like it may be around for another 10 years. I'll put the party poppers back in the draw then.
--- End: Internet Explorer 9 Preview 6, we have a winner
--- Start: WordPress plug-ins and svn:externals
Published on: 03 November 2010
https://nooshu.com/blog/2010/11/03/wordpress-plug-ins-and-svnexternals/
Main Content:
So last week I decided to play with the post-commit hook in Subversion which allows you to easily update your WordPress install after committing changes to your repository. After some trial and error this works perfectly. One issue you may run into with WordPress when it's committed to SVN is using the auto-update plug-in function.
Committing your plug-ins to SVN tends to break this (very cool) auto-update functionality. SVN adds a hidden .svn directory to each directory you commit. WordPress auto-update tries to delete the updating plug-ins folder before downloading and extracting the new version into the wp-content/plugins directory. WordPress isn't able to delete the .svn directories so the auto update process fails, leaving you without the plug-in you were trying to update (since it deleted it before failing).
So what's the solution? Well you could download the latest plug-in version and manually extract / commit it to your repository; but that's too long winded (and boring). The ideal solution lies in the use of the svn:externals property. It allows you to attach an external repository location to a folder in your own repository. Since all WordPress plug-ins are hosted in the WordPress repository you can update all your plug-in's directly from there with a quick "SVN Update"! Perfect!
You can do this via SSH and the command line or you can do it via a SVN client with a GUI (I use TortoiseSVN). I'll be showing you how to do it via the GUI.
First you need to remove the plug-in you want to update from your repository if it's been added. This may seem a little strange as you are trying to update it; but we need to update from an external repository and if a version already exists it will fail:
Next you need to setup your svn:externals property on the wp-content/**plugins** directory via the properties menu:
Now for the tedious bit. For all the plug-ins you want SVN to auto-update, you will need to find the WordPress repository URL for. So for the example, to update Akismet and All in One SEO pack you will enter the following:
akismet http://plugins.svn.wordpress.org/akismet/trunk/
all-in-one-seo-pack http://plugins.svn.wordpress.org/all-in-one-seo-pack/trunk/
Once you've added all the plug-ins you want to auto-update (remember to remove them first if they already exist in your repository!) commit your changes. Then watch the magic happen via an update:
Akismet and All in One SEO Pack have been checked out from the WordPress repository trunk. Every time you do an update SVN will check for new versions of the plug-ins. Great stuff! There is a slight warning with checking out from trunk; the developer could be working on a new release and unfinished code may have been committed, so the plug-in may be broken if updating from trunk! To get around this you may want to checkout from the plug-in tags (final versions) instead. To do that change the repository URLs to:
akismet http://plugins.svn.wordpress.org/akismet/tags/2.4.0/
all-in-one-seo-pack http://plugins.svn.wordpress.org/all-in-one-seo-pack/tags/1.6.9/
Unfortunately this will involve changing your svn:externals property every time a new version of a plug-in comes out, but it's less likely your plug-ins will break. Note: Remember to replace the tag version number with the latest version.
I hope this little tip helps you streamline your deployment!
P.S. On a side note, if anybody knows how to auto update from a tag automatically please leave a comment, I'd love to know if it's possible.
--- End: WordPress plug-ins and svn:externals
--- Start: SVN post-commit hook on Dreamhost
Published on: 24 October 2010
https://nooshu.com/blog/2010/10/24/svn-post-commit-hook-on-dreamhost/
Main Content:
Over the past couple of days I decided to start using the SVN post-commit hook for deploying sites to my staging servers. Once you get it working it will save you a massive amount of time. Make changes on your local server, then, when you're ready, commit your changes to the repository and the server will auto-update the staging site. Nice! For instructions on how to set this up on your Dreamhost server take a look here.
Unfortunately a slight over-site on my part didn't make deployment easy. I followed the instructions to the letter (more than once!) but received the same error on commit:
post-commit hook failed (exit code 255) with no output.
At first I thought this was a permissions issue but that turned out not to be the case. The solution in the end was because I was saving the do_update.cgi script in Windows format in Notepad++! Doh! Windows and UNIX new lines just don't mix!
To save a file in UNIX compatibility mode in Notepad++ click "Edit" then "EOL Conversion". Make sure UNIX Format is greyed out (why greyed out? no idea) when you save your CGI script. Upload to the server and you're done. Won't be forgetting to do that again any time soon!
--- End: SVN post-commit hook on Dreamhost
--- Start: Page not found with custom post types
Published on: 20 October 2010
https://nooshu.com/blog/2010/10/20/page-not-found-with-custom-post-types/
Main Content:
IMPORTANT NOTE: Using the flush_rewrite_rules on the init hook is VERY expensive and shouldn't be used in this way. It is possible this call will slow down your website dramatically, maybe even bring your site down! The correct way to solve this issue is by flushing permalinks / rewrite rules. You can do this by visiting the permalinks page, running wp rewrite flush on the command line, or using flush_rewrite_rules only once.
Just a quick post on a very frustrating problem I was having with WordPress and the new custom post types introduced in version 3.0. Everything was rolling along smoothly until it came to actually viewing one of the custom posts... 404 error. Weird, maybe a .htaccess issue... nope that's all good, spelling error.. nope. Long story short, this tinkering went on for a good couple of hours and the problem wouldn't go away.... cry! I tried everything I could think of but nothing helped. I could view the post pages with permalinks turned off, but it failed with them turned on.
After hours of frustration I stumbled upon a similar forum post with the answer:
flush_rewrite_rules( false );
Hours of frustration over such a simple fix. Sods law I guess. Add this code to the function you use to register your custom post type like so (usually in your themes functions.php):
function post_type_myposttype() {
$labels = array(
/* Labels here */
);
register_post_type(
'myposttype',
array(
'labels' => $labels,
'singular_label' => __('My Post Type'),
/* More settings etc */
'rewrite' => array('slug' => 'custom-post-slug'),
'query_var' => false,
'supports' => array(
'title',
'editor',
'author',
'thumbnail',
'excerpt',
'custom-fields',
'revisions')
));
/* IMPORTANT: Only use once if you have too, see important note at the top of the page for details. */
flush_rewrite_rules( false );
}
//Initialise custom post type
add_action('init', 'post_type_myposttype');
No more 404 errors! Huzzah! One last tip: make sure you turn off any caching plug-ins (DB-Cache reloaded, Hypercache etc) before you start redeveloping your WordPress blog. Yes I made that mistake too! Yesterday evening is one I wish to forget...
Update: If you are adding custom taxonomies to your post types you may need to add the flush rewrite rules to the function when you initialise them:
function create_custom_taxonomies(){
register_taxonomy('taxonomy1', 'posttypename', array( 'hierarchical' => true, 'label' => 'Taxonomy1'));
register_taxonomy('taxonomy2', 'posttypename', array( 'hierarchical' => true, 'label' => 'Taxonomy2'));
/* IMPORTANT: This is bad! Don't do this! Read the important update at the top of the page, and update 2 below for details */
flush_rewrite_rules( false );/* Please read "Update 2" before adding this line */
}
add_action('init', 'create_custom_taxonomies' );
Update 2: Adding flush_rewrite_rules in the places mentioned above will force a flush for every page load. This is bad! For a better solution see Kens comment below.
Add your register_post_type to init, then add a function to with register_activation_hook that itself adds an action to init (priority 11) that in turn flushes the rewrite.
This way you don't flush on every single page load (which is bad).
Alternatively you could add the flush_rewrite_rules where suggested and reload your page; this will flush the rewrite rules and fix the 404 errors. Remember to remove or comment out the flush_rewrite_rules line after as it's no longer needed! Thanks Ken for this update.
--- End: Page not found with custom post types
--- Start: In memory of Benoit Mandelbrot
Published on: 18 October 2010
https://nooshu.com/blog/2010/10/18/in-memory-of-benoit-mandelbrot/
Main Content:
It was a sad day for Mathematics over the weekend, the visionary Benoit Mandelbrot died of cancer aged 85 years. Many people may not recognise his name but they will certainly recognise the fractals he helped to discover. Below is the beautiful Julia set, named after the French Mathematician Gaston Julia. There's also a Mandelbrot set named after the man himself; it's actually possible to "zoom in" to the Julia Set from the Mandelbrot set (see the Wikipedia article)... amazing!
In February 2010, Mandelbrot was invited to speak at Technology, Entertainment, Design. See below for &"Fractals and the art of roughness" a truly inspiring TED talk. RIP Benoit Mandelbrot.
--- End: In memory of Benoit Mandelbrot
--- Start: jCarousel missing item width
Published on: 12 October 2010
https://nooshu.com/blog/2010/10/12/jcarousel-missing-item-width/
Main Content:
On a recent project the UX team put together a set of wireframes where the use of carousels featured heavily. Luckily when you choose a JavaScript library like jQuery you have quite a few carousel plug-ins to choose from. I've used various different ones in the past, but my favorite is called jCarousel. You only have to take a quick look at the jCarousel homepage to see that it will do pretty much anything you ask of it. So in theory it should be a case of copy / paste the code into your site and you're away. Unfortunately Web Development doesn't always work that way; a small oversight can leave you racking your brains for hours... arghh!
The design and layout layout had already been created in the usual fashion. All that was left to do was to layer on all the JavaScript goodies (the fun part!). While implementing jCarousel I ran into a curious console error message:
"jCarousel: No width/height set for items. This will cause an infinite loop. Aborting..."
When I checked the carousel CSS, the item width had been set:
.product {
float: left;
display: inline;
text-align: center;
font-size: 0.75em;
width: 75px;
}
Strange. The width had been set, so the error message must be from something else. After a few minutes investigation it turned out that the carousel didn't have a parent with a set width. When fired the carousel is wrapped with two divs; one wraps the carousel, the other wraps the carousel and the navigation. Neither of these divs have an explicit width set which is what was causing the problem. It was a very quick fix in the end:
.jcarousel-container {
padding: 20px 0 0;
width: 300px;/* Fixed! */
}
Upon a little more investigation it seems you can fix this issue in other ways too. Instead of using a class of "product" to set the item widths I tried using the following:
#carousel li {/* New selector also fixed it! */
/*...*/
font-size: 0.75em;
width: 75px;
}
Very strange! The CSS in both cases changes the same elements, it just ignored the width in the 'product' class.
So for anyone else encountering the same 'No width/height set for items' issue here's a quick check list for you to try:
Make sure you set a width on the items (duh!). Maybe try different CSS selectors if necessary.
Set a width on the 'jcarousel-container' class or one of its parents.
If all else fails, adapt one of the skin examples bundled with jCarousel.
The last one is very annoying if you have your carousel already styled up, but it is guaranteed to work.
--- End: jCarousel missing item width
--- Start: Goodbye Aptana, hello Komodo Edit
Published on: 01 October 2010
https://nooshu.com/blog/2010/10/01/goodbye-aptana-hello-komodo-edit/
Main Content:
I've been using Aptana IDE for a good few years now, before that I used Eclipse IDE. As Aptana is based on Eclipse, moving between them was very easy with only minor differences between the two. Unfortunately I find the Eclipse platform as a whole very bloated. As a Web Developer there are just so many functions and features I'm never going to use. The bloat kills the IDEs startup time and after a while this becomes very annoying. So I decided it's time to find an alternative.
Talking to a fellow developer recently he recommended Komodo Edit (free), which is essentially a cut down version of Komodo IDE (not free). The list of features it supports is huge, way to many to list in this blog post but here are the ones that really caught my eye:
Supports multiple client-side and server-side technologies (HTML, CSS, JavaScript, PHP, Python)
No fuss auto-completion on many languages (this was sometimes an issue for me in Aptana).
Supports various JavaScript libraries for auto-completion (enabled via preferences).
Support for code snippets at the click of a button; helps cut down on some of the monkey work.
XPI extensions available. What makes Firefox so great is it's many extensions. This is also possible in Komodo.
There's an extension for Zen coding available (yay!).
It hasn't been all plain sailing though, there are a few features that I miss from Aptana:
Integration with Subversion (I'm guessing this is a Komodo IDE feature).
JSlint for the JavaScript, but I have seen an extension available so this may be possible.
Aptanas auto-complete feature for CSS showed what browsers were supported by the typed property, which was quite handy at times.
Aptana used to add the trailing ; in CSS to properties (it's amazing how much you miss this feature when it isn't there!).
These aren't major issues, certainly not big enough to keep me using Aptana. Hopefully as the Komodo community grows more extensions and (useful) features will be developed. As long it stays quick to load and use, I'll be happy!
Update: After using Komodo for a few more days I've noticed a couple more little bugs / annoyances:
Auto-completing a paragraph tag automatically inserts class='classname', not quite sure why I'd need a class for every paragraph. Maybe there's a preference for this?
When you paste in a long line of text it seems to "drop off" the end of the page and isn't recognised by the horizontal scrollbar. The only way to solve this is to use the right scrollbar arrow. Very weird!
When indenting multiple lines of code using the 'Tab' key it seems to fail and only indent the line directly below the selected text. Another strange one.
There's a beta release of version 6 out available on the website, maybe they have been reported and fixed. I'll install it and see what happens. Fingers crossed!
--- End: Goodbye Aptana, hello Komodo Edit
--- Start: JS1k: We have a winner!
Published on: 27 September 2010
https://nooshu.com/blog/2010/09/27/js1k-we-have-a-winner/
Main Content:
If you've been following my blog posts over the past couple of months you will have seen JS1k being mentioned quite a few times. If not the idea is simple; create something cool with JavaScript using only 1024 bytes. Now you may think that you can't do much with 1Kb, but you'd be wrong! Just take a look at the 1st place entry:
The author Marijn Haverbeke has created a very cool little platform game that's actually very playable. As you jump from block to block and move through the level to collect the gold coins, the game gets progressively harder. How exactly did he do that I hear you ask; well using this code of course:
c=document.body.children[0];h=t=150;L=w=c.width=800;u=D=50;H=[];R=Math.random;for($ in C=
c.getContext('2d'))C[$[J=X=Y=0]+($[6]||'')]=C[$];setInterval("if(D)for(x=405,i=y=I=0;i<1e4;)L=\
H[i++]=i<9|L9?0:X;j=H[o=\
x/u|0];Y=y9&S<41;ta(u-S,0);G=cL(0,T=H[i],0,T+9);T%6||(A(2,25,T-7\
,5),y^j||B&&(H[i]-=.1,I++));G.P=G.addColorStop;G.P(0,i%7?'#7e3':(i^o||y^T||(y=H[i]+=$/99),\
'#c7a'\));G.P(1,'#ca6');i%4&&A(6,t/2%200,9,i%2?27:33);m(-6,h);qt(-6,T,3,T);l(47,T);qt(56,T,56,\
h);A(G);i%3?0:T$-9?1:D);ta(S-u,0)}A(6,u,y-9,11);A(5,M=u+X*.7,Q=y-9+Y/5,8);A(8,M,Q,5);fx(I+'¢',5,15)}D=y>h?1:D"
,u);onkeydown=onkeyup=function(e){E=e.type[5]?4:0;e=e.keyCode;J=e^38?J:E;X=e^37?e^39?X:E:-E}
See, simple... urghh! That's the minified source code so it won't make much sense, but Marijn has been kind enough to post the unminified code for everyone to look at in a blog post about the entry. Very impressive! I'll be taking a close look at the source when I get some spare time. Many congratulations to Marijn, superb work.
There are 10 winners in total listed on the JS1k page, all equally impressive, but here are my 5 personal favourites:
3D Snowman by romancortes
Mandelbrot with Colours by Gabor Turi
Colourful Visualisation by “Cowboy” Ben Alman
Tiny Chess by Óscar Toledo
Wobbling Tunnel by Marcin Ignac
Some excellent submissions there, I sure you'd agree. Take a look at all the submissions on the JS1k demo page.
I'd like to say a big thank you to Peter van der Zee for creating the JS1k competition, I've really enjoyed it. I'm already looking forward to next year. On a side note, just imagine what's possible with 2048 bytes!
--- End: JS1k: We have a winner!
--- Start: Adding a custom header image to your WordPress theme
Published on: 23 September 2010
https://nooshu.com/blog/2010/09/23/adding-a-custom-header-image-to-your-wordpress-theme/
Main Content:
Every new iteration of WordPress (version 3.0.1 at the time of writing) brings a host of new features and bug fixes. One feature that I completely missed in 3.0 was the new custom header functionality. Before 3.0 it would be a case of hacking together your own solution using custom fields or using a separate plug-in. Thankfully the WordPress team have added this functionality directly to the core.
It just so happens that I've had a request for a customisable header image on an future project, so decided to have a play and see how difficult it is to implement. Well it isn't difficult at all, very simple in fact.
First you will need to edit your functions.php located in your theme directory. Go ahead and create one if it isn't in the directory. Now copy and paste the code below into the file. I've commented the code but it's all quite self explanatory. Change the height and width of the image and change the directories where needed.
array (
'url' => '%s/header/default.jpg',
'thumbnail_url' => '%s/header/thumbnails/pb-thumbnail.jpg',
'description' => __( 'Perfect Beach', 'customisetheme' )
),
//Image 2
'tiger' => array (
'url' => '%s/header/tiger.jpg',
'thumbnail_url' => '%s/header/thumbnails/tiger-thumbnail.jpg',
'description' => __( 'Tiger', 'customisetheme' )
),
//Image 3
'lunar' => array (
'url' => '%s/header/lunar.jpg',
'thumbnail_url' => '%s/header/thumbnails/lunar-thumbnail.jpg',
'description' => __( 'Lunar', 'customisetheme' )
)
);
//Register the images with Wordpress
register_default_headers($customHeaders);
}
endif;
if ( ! function_exists( 'customisetheme_admin_header_style' ) ) :
//Function fired and inline styles added to the admin panel
//Customise as required
function customisetheme_admin_header_style() {
?>
By adding the code above you will now see a new option under 'Appearance' in the admin panel called 'Header'. From there you should be able to see all the images and options we just set in the functions.php file. The only thing left to do now is add the header image to the theme.
Where you place the following code will be depend on your theme setup; I've decided to place it in the header.php file as I want the image to appear on every page. You may only want the image to appear on specific templates e.g. pages, archive, category (you could also use WordPress conditional tags to do this).
And there you have it, one header image that you can customise via the WordPress admin panel. An ID is attached to the image for CSS styling where needed.
The example above is quite a simplified version of the header image functionality. It is possible to place text over the image and even have a different image per blog post by using the custom thumbnail functionality, but these are beyond the scope of this blog post. Copy & paste and enjoy!
--- End: Adding a custom header image to your WordPress theme
--- Start: Drupal Love! Stuff I've learnt!
Published on: 09 September 2010
https://nooshu.com/blog/2010/09/09/drupal-love-stuff-ive-learnt/
Main Content:
I created a post a couple of months ago about how I was learning Drupal for an up and coming project; well that project finally went live this week. Huzzah! It wasn't all smooth sailing; there was lots of trial and error, head scratching and a few mini panics, but I got there in the end. It's amazing what you learn over the course of a project. Any future Drupal projects will be so much quicker and easier to setup due to the fact that I now actually know how to use Drupal!
So anyway here are a few things I learnt along the way:
There are some very simple yet powerful templating rules you can use to style your website. Learning how they work will really help you style specific pages and blocks.
Looking for some functionality that is missing by default? I bet there's already a module that does the job. Check out Drupal modules, this excellent website lists and rates thousands of Drupal modules which you can install and use.
If you do find a module that adds the functionality you need, double check that there aren't other modules about that do it better. Since Drupal has been around for some time, many modules haven't been updated in quite a while so they may just be occupying the name space. It's always best to check before you dive into using one particular module as it may not always be the best route to take.
Learn how to use the Content Construction Kit (CCK). If you are missing a type of CCK field, look for an additional module; I'm sure there will be one you can install that does the job. You really can make content types do anything you want with CCK.
Learn how to use the Views module. I really can't express this point enough. The Views module is without a doubt one of the most powerful additions to any CMS I've ever come across. With it you can take any content and display it however you like on a page. The layout is a little intimidating at first, but once you get your head round it you will have a dynamic site up and running in no time at all.
Install the ImageCache module. It ties in with both CCK and Views allowing you to upload and display images on your site however you need to. If you add a new image preset the module will automatically iterate over old images so you never have to go in and manually adjust images if you change your site design / functionality.
One thing I missed from Drupal was the ability to add parent / child nodes. Luckily theres a module called Node Hierarchy that will add this functionality. It even handles the breadcrumbs and Views for you. Note: Make sure you don't have ‘Taxonomy breadcrumb' enabled with Node Hierarchy as the breadcrumbs won't work. I learnt that the hard way!
Hopefully other budding Drupal users found the tips helpful. I'm still a Drupal novice, but now I know the basics the site possibilities are endless.
--- End: Drupal Love! Stuff I've learnt!
--- Start: The beauty of the Mandelbrot set
Published on: 18 August 2010
https://nooshu.com/blog/2010/08/18/the-beauty-of-the-mandelbrot-set/
Main Content:
In the past I've dabbled with fractals using the lovely HTML5 canvas element and JavaScript, so this video really caught my attention. You start with a "simple" Mandelbrot fractal, pick a point and zoom in. It all sounds so easy doesn't it! Well that's what Team Fresh did a few months ago, and as it says in the video description it took 2 days to setup the 6 months to render! Wow that's a lot of render time; the results were certainly worth the wait:
As you zoom further into the Mandelbrot it becomes more and more complex. You can really tell in the last 4 - 5 minutes as it started to hurt my eyes after a while. So how far 'in' did the video zoom? Only 6.066 e228 (2^760)... that's a huge number (huge doesn't even come close to describing it)! The size of the Milky Way galaxy is 'only' 1.0 e21! At times tt looks like the camera is panning across the fractal when in fact it is constantly zooming into one point. And that point is... well I think you better just read the description for the video as it's a very long set of co-ordinates! Excellent work Team Fresh, I'll certainly be checking the website often.
--- End: The beauty of the Mandelbrot set
--- Start: Aloha Editor - Content editing the HTML5 way
Published on: 17 August 2010
https://nooshu.com/blog/2010/08/17/aloha-editor-content-editing-the-html5-way/
Main Content:
The number of times I've built a website based on a CMS only to have the client utter the words "Oh I'm confused, it'd be so much quicker if you made the changes". Right, so the CMS was a bit of a waste of time then! But fingers crossed thanks to Aloha Editor that may be a thing of the past. Often the problem clients have is actually finding the content that needs to be edited in the CMS; Aloha to the rescue!
What Aloha actually does is make the content editable right on the page; no need to jump into the CMS, find the page, make the changes then preview the result. Just click on the text you wish to edit and type away. Done! It's hard to believe it actually works until you try it. Why not give it a go on their demo page. It incorporates a few HTML5 technologies which could cause issues with older IE versions, but the demo page seems to work (with a few quirks).
The core has been written to be very small and streamlined, with additional functionality being added by the way of user contributed plug-ins. There's already an extensive API for developers to play with so I'm sure many of the missing features will be plugged very soon.
There are alternatives about such as TinyMCE and CKEditor, but they're integrated directly into a CMS' administration pages rather than as an inline editor like Aloha. Now before you get too excited there are a few cons:
It isn't as simple as just dropping the scripts into a page, it needs to be integrated into a backend system for the changes to be saved.
Still in early development so could be quite buggy.
Doesn't work with Opera Browser at the moment but this is being worked on.
Some features aren't available yet, like image / media insertion. But I'm sure these will be developed as it matures.
So there are still a few issues to iron out but it all looks very promising! There were even murmurs on Twitter today about a WordPress plug-in and a Drupal v7 module (not 6 though I presume) in development. So it won't be long before we'll be able to try it out on a live site; hopefully it's also simple enough for clients to use too!
--- End: Aloha Editor - Content editing the HTML5 way
--- Start: JS1k: Original source
Published on: 16 August 2010
https://nooshu.com/blog/2010/08/16/js1k-original-source/
Main Content:
Unfortunately I haven't been able to put together another JS1k demo as I've had lots of 'real' work going on at the moment (boo!); so I thought I'd post a fully commented version of the JavaScript code for anyone who is interested to look over.
Some of the entries have been breathtaking, making my poor little demo look a little simple! Never mind. I look forward to looking over the uncompressed source of the other entries. There are just so many things to learn from them!
/**
* This uncompressed source is close to my entry submitted to JS1k.
* The number of particles and colours are different, but the rest is
* near enough the same. The code is structured in a much neater way.
*/
var animate = function(){
//Grab our canvas object and context
var canvas = document.getElementById('c');
var c = canvas.getContext('2d');
//Set the canvas width to the same as the browser
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
//Make the body background black and hide the scroll bars
document.body.style.background = "black";
document.body.style.overflow = "hidden";
//Grab the width / height of the canvas for later use
var width = canvas.width,
height = canvas.height;
//Arrays used to store the position / speed / direction and radius of the particles
var posY = [],
posX = [],
speedX = [],
speedY = [],
directionX = [],
directionY = [],
radius = [];
return {
//Our initialise function
init: function(){
//Look at the width and generate a number of particles
for(i = 10; i < width; i += 30) {
//For each ballplace it in a random location
var generatedX = Math.floor(Math.random()*width);
var generatedY = Math.floor(Math.random()*height);
//Set the initial particle start positions
posX[i] = generatedX;
posY[i] = generatedY;
//Each particle has a random x and y speed
var generatedSpeedX = 1 + Math.ceil(Math.random()*8);
var generatedSpeedY = 1 + Math.ceil(Math.random()*8);
//Set the initial speeds
speedX[i] = generatedSpeedX;
speedY[i] = generatedSpeedY;
//Set the x and y directions of each particle
(Math.ceil(Math.random()*2) === 1) ? directionX[i] = 1 : directionX[i] = -1;
(Math.ceil(Math.random()*2) === 1) ? directionY[i] = 1 : directionY[i] = -1;
//Each particle has a different radius
radius[i] = 10 + Math.ceil(Math.random()*5);
}
//Fire our draw function every 10ms
setInterval(this.draw, 20);
},
//Fun this function to draw a frame
draw: function(){
//Clear the last frame by filling it black (clearRect caused issues in chrome)
c.fillStyle = "black";
c.fillRect(0,0,width,height);
//Loop through each particle
for(i=10;i width || posX[i] < 0){
directionX[i] *= -1;
}
//Change its y direction if it gets to the boundry
if(posY[i] > height || posY[i] < 0){
directionY[i] *= -1;
}
//Save the canvas settings before we modify anything (clip)
c.save();//Before path
//For each particle begin a path around its position
c.beginPath();
c.arc(posX[i],posY[i],radius[i],0,Math.PI * 2,false);
//Clip the path ready to be filled later
c.clip();
//Set the red radial gradient alpha to 1
c.globalAlpha = 1;
//Create our red radial gradient up the top left corner
var radGradRed = c.createRadialGradient(width/4,height/4,100,width/4,height/4,width/4);
radGradRed.addColorStop(0, 'red');
radGradRed.addColorStop(1, 'black');
c.fillStyle = radGradRed;
//Create a rectangle filled using the red radial
c.fillRect(0,0,width,height);
//Set the global alpha to 0.6 for the next box (so the red shines through)
c.globalAlpha = 0.6;
//Create our green radial gradient up the top right corner
var radGradGreen = c.createRadialGradient(3*width/4,height/4,100,3*width/4,height/4,width/4);
radGradGreen.addColorStop(0, 'green');
radGradGreen.addColorStop(1, 'black');
c.fillStyle = radGradGreen;
//Create a rectangle filled using the green radial
c.fillRect(0,0, width, height);
//Set the global alpha to 0.4 for the next box (red / green shines through)
c.globalAlpha = 0.4;
//Create our blue radial gradient at the bottom middle
var radGradBlue = c.createRadialGradient(width/2,3*height/4,100,width/2,3*height/4,width/4);
radGradBlue.addColorStop(0, 'blue');
radGradBlue.addColorStop(1, 'black');
c.fillStyle = radGradBlue;
//Create a rectangle filled using the green radial
c.fillRect(0,0,width,height);
//Restore the canvas to how it was before the clipping path
c.restore();
//Set the new x and y position of the selected particle
posX[i] += directionX[i]*speedX[i];
posY[i] += directionY[i]*speedY[i];
}
//Set the new global alpha to 0.9 for the static particles
c.globalAlpha = 0.9;
//Create a red particle top left
c.fillStyle = "red";
c.beginPath();
c.arc(width/4,height/4, 20, 0, Math.PI * 2, false);
c.fill();
//Create a green particle top right
c.fillStyle = "green";
c.beginPath();
c.arc(3*width/4, height/4, 20, 0, Math.PI * 2, false);
c.fill();
//Create a blue particle middle bottom
c.fillStyle = "blue";
c.beginPath();
c.arc(width/2, 3*height/4, 20, 0, Math.PI * 2, false);
c.fill();
}
};
}();
//Call the init function and get the particles moving
animate.init();
Or for those of you who are a fans of jsFiddle I've pasted it here for you look at.
--- End: JS1k: Original source
--- Start: JS1k: JavaScript Optimisations
Published on: 05 August 2010
https://nooshu.com/blog/2010/08/05/js1k-javascript-optimisations/
Main Content:
Following up on my post on JS1k I thought I'd put together a small list of optimisations you can use if you're looking to minify your code before compressing it. When you only have 1024 bytes to play with every byte counts!
Very obvious, store your objects for later use. You may need to use the document / context later so store them in a single byte variable.
//From:
var canvas = document.getElementById('c')
var context = canvas.getContext('2d')
//To:
d=document
t=d.getElementById('c')
c=t.getContext('2d')
If you are using Math object / functions, don't repeat 'Math' over and over. It may not look much at first but it will pay off and save you loads of bytes
//From:
var colour = Math.floor(Math.random()*255);
//To:
M=Math
R=M.random
L=M.floor
colour = L(R()*255)
I found myself using 2 Pi and false quite a lot in the arc method, so why not minify them too.
//From:
context.arc(posX, posY, radius, 0, Math.PI*2, false);
//To (uses Math example above too):
P=M.PI*2
f=false
context.arc(posX, posY, radius, 0, P, f);
For your 'draw' function use an anonymous function within setInterval(). This will save you around 5 bytes.
//From:
function d(){
//Code goes here...
}
setInterval(d,9)
//To:
setInterval(function(){
//Code goes here...
},9)
When it comes to the canvas API it is necessary to minimise it's usage at times since the methods can't be stored like we did with the Math object. For that I used a mixture of arrays and for while loops.
//From:
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(50, 100, 10, 0, Math.PI*2, false);
ctx.closePath();
ctx.fill();
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(143, 230, 15, 0, Math.PI*2, false);
ctx.closePath();
ctx.fill();//Add more if needed...
//To:
A=["red",50,100,10,"blue",143,230,15];
i=2;while(i--){
D=i*4;
ctx.fillStyle = A[D];
ctx.beginPath();
ctx.arc(A[D+1], A[D+2], A[D+3], 0, P, f);//We stored 2Pi and false in a var above
//removed closepath() as this is done when fill is called
ctx.fill();
}
Another quite obvious one, use the ternary operator instead of an if else statement.
//From:
if(Math.ceil(Math.random()*2) == 1){
var result = 1
} else {
result = -1
}
//To:
Math.ceil(Math.random()*2) == 1 ? result = 1:result = -1
//Remember you can minify the Math functions
An excellent couple of tips from Ben Almans blog post.
/*Backwards iterating while loop*/
//From:
for(i=0;i<20;i++){} //19 bytes
//To:
i=20;while(i--){} //17 bytes
/*Use 'this' instead of 'window'*/
//From:
w=window
//To:
w=this
Hopefully you've found some of these JavaScript short-cuts useful. Have any more to add to the list?
--- End: JS1k: JavaScript Optimisations
--- Start: Learning HTML5 Canvas
Published on: 29 July 2010
https://nooshu.com/blog/2010/07/29/learning-html5-canvas/
Main Content:
For a good while now I've been wanting to explore generating visualisations using JavaScript, and there really hasn't been an easier time to do it with web technologies like Canvas and Processing (via processing.js). As with all things in life there's never enough hours in the day to do everything. I've had the excellent book by Daniel Shiffman, 'Learning Processing' which I'm about 4 chapters into; stareing back at me on my desk for 8 months now. It's all bright and orange and full of cool stuff! But alas no time... until now. Time for me to pull my finger out and learn something new.
In terms of canvas I've already gone through quite a few tutorials on the API and how it works, so I'm not quite a complete beginner. If you are just starting out with canvas one set of tutorials I found particularly helpful is located at the Mozilla developer center (MDC). I must admit I'm struggling to find intermediate tutorials; lots of inspirational demonstrations but the code can make your head hurt due to its complexity.
I've compiled a list of canvas related demos and sites below, which I've been reading. I'm going to concentrate on canvas for the moment then come back to Processing at a later date.
Visualisations
Liquid Particles: Loving the simplicity and the bright colours. Try leaving the particles to collect into a tight ball then rip it apart!
JuicyDrop: If you ever tried Milkdrop for Winamp you will love this port to canvas. There are four examples of the thousands of Milkdrop visualisations available.
HTML 5 Audio Experiment: Another particle based visualisation, this time mixed with audio. I don't think the particles react to the audio (correct me if I'm wrong!) as it seems to be a repeating pattern. But still very cool!
3D landscape on HTML5 Canvas: Superb 3D visualisation by Seb Lee-Delisle. Canvas may only have a 2D context at the moment but with a little JavaScript magic you can create 3D visualisations.
Technical Demos
Blowing up HTML5 video: If the addition of plug-in less video wasn't enough in HTML 5, check out this demo. Blow up a streaming video with a mouse click.
Cloth simulation: It may not sound that exciting but the demo is very clever. Pull and push the cloth with your mouse to see how the mesh changes. Maybe one day we will see Maya ported to HTML5 (it could take a while!)
Image Evolve: This has to be one of my favourite HTML5 canvas demos so far. Upload an image and watch how the computer generates the same image using overlapping polygons. The image improves over time; leave it a couple of days and a canvas based Mona Lisa can be yours!
Raycaster: If you've ever played Wolfenstein 3D this demo will look familiar. It may not look too pretty but it's a great proof of concept.
Games
HTML 5 Asteroids: If you are into retro arcade games there are plenty to choose from built with HTML5. Here's the classic 'Astroids' for your time wasting pleasure.
HTML5 Pacman: Another classic, this time Pacman. A of version of Pacman hit the news recently when Google replaced their logo with a playable version of Pacman and cost 4.2 million hours of productivity. Not bad people!
Experimenting With Textures: Much like the Raycaster technical demo above only a little more advanced. The game actually looks to use some of the original Wolfenstein 3D textures. Now where are the German soldiers?
Torus: Looking for a 3D version of Tetris? Look no further as Ben Joffe has done exactly that.
Compilation Sites & Experiments
Mr Doob: If you haven't seen Mr Doobs site you've been missing out. Lots of HTML5 and Flash experiments for you to look at. You can learn lots by doing a quick view source!
Chrome Experiments: To promote their Chrome browser Google launched Chrome Experiments. The demos available really show off the speed of the V8 JavaScript engine.
Hakim.se: If you like particle visualisations you will love the site by Hakim El Hattab. The HTML5 - Keylight demo is superb.
Andrew Hoyer: I mentioned this site earlier with the cloth simulation; but Andrews other experiments are also worth looking at. If you like mathematics you will love these demos. On a side note I'm impressed with the site design too!
Wow there's a lot to look at there, with more and more coming out every day. So little time! If only I didn't have to sleep...
--- End: Learning HTML5 Canvas
--- Start: Nooshu.com now with added HTML5 goodness
Published on: 17 July 2010
https://nooshu.com/blog/2010/07/17/nooshu-com-now-with-added-html5-goodness/
Main Content:
So I finally pulled my finger out and took the HTML5 plunge over the past day or so; the Nooshu WordPress theme now has a sprinkling of HTML5. Mmmm I have that warm fuzzy feeling of completeness! In all honesty it's been an easy way to learn about the new HTML5 specifications (although they aren't complete and won't become a W3C recommendation until 2022… no that isn't a typo!).
HTML5 has added a host of new tags which have much more semantic meaning. So instead of using ‘divs' to section off areas of your page layout, you can now use:
It's certainly a welcome addition to the modern web. My favourite part of HTML5 has to be the doctype (other than the canvas element):
Look how simple it is! No more copy / paste from a previous project for this doctype.
My main concern when converting the theme to HTML5 was how it would work in IE; as IE8 supports parts of HTML5 but IE6 and IE7 not at all. When IE comes across a tag it doesn't recognise it just ignores it. Since the tags aren't recognised you won't be able to style your lovely new HTML5 template in IE6 & IE7. Lucky you can patch this missing functionality using JavaScript. Remy Sharp has created a script called html5shim, that adds the missing tags to IE. Just add the following code to your header and you will now be able to style your HTML5 tags:
The script must be in the header and must fire before the DOM is created. The script simply creates all the new HTML5 elements using the document method ‘createElement', you don't even need to attach the created elements to the DOM! Now IE will recognise the tags and you can get on with your page styling. Yay!
Those who use WordPress 3.0 may have noticed that the default Kubric theme is no more and it's been replaced with a new theme called twenty ten. The theme uses the HTML5 doctype but it doesn't use any of the new tags. I guess because of the IE issues. Maybe this will be changed in future releases.
The Nooshu theme is still a work in progress, and I'll modify areas as I learn more about the new HTML5 features. Here are a selection of links that I found incredibly useful while working on the theme:
Dive into HTML5: Read through this article and you will be well on your way to learning HTML5. It delves into the history of HTML and progresses forward right up to implementing the new specifications.
HTML5 Doctor: Looking for HTML5 related news or need some clarification of a new tag? Look no further than HTML5 Doctor. Lots of articles available for you to read and there's even the option to ask a question if you don't find the answers you are looking for.
HTML 5 Outliner: So you've created your shiny new HTML5 template; why not check it with the outliner to see if it makes sense to a user / search engine.
W3C Markup Validator: It's been a while since I've used a validator since I have one built into Firefox, but the W3C validator was very handy for pointing out attributes and tags that are no longer supported in the specifications. It also gives you a quick benchmark to aim at.
If you have any other useful HTML5 tips and links let me know via the contact form.
--- End: Nooshu.com now with added HTML5 goodness
--- Start: Looking for a new CMS for small websites
Published on: 15 July 2010
https://nooshu.com/blog/2010/07/15/looking-for-a-new-cms-for-small-websites/
Main Content:
Recently I've been looking at other small CMS solutions for future projects. For a while now I've been using Frog CMS; unfortunately development seems to have stopped which is a shame. At the weekend I stumbled across quite a major security concern with Frog involving a Cross-site request forgery (CSRF). Using Google it is even possible to find ready to be used scripts (which I won't link to here). Being hacked using CSRF is unlikely to happen as it requires a user who regularly uses the site to click on a rogue link, but even so it's quite concerning.
Now I could keep using Wolf CMS (which is a variation on Frog) but my thoughts are why keep all your eggs in one basket. If Frog is vulnerable then its likely that Wolf will be too. So time to look about for a new small CMS.
The CMS will be used for very small websites (5 - 20 pages) where MODx, Drupal and WordPress are just overkill; It gets updated regularly and is based on PHP / MySQL. I've been having a search and have found a few that look really promising:
Textpattern
Very clean looking CMS (love the typography on its homepage... not that it matters) and having tried the demo I can see the admin interface is simple to use and all the features are easy to find. I think the admin area needs a little work in terms of design, but the comments on Opensourcecms all seem to be very positive so I'll definatly be installing it locally and having a closer look.
Concrete5
Another interesting CMS, the video on the homepage makes it look like some sort of action movie, maybe a little over the top but whatever. I was unable to find a live demo of the CMS unfortunately, but the screencasts from the video looked very promising. There's also an option of Concrete5 hosting the CMS, which removes the (sometimes) tricky setup process; great for non-technical people.
CMS Made Simple
Of the new CMS' I've looked at CMS Made Simple is my favorite. The live demo looked good with a very intuitive administrator area. Some of the comments on Opensourcecms were quite negative; so I'll have to do some testing of the installation and template system before I commit to building a live site with it.
For my next small project I'll be using one of these small CMS', but which one will it be? When i decide I'll be sure to update you. Got any other suggestions? Why not leave a comment.
--- End: Looking for a new CMS for small websites
--- Start: New to Drupal? Here are a few helpful links
Published on: 13 July 2010
https://nooshu.com/blog/2010/07/13/new-to-drupal-here-are-a-few-helpful-links/
Main Content:
For the past week or so I've been expanding my horizons and started using a new CMS (to me at least), it's name is Drupal. Now Drupal has been around for many years, originally known as 'Drop' until it was renamed to 'Drupal' in 2001. The CMS is now on version 6 (with alpha versions of 7 available from the download page). As I've only just started using this extremely powerful CMS I thought I'd put together a quick list of links and tips of what I've learnt so far. Hopefully other beginners like myself will find them useful.
Screencasts
Lynda.com: I can't stress enough how useful Lynda.com has been while learning Drupal (or any other piece of software for that matter). It has 3 superb sets of screencasts available that will take you from a complete beginner a fairly competent Drupal developer. They aren't free but they are well worth the money!
Learn by the Drop: Another set of brilliant screencasts that you can use to get up to speed on how to use Drupal. The site contains both premium and free videos for the 'want to be' Drupal developer.
Websites
Stack Overflow: Now I know this is a bit of a catch-all site as it can be used for any programming language, but you will often find many questions you have, have already been answered on Stack Overflow. The Drupal specific questions are available here.
Drupal Snippets: Drupal Snippets is a whole site dedicated to.... erm... snippets for Druplal. I must admit I've yet to use the site, but I bookmarked it as soon as I found it as I'm sure it will come in extremely useful after learning the basics.
Modules
CCK: Download and install this module and developing dynamic websites in Drupal becomes so (so!) much easier. CCK (Content Construction Kit) is a module that expands Drupals native Custom Content Types functionality opening a whole world of possibilities for your site and users. In essence CCK makes it easier to 'push' data into your site in any way you see fit. It's even being included into the core of Drupal 7.
Views: Over the past couple of days I've been blown away by the power and versatility of the Views module. Where CCK is used to push data into your site database, Views 'pulls' the data back out and display it in any format you like. It's quite intimidating at first as there are tonnes of options and settings, but once you get your head around it, the Drupal world is your oyster. A free screencast on how to use it is available here.
Pathauto: Coming from WordPress I'm used to its fantastic permalink functionality, once setup it just works. Drupal doesn't seem to come bundled with anything similar (please correct me here if I'm wrong!) so installing the Pathauto module will plug that gap. The module automatically generates a path for various content types without you having to worry about it.
Themes
Zen: If you are a Front End Developer like myself you will be wanting a solid foundation with which to build and style your site. You could just edit one of the bundled themes if that's your thing, but I prefer to start a fresh. The Zen theme is a fantastic theme with which to base your styling off. One big tip, don't edit the main Zen folder, create a sub-theme by following these directions (I learnt that the hard way).
So there you go, hopefully fellow Drupal beginners will find the links above useful. Any that I've missed off or that you'd recommend? Leave a comment below.
--- End: New to Drupal? Here are a few helpful links
--- Start: WordPress plug-in: Snipplr Snippets
Published on: 24 June 2010
https://nooshu.com/blog/2010/06/24/wordpress-plug-in-snipplr-snippets/
Main Content:
Note: This plug-in is no longer maintained.
Recently I blogged about the fact that Snipplr was under new management!, and what great news that is. You can see the changes being made already, fingers crossed they manage to nail the spam issue.
Back when Snipplr was young, Tyler Hall wrote a WordPress plug-in for Snipplr that allowed you to embed your snippets directly into your posts. What a great idea; unfortunately it hasn't been updated since 2006 and much has changed in the world of WordPress. Enabling the plug-in in it's current state is a little flakey; so I've decided to update it for WordPress 3.0+.
The plug-in is called 'Snipplr Snippets' and is available to download from the WordPress plug-in repository. I've used many of the functions that were in the old plug-in so it isn't a complete rewrite but much of the structure has changed (big thank you to Marcin Dominas helped with a couple of issues i was having at first).
The administrator area has been updated and there are a couple of new features available which hopefully are self explanatory. I've also updated to the latest version of GeSHi for the syntax highlighting, if you don't like the look a feel of the outputted code simply disable the plug-in CSS in the site header (admin panel), copy to your style.css and modify as needed. For the plug-in to work you will need a Snipplr account and an API key (available from the settings page).
Once you've installed the plug-in and enabled it, it's dead simple to include a snippet into your blog post like so:
//Remove the spaces inside the brackets.
[ snippet id=## ]
I've tested the plug-in and it seems to work fine, there was a warning from the CodeColorer plug-in because it also uses GeSHi for syntax highlighting but I haven't noticed anything break because of it. If it does please let me know and I'll fix it. If you have any suggestions / bugs leave a comment and I'll see what look into implementing / fixing them. Download here.
--- End: WordPress plug-in: Snipplr Snippets
--- Start: Using the DeviceAtlas API with WordPress
Published on: 22 June 2010
https://nooshu.com/blog/2010/06/22/using-the-deviceatlas-api-with-wordpress/
Main Content:
Over the past couple of weeks I've had the absolute pleasure (no not really!) of adapting a WordPress site and making it accessible on as many mobile phones as possible. Now I must admit I've not had much experience building mobile sites so this is all new ground for me; and by mobile website I don't mean for the iPhone only (for more information on this plus lots of swear words see 'The iPhone Obsession' by PPK).
Luckily there are already many plug-ins available for WordPress that can get you started on your way, one that really grabbed my attention was 'WordPress Mobile Pack' by MobiForge. The plug-in contains a mobile optimised theme that you can adapt for your needs and the 'mobile switcher' functionality. Mobile switcher detects if a user is browsing from a desktop or a mobile phone and switched the theme accordingly. Great, we're already half way there!
One of the specifications for the site was that it must work on a set of 4 different screen widths (480px, 320px, 240px and 176px) and this is where the DeviceAtlas API comes in very useful. Device Atlas keep a huge database of mobile phone user agent strings plus specifications associated with a particular mobile phone that you can tap into and use in your web application.
Now one thing I must mention is that according to the mobiForge page listed above, WordPress Mobile Pack includes DeviceAtlas integration. This turns out not to be the case. I couldn't find any settings regarding DeviceAtlas in the plug-in admin area and very little mentioned on the forums. I assume the page hasn't been updated for a while and the functionality has been removed. This isn't a problem though as it's fairly simple to integrate the DeviceAtlas API into your PHP application i.e. WordPress. Here's how you do it.
First you must register with DeviceAtlas and order a developer licence (there's a free option available here). Once registered grab a copy of the PHP API and the latest Device JSON file (under 'My account'). Unpack the API into the root of your web application (or wherever you like, just make sure the includes are set correctly) and copy the JSON file into the json directory along side it. You are now ready to include the API into the base WordPress Mobile Pack theme. Copy and paste the following into your header.php above the doctype:
Great now we know the user agent that the user is using to view the website (well it may not be 100% accurate but better than nothing). So now you want to query the JSON file and pick out the relevant phone specifications you need. I'm just looking for the width of the device, so I included this in the head tag:
All this code does is find the display width of the phone viewing the website and add a CSS file with relevant site tweaks, allowing you to optimise for that screen size. If the device isn't found I've defaulted to a screen size in the middle of the screen sizes.
Looking through the API docs there are plenty of ways to distinguish between your users, using the following code will allow you to target specific phone brands:
So now you can target only Nokia users. Or instead of loading a different CSS file you could include a different sized image for different screen widths; there are tonnes of options available.
I must admit I really dislike having to 'sniff' for the user agent string and having a different CSS file / image per device width, it reminds me of the Netscape / IE browser war days, oh how much fun that was! I guess it's a necessary evil.
A word or warning when it comes to DeviceAtlas, there seems to be distinct lack of support available. I wrote a couple of emails asking questions and got no reply, and lots of questions on the forum are left unanswered. So if you get stuck you may need to figure it out for yourself I'm afraid.
All in all I'm pleased with the results of my first adventure into the world of mobile web development. I still have lots to learn so if you have any tips and tricks please let me know!
--- End: Using the DeviceAtlas API with WordPress
--- Start: Headspace2 JavaScript error
Published on: 17 June 2010
https://nooshu.com/blog/2010/06/17/headspace2-javascript-error/
Main Content:
Update: An update of Headspace2 has just been released that seems to solve this issue as well as a few others.
After updating to WordPress 3.0 (yay!) I decided to check the plug-ins that I've written to see if they still worked in version 3.0; to my dismay Post Thesaurus had stopped working... nooooo! Not good! A quick scan using Firebug revealed the issue: the Headspace2 plug-in.
Headspace2 is a superb plug-in that allows you to tweak the SEO potential of your site. There are tonnes of options available; All In One SEO is easier to use, but I prefer the flexibility of Headspace2. The problem was occurring in the headspace-tags.js file:
$(get_tag_element()).val() is undefined
/wp-content/plugins/headspace2/js/headspace-tags.js?ver=3.6.32
Line 76
This error was stopping the rest of the JavaScript on a post page from firing (hence breaking Post Thesaurus). Looking at line 76 of headspace-tags.js you will see:
// Highlights headspace tags using the WordPress tag field as source
function highlight_tags () {
var words = $(get_tag_element()).val().toLowerCase().split(',');
//...
}
The code seems to be falling over when there are no tags, so I just added a ternary operator which checks the array length first.
var words;
var wordArray = $(get_tag_element());
(wordArray.length) ? words = $(get_tag_element()).val().toLowerCase().split(',') : words = [];
If there are no tags create an empty array, else run the usual code. Adding this code fixed the issue and Post Thesaurus works again. Phew! Panic over. I'm sure this error will be picked up by the developer straight away and fixed in the next update.
--- End: Headspace2 JavaScript error
--- Start: Snipplr under new management!
Published on: 16 June 2010
https://nooshu.com/blog/2010/06/16/snipplr-under-new-management/
Main Content:
A few months ago I wrote a blog post regarding Snipplr, and how it was annoying it's user base. By the look of it other people noticed the severe lack of development and abundance of spam and the site has been sold to envato.com (which I must say I love the site design).
With Envato behind Snipplr hopefully it will go from strength to strength. They already have a huge number of popular sites behind them including Nettuts and FreelanceSwitch which I read regularly.
There's already been activity on the Snipplr twitter account asking for feedback, so here are a few of my requests:
Remove spam snippets & comments.
Better sign-up process to stop spam.
Fix the export function in the user preferences.
Better syntax highlighting (I hate having to click plain text before copy / paste).
Fix the blog links from the homepage, they have never worked for me.
Ability to remove comment spam from your own snippets.
Better design... the original orange was better than the current version.
Fix the gigs functionality, or at least explain how it works. I've never had much luck.
Use OpenID, I hate remembering all those passwords.
Ability for the API to output snippets as JSON-P.
Those are all I can think of at the moment but I'm sure there are others. Really looking forward to seeing how Snipplr evolves in the coming weeks and months!
--- End: Snipplr under new management!
--- Start: High Resolution Icons for Google Chrome
Published on: 15 June 2010
https://nooshu.com/blog/2010/06/15/high-resolution-icons-for-google-chrome/
Main Content:
I've been using Google Chrome as my default browser for quite a few months, I still use Firefox for Web Development but for general browsing you really can't beat the speed of Chrome. One of my favourite Chrome features is the 'Create application shortcuts...' function. Creating an application shortcut essentially adds an icon to your desktop, Chrome will then run the web application like it is a free-standing desktop application (you still need to be connected to the internet unless it uses some form of offline storage).
If you are a Gmail user I highly recommend creating an application shortcut to see this function in action. One thing you will notice when you create the shortcut with Gmail is it uses a high resolution icon. If you create a shortcut using a standard website, by default the favicon.ico is used. As the favicon is limited to 16 by 16 resolution it will look very ugly blown up on your desktop.
The image above really illustrates the difference between a 16 x 16 icon and a high resolution version. Now of course you could just change the icon in the Windows properties.... but that's boring. Why not offer your users a high resolution image along with the standard favicon? It really is very simple:
Simply place this code in your head tag of your web application and link to the corresponding icons. Now when your user creates an application shortcut they will have a nice high resolution icon on their desktop.
I've added a high resolution icon for my blog administration, now if only F1 live timings would do the same. For those of you who want to add a high resolution icon to your WordPress blog add the following code to your functions.php:
function wp_hi_res_admin_icons() {
echo ' '."\n";
echo ' '."\n";
}
add_action('login_head', 'wp_hi_res_admin_icons');
add_action('admin_head', 'wp_hi_res_admin_icons');
This will add the icon code to your administrator login panel and dashboard; or paste the raw HTML into your header.php so all users can see the icons.
--- End: High Resolution Icons for Google Chrome
--- Start: Converting a WordPress post to a custom post type
Published on: 03 June 2010
https://nooshu.com/blog/2010/06/03/converting-a-wordpress-post-to-a-custom-post-type/
Main Content:
Update: There is now a plug-in that does this for you called Post Type Switcher so you don't have to get your hands dirty with the SQL (thanks Bruno!). Another plug-in called Convert Post Types is also available that does the job for you, Thanks to Steve for that one.
With the release of WordPress 3.0, developers now have the ability to create custom post types by adding a few lines of code to a themes functions.php. The feature is a huge step forwards for WordPress as it moves closer to being a viable CMS solution (without all the hacks). There have been a number of projects I've worked on that have required a custom post type; rather than relying on the client selecting the correct category under 'Add new post', which tends to always leads to issues.
I'm in the process of converting nooshu.com to use custom post types and taxonomies, the main area in particular is my portfolio section. At the moment the portfolio posts are just standard posts which have a category of 'portfolio' attached to them. It works, but I don't get that warm fuzzy feeling, and it feels like a bit of a hack. So time to start using a custom post type of 'portfolio' (yay!).
Unfortunately at the moment there doesn't seem to be a quick way of converting a published standard post into a shiny new custom post type, at least not from the administration area. After a little investigation work using phpmyadmin and the nooshu WordPress database, I discovered it's actually quite easy. Be warned though, it's easy to break your blog by editing the database directly, so make sure you back everything up. I take no responsibility for what happens if you break something!
To convert a post into a custom post type; in phpmyadmin look for the wp_posts table. Inside it do a search, where the post_type value equals 'post'. This will give you a list of all your posts (otherwise you will also have all the revisions and attachments listed). From the list you should be able to pick out the posts you want converting to your new post type, edit one of these posts and change 'post_type' from 'post' to your new custom post. In my case this would be 'portfolio':
Click save and go back to the previous page. Done! You should now see the post appear under your new custom post type in the WordPress admin panel. If you have any issues just change 'post_type' back to 'post' and it will reappear under the standard posts. No information is lost when changing the post type.
It's not an ideal solution, hopefully it will be possible to do it from the administration panel in the future; but it does save having to re-enter all the posts under the custom post type for the moment.
--- End: Converting a WordPress post to a custom post type
--- Start: WordPress 3.0 RC1 blank page error
Published on: 02 June 2010
https://nooshu.com/blog/2010/06/02/wordpress-3-0-rc1-blank-page-error/
Main Content:
Update: Apologies to the author of Hyper Cache, the error isn't cause by the plug-in. The error is being caused by DB Cache Reloaded. After updating the site to 3.0 final I was getting the error on the update page, disabling DB Cache Reloaded fixed it.
Update 2: DB Cache Reloaded has now been updated and works flawlessly in 3.0, get it here.
I've been eagerly awaiting the release of WordPress 3.0 (due any day now!). I plan on making a few changes to my blog once it is released so decided to try out Release Candidate 1 on my development server. At first it all went fine, upgraded the database no problem... then a blank page. Weird! After a couple of page reloads the sparkly new dashboard popped up (it's not that different, although it does look greyer). Clicking around the admin area I could see this blank page error was randomly occurring on different pages; bugger!
My immediate thought was a plug-in I had installed, as I'm sure this rather large error would have been picked up while testing the WordPress core functionality! Looking at my Apache error log the following error was listed:
[error] [client 127.0.0.1] PHP Fatal error: Call to undefined method wpdb::get_blog_prefix() in dev.nooshu.com\\trunk\\httpdocs\\wp-admin\\includes\\user.php on line 260, referer: http://dev.nooshu.com/wp-admin/edit.php?post_type=portfolio
The error is too vague to actually help, but after a little investigating (and from a hunch I had) I disabled any plug-ins involved in page caching; namely DB Cache Reloaded and Hyper Cache. Unfortunately disabling them still didn't fix the error, so I decided to remove them completely (db-config.ini, advanced-cache.php and db.php removed from the wp-content directory). Suddenly no more blank page errors occurring! Huzzah!
So if you come across the same problem, then check what caching plug-ins you have installed. When 3.0 final is released I'll be doing a fresh install of both plug-ins. Hopefully that will solve the issue. They are both quite popular plug-ins so I'm sure others have had the same issue.
--- End: WordPress 3.0 RC1 blank page error
--- Start: Visualising Subversion with Gource
Published on: 24 May 2010
https://nooshu.com/blog/2010/05/24/visualising-subversion-with-gource/
Main Content:
Over the weekend I stumbled across a video link, released (I assume) by Flickr. The video is a visualisation of the last 7 years of commits into the Flickr Subversion repository. Wow, there's a lot of work been done to Flickr over the past 7 years! What's even more interesting is you can easily create the same type of visualisation with your own project using an open-source project called Gource.
Gource is a version control visualisation tool developed by Andrew Caudwell. At the moment it supports Git, Mercurial and Bazaar but it is also possible to use it with Subversion (SVN) with a few extra steps. I've created a video for a project I've been working on with another developer for 9+ months. The video isn't as active as the Flickr one but its still interesting to watch and see how a project develops right before your eyes.
Gource Visualisation from Matt Hobbs on Vimeo.
The videos produced by Gource really illustrate how much work goes into projects over time, with each developer 'shooting a laser' at each file created / changed / deleted. Files in the same folder are clustered together, lines in-between these clusters link them together depending on the folder structure.
Creating the videos is fairly simple, I'll give you a step by step guide how to do it using an SVN repository below. You will need:
Gource
Command line SVN client
Python
Fraps (optional)
VirtualDub (optional)
SVN repository
First you will want to grab a copy of Gource and extract the zip file to somewhere easily accessible. I've used c:\gource as you will be using the command line so it's simple to find. Extract Python into a similar directory, I used c:\python31. If you don't have the SVN command line client installed, install it and note down where it's installed too.
Next you need to export the SVN repository log file to an XML document. To do this open a command prompt and locate the SVN client directory. Now type:
svn log http://www.yourrepository.url/svn/ --verbose --xml > projectlog.log
This command has exported the SVN log file to an XML doc that you should see in your SVN client directory. Since Gource doesn't support SVN natively, the log file needs to be converted into a format Gource will understand. To do this copy the XML log file and this python script into the python directory. To convert the log file type the following from the command line in the python directory:
python svn-gource.py --filter-dirs projectlog.log > my-project-gource.log
Great! Now time for the fun part! You now have a log file (my-project-gource.log) that Gource can understand, so copy it to the Gource directory and bring up the command line. To generate the video created above I used the following command line:
gource --log-format custom my-project-gource.log -s 0.1 --hide filenames --stop-at-end --disable-progress -1280x720 -f --disable-progress --hide date
The command line is pretty self explanatory, I've set the size of the video I want, and hidden a few elements that weren't needed. The -s 0.1 is an important command as it sets how quickly the visualisation runs through the log file. It's worth experimenting with different values until you are happy with the results.
If you look in the README.TXT file thats in the Gource directory it gives you a whole list of options that are available to experiment with, there's hours of fun in there if you really want delve into Gource.
Saving the video
This part actually took me longer to complete than generating the video in Gource; due to a few video encoding issues I was having (Grr!). Capturing the video is simple (once you know how) and uses a program called Fraps. Fraps is usually used in the online gaming scene, it is used to capture full-screen video and save it into an (uncompressed) video format. Once installed it will sit in your taskbar waiting for a full-screen video to kick in which it can then capture.
Play your Gource video from the command line in full-screen and press F9, this is the hotkey that triggers Fraps to start recording. Once complete, your video will be saved into the \fraps\movies directory. The video that has been saved is in an uncompressed format so it's likely it will be a large file (mine was around 700MB for 2 mins at 1280 x 720). This size isn't very practical so it's time to convert it to a smaller more portable format. For this we use the excellent VirtualDub by Avery Lee.
Once VirtualDub is installed it only takes a couple of steps to compress the video down:
Run VirtualDub and open your Fraps video file
From the Video menu select 'Compression'
Choose the codec / compression settings you wish to use (I used the XviD codec single pass)
From the file menu select 'Save as AVI', once compressed you are done!
As simple as that! The file produced will be much smaller which you can then upload to Youtube / Vimeo as you see fit. Gource may not have a huge number or practical uses other than eye candy, but it's a superb little tool that I will be using again in the future.
--- End: Visualising Subversion with Gource
--- Start: NextGEN Gallery + WordPress custom fields = happy developer
Published on: 20 May 2010
https://nooshu.com/blog/2010/05/20/nextgen-gallery-wordpress-custom-fields-happy-developer/
Main Content:
Over the past couple of weeks I've been working on a number of WordPress projects, all of which have needed some basic photo gallery functionality. As I've mentioned before in previous posts, NextGEN gallery is my WordPress gallery of choice, there really is nothing that comes close to it in terms of features and customisation (that I know of, if there are others post a comment!).
To add a gallery (or album) to a post / page is as simple as adding [ nggallery id=x ] to the post content... super! One issue though... what happens when you allow a client to edit and add new pages; well what usually happens is the tag gets deleted or changed, the gallery breaks, client panics and the virtual world ends (well not quite, but close). A technique I have been using to help solve this issue involves using WordPress custom fields and the excellent Get custom field values plug-in. You can grab the custom field values directly from WordPress using get_post_meta() but the plug-in makes it much easier.
Digging through the nggfunctions.php file in the NextGEN gallery plug-in folder reveals a whole host of useful functions that can be easily called directly from inside your WordPress theme. So say you wanted a gallery in a post page, but didn't want the client to have to remember [ nggallery id=x ] every time, simply add this code next to your content in the single.php file:
Add a custom field of galleryID with an integer value linking to the relevant gallery and you're done. Now the client can pick out the galleryID custom field from a drop-down since WordPress remembers the custom fields used. Much easier for a client to remember than adding the tag every time.
I highly recommend looking through the nggfunctions.php file, here are just a few functions that are available:
nggShowAlbum(): Show a whole album depending on the ID.
nggSinglePicture(): Show a single picture from an ID.
nggShowRandomRecent(): Show random image(s) from a certain gallery.
nggShowSlideshow(): Show a flash slideshow pulling images from a specified gallery.
I have used nggShowRandomRecent() quite a few times in the past few months, here's a quick example:
Pick 6 images at random from a selected gallery on page load, very simple and effective.
Note: When using the random images function make sure you don't have any WordPress caching plug-ins running on the selected page, else it won't work as the page gets cached on first load. It took me a good 15 minutes to figure out why the function had suddenly stopped working due to this slight oversight.
--- End: NextGEN Gallery + WordPress custom fields = happy developer
--- Start: Wolf CMS: A fork of Frog CMS
Published on: 09 May 2010
https://nooshu.com/blog/2010/05/09/wolf-cms-a-fork-of-frog-cms/
Main Content:
I've written about my Frog CMS usage in previous blog posts; where other CMS's can be a little overkill for small websites, Frog CMS fits perfectly into the gap. Unfortunately as much as I like Frog, the development seems to have stopped. The last stable version was released on the 26th April 2009, over a year ago. There's no need to panic though, a development fork has been created called Wolf CMS which is building upon this superb little CMS and making it even better!
At the moment there's very little difference between Frog and Wolf as you might expect, so migrating from one to the other is fairly simple, a wiki page has been created with instructions on how to do this. As it says on the page it's probably best to decide between the two versions now since there's still little difference between them, but this could change in future versions (version 0.6.0 introduced a number of large changes). So there may be a point where it isn't (easily) possible to jump between the two versions.
So what are the differences at the moment? When version 0.6.0 of Wolf CMS was released on the 1st February it added a new core plug-in called 'BackupRestore', allowing admin users to easily backup the Wolf CMS core DB tables. I've been using an external plug-in to do this on sites I built, so having this feature added as a core plug-in is nifty addition. Other features include:
Admin users can now uninstall plug-ins, including the db tables
HTTPS Support added to the admin area for greater security
You can now preview a page before it is published
It's great to see that such a useful little CMS hasn't been left to stagnate and die out, the roadmap for Wolf CMS looks promising, so fingers crossed it has a bright future ahead of it. I think it's time to migrate my Frog websites over to Wolf...;
--- End: Wolf CMS: A fork of Frog CMS
--- Start: Aptana on Steroids using Zen Coding
Published on: 04 May 2010
https://nooshu.com/blog/2010/05/04/aptana-on-steroids-using-zen-coding/
Main Content:
I've mentioned before in previous articles that Aptana is my IDE of choice; one which I've been using for a few years. I only use a handful of the many features available in Aptana, all of which are also available in other editors (Notepad++ being one), but I've got so used to the way it works I'm sticking with it for the moment.
One of Aptana's helpful features is the ability to generate code using the easy to access menu bar at the top of the code window (see image):
A superb feature it must be said, but it is totally eclipsed when you start using the Zen Coding JavaScript Library. Zen Coding, written by Sergey Chikuyonok isn't a JavaScript Library in the traditional sense, it isn't uploaded and linked to in your web page; it's installed as a plug-in for your selected text editor. As you can see from the list there are many versions available, so you aren't restricted to only Aptana.
Let me explain what it does first, then I'll show you how to install it (for Aptana). As a Front End Web Developer you will often find you're writing out the same blocks of code again and again. You can just copy / paste then modify, but even that's quite slow and tedious. Zen Coding uses a technology that you will be very familiar with: CSS selectors. It may seem confusing at first, but once you see it in action it makes perfect sense. Here are a few code examples I use all the time:
Using simple CSS selectors we've been able to quickly generate an unordered list that can be used for example, as a page navigation. You can even use more advanced selectors like siblings and abbreviated groups to generate more advanced HTML:
It may take a little while to get into the routine, it's all to easy to slip back into typing the code by hand; but once you do you can build the basic mark-up of a page in a matter of minutes.
There's a very informative article on Smashing Magazine from last year which you may find useful if you plan on investigating Zen Coding further; I highly recommend adding it to your "toread" list. There are so many more functions available that I haven't even touched on in this article, you will be amazed.
Now that you've seen Zen Coding in action you may be wondering how you install it for use with Aptana. Well luckily it's dead simple. First create a 'new project' in Aptana, call it whatever you like e.g. 'Zen Coding':
Within the new project create a scripts directory and copy the Zen Coding JavaScript into into the directory. That's it you're done! Restart Aptana and start using Zen Coding. Once you've typed in a string of CSS selectors you wish to convert to HTML, hit CTRL + E (Expand Abbreviation) and it will do the rest for you. One thing to note, you must keep the new project you've just created open at all times, else Aptana won't be able to access the scripts.
You can customise the key you use expand an abbreviation by editing the 'Key' value in 'Expand Abbreviation.js'. For more information on available keycodes see the Aptana documentation here.
Hopefully you find Zen Coding useful, it's certainly changed the way I code on a day to day basis.
--- End: Aptana on Steroids using Zen Coding
--- Start: Recommended books for Front End Web Developers
Published on: 27 April 2010
https://nooshu.com/blog/2010/04/27/recommended-books-for-front-end-web-developers/
Main Content:
So you've decided to persue a career as a Front End Web Developer (or you already are one and are looking for something new to read); smashing! The life of a Front End Developer is never dull... (cough) okay sometimes it is but there are certainly some exciting technologies out there to play with, especially at the moment with HTML5 and CSS3 gaining popularity.
Like with anything, you need to have a solid foundation of knowledge to build upon when it comes to new technologies, sometimes it's a little dull but it will pay dividends in the future. Once you have the basic knowledge the world is you web browser. So here are a list of five books I've read in the past that I've found particularity helpful.
DOM Scripting
The reason I've put this book first is simply because it's one of the best technical books I've ever read. The way it's written is simple to understand and concise. All the way through the book it explains not only what you are doing but also why you're doing it, and why you should also follow the same methodology.
If you are a complete beginner to JavaScript and the DOM this book will get you up and running and understanding in just a couple of chapters. Now some may say "oh I don't need to know this anymore, that's what JavaScript librarys are for", but in my opinion that's a dangerous road to go down. If ever your chosen library doesn't do what you need, or if you can't use a library for whatever reason; then you're in trouble.
If you know the basics of the DOM and how to manipulate it using JavaScript, you're much more likely to solve any issues you encounter and you'll have a much better understanding of what the libraries are actually doing.
Author: Jeremy Keith (Amazon).
Eric Meyer on CSS
There simply couldn't be a review of front end development books without a book from the wizard of CSS, Eric Meyer. Eric has been a major part of the CSS community for many years; helping to educate developers in the proper usage of CSS and how it can make development so (so!) much easier. I had the pleasure of attending a 2 day workshop of his in London a few years back, and still use what I learnt there on a day to day basis.
'Eric Meyer on CSS' will teach you some of the advanced techniques involved in using CSS in a practical manner. You take a plain website built using tables, clean up the mark-up and layer on features and functionality using CSS over the various chapters; so rather than just getting a list of properties and selectors to read about, you actually get to see a live project changing over time.
Be warned, the book isn't for absolute beginners, you do really need to know the basics of HTML and CSS to get the most out of it. Not to worry though, all the information you need to learn the basics of many different languages including HTML and CSS is available online at w3schools. You don't have to stick to HTML and CSS, they also have JavaScript and the DOM if you're feeling adventurous.
Author: Eric Meyer (Amazon)
JavaScript - The Definitive Guide
The very large book you can see in the image above is 'JavaScript - The Definitive Guide', and it really is a definitive guide. It has of 900+ pages of wonderful JavaScript! Now I wouldn't expect anyone to read it page by page (although that's what I did), but it's defiantly a book you should have in your tool kit for reference. It goes over pretty much all aspects of JavaScript you will ever use and even though it is quite technical it isn't hard to follow; with plenty of examples and explanation of the code.
Again there's an argument for do you need to know JavaScript if you just intend on using a library. Well I guess that up to you, but I personally don't feel comfortable using any sort of framework / abstraction without having at least some understanding of the language it is built on.
Author: David Flanagon (Amazon)
Learning jQuery
So assuming you know about HTML, CSS and JavaScript it's time to learn one of the many JavaScript libraries available. Now I agree with Christian Heilmann on a point he made at Full Frontal 2009 (I think it was Christian who made it), it doesn't matter what library you use, as long as you use one!
'Learning jQuery' is a fantastic book that will take you through all aspects of jQuery, from setting up and writing basic code to Ajax and writing your own jQuery plug-ins. If you know how to use CSS to select parts of the DOM then jQuery will be simple for you to pick up and use. The book is filled with practical examples and applications, all using best practice methods.
I only had one slight gripe with the book while reading it; I found the font for the code blocks was slightly too big, so you tended to get a lot of wrapping on large code blocks. In terms of the content though, it really is one book that is a must read if you use jQuery or want to use jQuery in your projects.
Author: Jonathan Chaffer & Karl Swedberg (Amazon)
PHP Solutions
Now I know what you may be thinking, PHP isn't a front end language, it's a server side language. That is very true, but one thing I can guarantee is one day you will have to integrate the front end templates you've built into a server side language; be that PHP, .Net, JSP, Java etc. As I've mainly worked with open source technologies, PHP is primarily what I integrate into.
'PHP Solutions' is another excellent Friends of Ed book that takes you through lots of practical uses of PHP that you can use straight out of the book. It covers subjects such as setting up your server and includes, to online galleries and security. You may not use any of the functionality it covers since most frameworks and CMS's have the functionality built in; but it will give you an understanding of how PHP works as a language which in turn will help you when it comes to integration.
Author: David Powers (Amazon)
So there you have 5 books I'd recommend to any Front End Web Developer looking to expand their client-side knowledge. Leave a comment if there are any books you'd recommend and I'll take a look and add it to my Amazon wishlist.
--- End: Recommended books for Front End Web Developers
--- Start: Adding Content using CSS3
Published on: 20 April 2010
https://nooshu.com/blog/2010/04/20/adding-content-using-css3/
Main Content:
CSS3 is an exciting new browser technology, it's implementation is improving with every new browser release. Microsoft is adding a whole host of CSS3 selectors to the their next version of Internet Explorer, version 9. Until IE9 is released and the vast majority of users start using it, (2016 maybe?) it's a case of having to use CSS3 quite cautiously.
Using the 'progressive enhancement' methodology, we build a website that works in all browsers first, then 'layer on' the cool features and 'nice to haves' after, so users with modern browsers get the full site experience and older browsers still have access to all the content. CSS3 sits in the 'nice to have' category for the moment.
While looking through the W3C CSS3 Working Draft I came across a section called 'Inserting content into an element'. The CSS3 pseudo-elements listed here are used to add content to the page using CSS. Cool! ....wait a second; for years we've been separating layout from content, allowing us to easily edit a whole website layout from a single file. The pseudo-elements seem to be going against this mantra! Uh ohh! It's controversial, but I believe if used responsibly the pseudo-elements shouldn't cause any major accessibility issues.
::before & ::after
The ::before and ::after pseudo-elements are used to add content before and after the content inside the selected element (surprising huh!):
#element::before {
content: "Paradox: ";
}
#element::after {
content: " Now my head hurts."
}
View a demo here.
The specifications even allow you to add more content by iterating the pseudo-elements, so ::after::after (or ::after(2)) but this isn't supported in current browsers I have tested. I'm personally hoping that part of the specification isn't implemented, as you can have too much of a good thing. You could end up in the nightmare situation of pages completely generated using CSS3 using multiple levels of ::before and ::after.
The CSS3 specification has also outlined the pseudo-element ::outside but it hasn't been implemented yet in the current version of Firefox I'm using (3.6.3).
Outline will allow you to wrap an element inside another element and then add styling to it. Usually you'd modify the source code by adding extra divs to do this, but it isn't always possible. Outline would have been very useful over the past couple of years for adding 'sliding doors' and rounded corners where needed, without having to clutter up the mark-up with 'for style' only tags. Oh well it's a tool for the future.
I can't say I'm a big fan of these new pseudo-elements as they seem to be stepping on HTML's toes. It's hard to think of a situation where you'd want the CSS to be writing content to the pages since it isn't accessible to screen readers or search engines, but I'm sure there are some. The only example that springs to mind is when you add a ':' after the label on a form field, you don't want a screen reader to read out the 'colon' so you add it using CSS.
I'd love to hear where other people plan on using ::before and ::after, or where you are using them at the moment.
--- End: Adding Content using CSS3
--- Start: CodeColorer Auto Expanding Code
Published on: 16 April 2010
https://nooshu.com/blog/2010/04/16/codecolorer-auto-expanding-code/
Main Content:
Just quick post on a small feature I've just added to the site which I thought I'd share. It's a slight addition to the CodeColourer plug-in for WordPress. CodeColourer formats and colourises code blocks in your blog posts for better readability. It comes with several different styles built in, or you can customise it using your own CSS file.
A feature that I saw on another site (although I can't remember which) was when a user rolled over a code box it would expand to fit the code, allowing the user to see everything. Cool little addition, so I decided to create my own using jQuery. I've taken some of the code from the plug-in and pasted it below so you can see it in action:
if($(".codecolorer-container").length){
var $code = $(".codecolorer-container").each(function(){
var $this = $(this);
//Animation decision object
var decisionObject = {
w: false,
h: false
};
//Original width / height of the displayed code
var originalWidth = $this.width();
var originalHeight = $this.height();
//Width / height of hidden portion of code
var mainWidth = $this.find(".codecolorer").width();
var mainHeight = $this.find(".codecolorer").height();
var lineWidth = $this.find(".line-numbers").width();
//Only attach events if needed (ie has scroll bars)
if((mainWidth + lineWidth) > originalWidth || mainHeight > originalHeight){
/* and so on...... */
}
}
}
Since this action is fired on hover, I didn't want the code boxes expanding immediately every time a user hovers over a box; as just scrolling down the page would expand the boxes which would become extremely annoying. The boxes should only expand when the cursor is left over the box; lucky there's a plug-in for jQuery that already adds this functionality, it's called $.event.special.hover.
Special hover simply replaces the standard hover event with one that monitors the speed of the cursor over a set period of time. If the cursor speed drops below the threshold the hover event fires. This is enough to stop random hover events firing when a user navigates over the page, simple!
I'd be interested to see if the code works for others using CodeColorer, there's no reason why it shouldn't.
--- End: CodeColorer Auto Expanding Code
--- Start: WordPress plug-in: Post Thesaurus
Published on: 14 April 2010
https://nooshu.com/blog/2010/04/14/wordpress-plug-in-post-thesaurus/
Main Content:
Note: This plug-in is no longer maintained.
Over the past few days I've been working on a new WordPress plug-in, one that I personally have desperately needed recently. It's called 'Post Thesaurus' and it does exactly what you'd expect it to do. It creates a little widget on the side of the 'Add new post' page which you can use to suggest new words of the same meaning.
After finding I use the word 'great' a little too much, I thought it was about time to do something about it. Here are a few screenshots of the plug-in in action:
Big thank you to Big Huge Labs for providing the excellent API. I've included an admin page with a few settings (under 'settings'). One feature to note is the ability to enter your own API key. I've added this just in case the plug-in starts exceeding the 10,000 requests per day a single API key is allowed. Sign up is simple and only takes a couple of minutes, then you'll have 10,000 requests per day all to yourself.
I've implemented the API using a little jQuery Ajax goodness and some JSONP. Since jQuery is used by the WordPress admin by default, there's no additional overhead in having to add it manually.
Grab the plug-in off the WordPress site here (Version 1.0.0.0).
I hope you find it useful.
--- End: WordPress plug-in: Post Thesaurus
--- Start: Shadowbox and NextGEN Gallery Sitting in a Tree
Published on: 07 April 2010
https://nooshu.com/blog/2010/04/07/shadowbox-and-nextgen-gallery-sitting-in-a-tree/
Main Content:
A project I'm currently working on requires a photo gallery, luckily with WordPress there are quite a few to choose from. Of the gallery plug-ins I've used NextGEN Gallery is without doubt my favorite, chocked full of useful features and easy to use; you could even let a client use it! My only issue is the way the images appear in a 'lightbox' when you click on them, the 'lightbox' is great, but it's implementation seems a little clunky.
By default NextGEN adds a chunk of code to the WordPress header which is one of my pet hates, that has to go. NextGEN uses ThickBox, which is great, but as it says on the website "Thickbox had its day" so it's time to use an alternative. One that's really caught my eye is Shadowbox.js.
Shadowbox.js is a fully featured media viewer that supports the webs most popular formats (images, Flash, QuickTime, Windows Media Video and FLV via JW FLV Player). Pretty much every format you really need. It also has the added bonus of being available either as a standalone script or integrated with your favourite JavaScript library (jQuery, Prototype, MooTools, Dojo, YUI and Ext). For me personally, it ticks every box... and it also looks great and works well!
So now time to bring the two together. First you should install the NextGEN gallery plug-in which you may already have it installed. Next you need view the gallery 'options' and select the 'Effects' tab. Change the "JavaScript Thumbnail effect:" to Custom and add the following code to the text box:
rel="shadowbox[%GALLERY_NAME%]"
The code will be added to each thumbnail generated by the gallery. Changing the dropdown to custom also removes various bits of default NextGEN code from the header, solving that problem too.
Next it's time to download Shadowbox.js. You have a few options on this page, as I only want to display images I selected 'Base (standalone)', checked the images checkbox and unchecked "Include support for using CSS selectors to select links". I don't plan on using shadowbox with jQuery so I didn't add the jQuery adapter, this also keeps the filesize to a minimum.
Hit the download button to download the ZIP. Once downloaded extract the CSS, JS and images into your WordPress theme directory. All thats left to do now is add a little code to your theme.
In your header.php add:
Or what I prefer to do is copy the CSS from shadowbox.css into my main style.css file, this way you keep everything in one place and you minimise HTTP requests. Then add the JavaScript to your footer.php (or header.php, but I prefer to put all JS in the footer.php).
Note the use of the 'is_single()' WordPress conditional tag. Since I'm only planning to use Shadowbox on an individual blog post I only call it on those pages. Feel free to remove this if you plan on using it elsewhere on your site.
Once those bits are added you're all done! If you don't see the any open, close, next, previous images make sure you are pointing to them correctly in your CSS file (since they are background images). Hurrah! Enjoy your new improved version of NextGEN Gallery complete with Shadowbox.js.
--- End: Shadowbox and NextGEN Gallery Sitting in a Tree
--- Start: jQuery Plug-in: Tab Down
Published on: 02 April 2010
https://nooshu.com/blog/2010/04/02/jquery-plug-in-tab-down/
Main Content:
This simple plug-in has been on my TODO list for quite a while, as I've seen the effect used on many websites. It seems particularly useful for displaying contact details / social media updates. I'm sure there are many similar plug-ins around, but where's the fun in using someone else's version. So I created a jQuery Tab Down.
Tab Down simply hides content above the page which a user can then access via a floating tab. It's easier to illustrate using a couple of demos. Demo 1 pushes the page content down with the tab, where as demo 2 tab content floats over the top of the page content. You can easily switch between versions by passing true or false to the 'floating' option when calling the tabDown method.
The plug-in is simple to use and has a number of options to allow customisation:
$("#tabContent").tabDown({
floating: true,
time: 900,
easing: "easeOutCubic"
container: "body",
downText: "Down",
upText: "Up"
});
Floating: Sets if the tab floats over the main content or pushes it down (default: true)
Time: Time in milliseconds for the slide animation (default: 1000)
Container: If your tab content is inside a 'wrapper' div, let the plug-in know the selector for this div, see demo 1 for an example (default: 'body')
Downtext: The text used in the tab before sliding down (default: 'Down')
Uptext: The text used in the tab after sliding down (default: 'Up')
Easing: For smoother animation you can use animation easing, requires the jQuery easing plug-in (default: 'swing')
View demo 1 and demo 2 (version 0.1 – updated 2nd Apr 2010).
--- End: jQuery Plug-in: Tab Down
--- Start: NASA Picture of the Day CSS Design Challenge
Published on: 31 March 2010
https://nooshu.com/blog/2010/03/31/nasa-picture-of-the-day-css-design-challenge/
Main Content:
A website I check on a regular basis is the NASA's Astronomy Picture of the Day, a superb site if you're interested in the Cosmos; it publishes a new picture each day with an explanation written by a professional astronomer. Amazing stuff... apart from the design is... just horrible! If you want an example of what the web looked like back in the mid nineties, then take a look.
Now I doubt restyling the website is high up on NASA's priority list, but there's no reason a user can't do it for them (only on their own machine of-course). All you need is Firefox and a custom CSS file.
The CSS file you will need is called userContent.css, and it resides in your Firefox profile under the 'chrome' directory. To find your profile directory look under 'Help' > 'Troubleshooting information...', there you will see a button to open the profile directory (Note: I wouldn't change much in here, it can break your profile!). If you still can't find it you can always look here. You may not have a userContent.css by default, so feel free to create a blank one.
This is when the fun starts, first you want to add this code snippet:
@-moz-document domain(antwrp.gsfc.nasa.gov) {
/* Page specific CSS here */
}
This is a Mozilla specific property that will allow you to include CSS for pages on a specific domain; note the 'antwrp.gsfc.nasa.gov'. Feel free to add as little or as much CSS as you want until you are happy with the page layout. Here's a sample from the userContent.css file I created:
@-moz-document domain(antwrp.gsfc.nasa.gov) {
/* authors and editors */
body > hr ~ center:nth-child(5) {font-size: 0.69em;}
/* all b's */
body > hr ~ center:nth-child(5) b {
margin: 8px 0 0;
font-size: 1em;
line-height: 1.4;
}
/* first b */
body > hr ~ center:nth-child(5) b:nth-child(1) {margin: 32px 0 0;}
/* all a's */
body > hr ~ center:nth-child(5) a {font-size: 1em;}
}
To make the page look in any way presentable I've had to rely heavily on the new CSS3 selectors available in most modern browsers; as the state of the mark-up on the pages is truly awful. I guess it all adds to the challenge though, it's certainly a great way to learn CSS3.
Here are a couple of before and after images I created, nothing spectacular but hopefully it looks slightly better:
The 'index' page was a page to far for me, I have no idea what the developer was trying to do with the mark-up, it's overuse of tables for layout really doesn't help either. On the end I got bored but feel free to dive in and take a look.
It's also worth mentioning that it is possible to customise the style of any website using a Firefox plug-in called Stylish, you can view many examples of it's usage on userstyles.org.
NOTE: Download no longer available.
--- End: NASA Picture of the Day CSS Design Challenge
--- Start: p01.org: Amazing Experiments using JavaScript
Published on: 30 March 2010
https://nooshu.com/blog/2010/03/30/p01-org-amazing-experiments-using-javascript/
Main Content:
Some websites you come across make you sit back in and say 'wow'. Stumbling across p01.org that's exactly what I said. P01.org is a website showcasing experiments in JavaScript & Canvas by French Web Developer Mathieu Henri, who currently works for Opera. As HTML5 is becoming increasingly popular, more and more of these cool little experiments are popping up; great news for people like myself who are interested in this up and coming technology.
Mathieu's experiments range over a wide range of areas, from photo manipulation and raytracing to fractal generation and Wolfenstein... amazing stuff! My personal favorites are the 512b JSpongy and 3D Dots Performance Test.
One thing that isn't available on the website is an RSS feed for the latest releases, which is a pity as I want to add them to my Google Reader. Luckily with Web Applications like dapper.net it's easy to create an RSS feed (plus many others) from any website using screen scraping. For anyone else who wants to add p01 to their feed reader, here's the RSS feed I created.
--- End: p01.org: Amazing Experiments using JavaScript
--- Start: Internet Explorer 9: Is that light at the end of the tunnel?
Published on: 25 March 2010
https://nooshu.com/blog/2010/03/25/internet-explorer-9-is-that-light-at-the-end-of-the-tunnel/
Main Content:
Last week Microsoft decided to unveil a technical preview of Internet Explorer 9 at Mix 2010, a conference that demonstrates up and coming Microsoft technology. Since it's only a preview it's no where near a complete browser yet, but it gives developers a chance to see what the future holds for the (Microsoft) web.
It comes packed with a whole host of new features.... border-radius at last! With new CSS3 selectors being included too, the life of the Web Developer is becoming slightly easier (and a lot more interesting!). The JavaScript engine has been improved dramatically, and it actually scores quite well on the Acid3 test (55 / 100 for IE9 compared to 20 / 100 for IE8).
Also included are a whole host of HTML5 features including native video support (video tag), audio embedding (audio tag) and some SVG sprinkled in there for good measure. The video codec being used is h.264, YouTube and Vimeo already support this codec which is great news for users. It's worth noting that Mozilla doesn't plan on using h.264 due to licence issues since the codec isn't free. So there could be trouble in store for developers when using the video tag in the future.
Hopefully IE9 will finally kill off IE6 (although I really can't see that happening) as it will only be available on systems running Vista+ operating systems. The reason for this is because IE9 supports DirectX video acceleration using Direct2D, which (apparently) isn't possible on XP; forcing users to upgrade to Windows 7. It's an interesting strategy, lets hope it works.
I'm not usually one to praise Microsoft when it comes to Internet Explorer, but IE9 looks very promising.
--- End: Internet Explorer 9: Is that light at the end of the tunnel?
--- Start: Coolclock: HTML5 Clock that is Actually Quite Cool*
Published on: 25 March 2010
https://nooshu.com/blog/2010/03/25/coolclock-html5-clock-that-is-actually-quite-cool/
Main Content:
*Unless you're Internet Explorer, then not so much.
Every so often a designer asks for something a little different, this time it was for an animated clock that sits in the top right corner of a website. Usually that means looking for a Flash based solution, but Canvas is the new Flash… apparently; luckily Coolclock is available to plug the no-flash gap.
Coolclock is a fantastic little script that will generate a canvas based clock from the parameters you pass it via the class attribute (I don't agree with that, but it works). It's fully customisable by way of a little JSON data, allowing you to create your own skins. There are quite a few user submitted skins available to use on the Coolclock homepage if you don't want to create your own.
I needed the clock to be able to change depending on the country that's chosen from a dropdown list, here's how I achieved it:
//Generate the clock
var generateClock = function(){
//Create our dropdown, time difference compared to GMT as a value
var dropHTML = "";
dropHTML += "United Kingdom ";
dropHTML += "France ";
dropHTML += "New York ";
dropHTML += " ";
//Append to the container
$("#time").append(dropHTML);
//Initial clock appended to the page (local time)
var clockHTML = ' ';
$("#clock").append(clockHTML);
//When the dropdown changes
$("#localTime").bind("change", function(){
var value = $(this).val();
var localClockHTML = ' ';
//Empty the old clock, append the new clock
$("#clock").empty().append(localClockHTML);
//Fire the coolclock function to generate the new clock
CoolClock.findAndCreateClocks();
});
}();
Very simple, the relevant HTML code is generated with JavaScript as to not leave a pointless dropdown on the page when it's turned off. The key to the solution was calling the CoolClock.findAndCreateClocks() function from the coolclock.js file, without that the clock isn't recreated when the dropdown is changed.
As mentioned above, the script seems to come unstuck when viewed in Internet Explorer, since IE doesn't support the canvas tag. You can plug the lack of canvas support using ExplorerCanvas, but even then coolclock is a little quirky. I managed to get the clock working with IE6 & IE7 but IE8 wasn't having any of it; bit of of shame as it's a nice solution. Good news is on the horizon though, IE9 will support canvas by default so no nasty JavaScript hacks.
Eventually I decided to add the clock as a type of 'progressive enhancemen' by wrapping the function in the following:
//IE returns false since it uses 'styleFloat'.
if(jQuery.support.cssFloat){
//IE can't see this code
}
I's not great, and I hate having to do it but if users want to see a cool clock they will have to upgrade to a modern browser (that's not IE8).
For those who are interested, here's a quick demo of the code in action.
--- End: Coolclock: HTML5 Clock that is Actually Quite Cool*
--- Start: Snipplr: How to Annoy Your Site Users
Published on: 18 March 2010
https://nooshu.com/blog/2010/03/18/snipplr-how-to-annoy-your-site-users/
Main Content:
Update: Snipplr now has a new owner so these issues should be ironed out very soon, I've written a new blog post here.
I feel quite sad I'm having to write this post but it's been a long time coming. I've been a big fan of Snipplr.com, having been using it for over 4 years it's become an essential part of my daily development process; I even mentioned it a few months ago in a recent blog post 'Useful Websites for a Front-end Web Developer'. Lately a few things have changed on Snipplr for the worse.
My first annoyance is the amount of spam posts and comments the site gets; now I understand it isn't Snipplr's fault that they are a target for spammers but they don't seem to be doing anything about it. The sign-up process obviously isn't strong enough to stop the spam bots getting in, so have a rethink and change that. I can't tell you the number of hours I've spent pressing the 'Report this snippet' link on spam posts; recently I've just given up. Unfortunately you can't report comment spam and in the last week I've had an influx of spam on quite a few of my snippets. Not good!
Now spam, okay it's annoying but I can live with it as all I want to do was get to my code snippets. The final nail in Snipplrs coffin for me is all the new advertisment banners they've recently added. There are now so many it's actually effecting the usability of the site!
I understand it may be costing money to run the site as it is quite popular, but shoving banners down your users throats isn't the best idea if you want to keep them using the site. They will just go elsewhere, and thats exactly what I'm doing. In the Snipplr setting you will find an export function, but it doesn't seem to be working at the moment so it could be a long copy / paste job... bugger.
A couple of alternatives I'm trying at the moment are Snipt and DZone Snippets, I haven't decided on which one I prefer yet, but they both look promising.
--- End: Snipplr: How to Annoy Your Site Users
--- Start: Book Review: jQuery Enlightenment
Published on: 15 March 2010
https://nooshu.com/blog/2010/03/15/book-review-jquery-enlightenment/
Main Content:
About a month ago I had the pleasure of reading 'jQuery Enlightenment' by Cody Lindley, a truly excellent book any Web Developer from beginner to advanced should have on their to-read list. Now I don't usually enjoy reading books about code as they are usually as dull as dishwater; just something you have to get through before you can get onto the interesting part of making it work for you; jQuery Enlightenment is different.
It starts by going through the basic concepts behind jQuery and how to use it, if you are already a jQuery developer you could skip this, but as it's packed full of short concise information you never know what you may learn. The book covers all aspects of jQuery you will need to get you started plus much more, from selecting, manipulating and traversing DOM elements all the way through to plug-ins and best practices.
There were countless times while reading I thought to myself 'Well, I didn't know you could do that!', here's one of my favorites:
jQuery(function($){
$("#testanchor").bind("keypress mouseenter focus", function(e){
//Event fires keypress, mouseenter and focus
console.log(e.type);
//Do stuff....
return false;
});
});
The bind() method can accept more than one event type, so the above function fires when any one of the listed events is detected on our #testanchor. I can't remember the number of times where I've used multiple binds on the same element to achieve the same effect.
The book is packed full of useful code snippets like the one above that will save you time and effort when it comes to jQuery development. Being only 123 pages long it's a fairly quick read, and it's always great to have on hand as a reference when needed.
Grab it from here as an eBook for $15 or hard copies are available from lulu.com if you prefer that.
--- End: Book Review: jQuery Enlightenment
--- Start: Formula One 2010 Season, people to follow on Twitter
Published on: 12 March 2010
https://nooshu.com/blog/2010/03/12/formula-one-2010-season-people-to-follow-on-twitter/
Main Content:
I've been a Formula One fan for as long as I can remember, my first experience was back in 1987 at Silverstone when the cars had turbos... oh the old days! The new season looks to be one of the most exciting yet, what with a couple of new teams, regulation changes and Schumacher has come out of retirement, roll on Sunday at Bahrain!
Twitter has become a great tool if you are looking for inside information on what is happening in and out of the paddock, so if you're interested in F1, here are a few people you should be following (if spot any fakes or know of others let me know!):
Drivers
Jenson Button (@The_Real_JB)
Rubens Barrichello (@rubarrichello)
Bruno Senna (@BSenna)
Heikki Kovalainen (@H_Kovalainen)
Nico Hülkenberg (@NicoHulkenberg)
Lucas di Grassi (@lucasdigrassi)
Karun Chandhok (@karunchandhok)
Felipe Massa (@Forza_Felipe)
Fernando Alonso (@NanoAlonso)
Mark Webber (@AussieGrit)
Nick Heidfeld (@NickHeidfeld)
Teams / Team Employees
Virgin Racing (@virginf1racing)
Mercedes GP (@OfficialMGP)
Lotus F1 (@lotusf1racing)
Ferrari (@InsideFerrari)
McLaren (@TheFifthDriver)
Force India (@clubforce)
Redbull (@redbullf1spy)
Toro Rosso (@ToroRossoSpy)
BMW Sauber (@BMWSauberF1Team)
USF1 Team (@USF1Team)
Ross brawn - Mercedes (@rossbrawngp)
Mike Gascoyne - Lotus (@MikeGascoyne)
Ex-Formula One Drivers
Nigel Mansell (@Mansell5)
Nelson Piquet (@NelsonPiquet)
Jacques Villeneuve (@27villeneuve)
Juan Pablo Montoya (@jpmontoya)
Sir Stirling Moss (@StirlingMossCom)
Official / FIA
Formula1.com (@F1)
F1™ Timing App (@f1timingapp)
BBC F1 Team
Jonathan Legard (@legardj)
Lee McKenzie (@LeeMcKenzieF1)
Ted Kravitz (@tedkravitz)
Sarah Holt (@sarahholtf1)
Andrew Benson (@andrewbensonf1)
Jake Humphrey (@jakehumphreyf1)
Radio 5 Live F1 (@5LiveF1)
BBC F1 (@bbcf1)
Independent Bloggers
James Roberts - Features Editor, F1 Racing (@JRobertsF1)
Well just a few people to follow there. I'm sure I've missed a few people off. Leave a comment if you know of any others and I'll add them to the list.
--- End: Formula One 2010 Season, people to follow on Twitter
--- Start: Preview Post Broke in WordPress?
Published on: 05 March 2010
https://nooshu.com/blog/2010/03/05/preview-post-broke-in-wordpress/
Main Content:
I've had a problem with my blog that has been on the back of my mind for a while now; whenever I click the 'Preview' button it simply shows my homepage. No errors... just my homepage. I had a search about and there were suggestions it may be because of the use of a sub-domain (or lack of in my case). So I tried changing a few settings in the admin panel, but still no luck. I thought it may be a .htaccess issue until I enabled the now famous Kubric theme, also know as 'default'; and suddenly the preview function worked. So it was an issue with my theme... Oops!
My immediate thought was the 'functions.php' file since the 'single.php' file was pretty much the same as Kubrics. After a few minutes of head scratching I finally solved the issue, my sidebar was breaking things:
//Register Sidebars
$p = array(
'before_widget' => '',
'after_widget' => ' ',
'before_title' => ''
);
if (function_exists('register_sidebars')){
register_sidebars(2, $p);
}
Note the use of 'p′,itmustbeusedinternallybyWordPress.Myfunctions.phpwasoverwritingthisvariableandbreakingthepreviewfunction.Oncethisischangedto′args' everything worked perfectly:
$args = array(
//settings here
);
if (function_exists('register_sidebars')){
register_sidebars(2, $args);
}
So there you go kids, don't use $p in your themes / plug-ins, use something a little more descriptive for your variable names.
--- End: Preview Post Broke in WordPress?
--- Start: Changing your WordPress Sidebar Markup
Published on: 03 March 2010
https://nooshu.com/blog/2010/03/03/changing-your-wordpress-sidebar-markup/
Main Content:
While creating a theme for WordPress today I ran into a little problem with my sidebar; the layout of the sidebar didn't quite fit my needs for the design in-hand. At first I thought it could be a case of delving into the WordPress core code that generates all the widgets and modifying where needed, but that isn't much fun. You also run the rist of these changes being overwritten next time you update WordPress; there had to be another way.
Purely for styling I needed to add an extra span to the title and a div to the widget wrapper. After searching through the Codex I came across the perfect solution:
//Custom settings in associative array
$args = array(
'before_widget' => '',
'after_widget' => "
",
'before_title' => '"
);
//Check for register function and register the sidebar
if (function_exists('register_sidebars')){
register_sidebars(1, $args);
}
You simply create an array with your custom settings and pass it into the register_sidebars function along with the number of sidebars you wish to register; paste that into the functions.php file in your theme and you're done. If you don't have a functions.php file you can just create one. All the settings are pretty self-explanatory and with these changing widget markup is easy.
On a side note; I've never been a big fan of using nested lists in the sidebar, I'm not sure it's semantically correct; but I guess it does the job and works even when CSS is disabled.
You learn something new everyday!
--- End: Changing your WordPress Sidebar Markup
--- Start: Useful websites for a Front-End Web Developer
Published on: 01 March 2010
https://nooshu.com/blog/2010/03/01/useful-websites-for-a-front-end-web-developer/
Main Content:
Over the past few days I've compiled a list of websites I use quite frequently that really help speed up the Web Development process. The sites won't build your pages for you but they can certainly help when it comes to debugging and problem solving.
Clean CSS
I have been using Clean CSS for a few years now to clean up and optimise my CSS. The tool will give you a break down of where you can be making optimisations and also point out potential issues with invalid properties. You can either apply the changes manually, as it gives you a line number (my prefered method) or you can download the output as a file. I must admit I only use it every so often as I've merged most of the optimisations into my working process.
An exception to that rule is when working with other peoples CSS, it's always my first port of call. There's even the ability to create your own template, so the CSS can be formatted just as you like it when it comes out the other end.
Snipplr
Snipplr has been around for a couple of years now, it's a excellent place to store all those little snippets of code that you often use. You can view other peoples snippets too, so if you're looking to a solution to a problem there's no need to re-invent the wheel; look see if someone else has a solution.
The only real issue I have with Snipplr is the amount of spam it receives, which is a real pity as it's such a useful tool. Maybe that's something the developers can look into fixing.
Em Calculator
For a few years now I've been setting my font sizes using the relative unit em's rather than pixels or points. This was due to the fact that if you set your font size in pixels, IE6 users can't increase the font size due to IE6 being... erm... a truly awful browser; not good at all for accessibility. Luckily IE6 is gradually fading away and IE7+ all scale font sizes properly, so in the future this tool won't be needed.
The problem with using relative font sizes comes when you have a nested elements. Say you have an unordered list with its font size set to 12px (0.75em) and you want one of your list items to be set to 10px (0.63em). Since we are using relative font sizes the 0.75em has an effect on the lower list items. If you simply set the the list item to 0.63em the text size will be tiny because you are asking the browser to set a size of 0.63em of 0.75em. Not what we wanted at all! This is where Em Calculator comes in useful as it does all the calculations for you. You actually needed to set the list item to 0.83em….duh!
jsFiddle
I've mentioned jsFiddle before, it's a tool that allows you experiment with HTML, CSS and JavaScript and see the results on the same page. In the past couple of days they've added a new version of Processing and the RaphaelJS library. A link to my previous post on jsFiddle is available here.
HTML Entity Character Lookup
If you've ever had to build a set of multi-lingual HTML emails you will know how tedious it can be to encode all characters so they are valid HTML. Lucky with HTML Entity Character Lookup by LeftLogic it's simple. Copy and paste the character you want to encode into the tool and it will give you encoded version; do a quick search and replace then you're done.
For OS X users there's also a dashboard widget you can use for easy access.
CSS Sprite Generator
Using the sprites method can speed up your page load time by minimising the number of HTTP Requests a users browser has to make to the server. It involves consolidating all your little icons and background images into one file, then moving that one image around using the background-position property.
You could do this manually in Photoshop, or you could get an on-line tool to do it for you. CSS Sprite Generator is my favourite of the sprite generators available. Simply ZIP up the files you want to sprite, upload them to the tool and it will return one large image and all the relevant CSS background-positions for you to copy / paste into your CSS file.
It's particularly useful when it comes to site navigations. Having the off, on and hover states all in one background image means the user doesn't see that ugly flash of unstyled content as hovering over the navigation bar, since all states are loaded when the user first hits the page.
Are there any others I'm missing? Leave me a message via the contact form if there are others you use.
--- End: Useful websites for a Front-End Web Developer
--- Start: jsFiddle: My new favourite website
Published on: 23 February 2010
https://nooshu.com/blog/2010/02/23/jsfiddle-my-new-favourite-website/
Main Content:
Every so often you come across a site that is so amazingly obvious that you think "why didn't I think of that!", jsFiddle is one of those sites. It allows you to paste your HTML, CSS and JavaScript code, and view the result all in the same page... simple! There are other sites out there that do the same such as Jsbin, but they just don't do it as well.
My favourite feature that really stands out is being able to include one of the many popular JavaScript library's by simple toggling a drop-down box; it even has different versions of each library to choose from. This is a really handy feature if you are a plug-in developer; keep your plug-in code in jsFiddle and quickly see if the latest version of the library breaks it.
Library's included so far are:
Mootools Core
jQuery
Prototype
YUI
BBC Glow
Dojo
Processing.js
A couple of other features available are the easy to access code examples for each library and ability to run Ajax requests directly in the page. It's like a mini IDE in your browser, all it needs now is an error console; maybe that is on their to-do list. If you don't use JavaScript library's and just want vanilla JavaScript, they have that option too.
As an example I've added my charactersLeft jQuery plug-in to jsFiddle, take a look here. Very cool huh!
--- End: jsFiddle: My new favourite website
--- Start: WordPress and Feedburner Woes
Published on: 22 February 2010
https://nooshu.com/blog/2010/02/22/wordpress-and-feedburner-woes/
Main Content:
For a couple of weeks now I've been having issues with Feedburner and the Nooshu RSS feed. When I added a post to the blog, Feedburner wouldn't update; I had some luck with 'pinging' Feedburner manually as mentioned in their documentation but having to do this every time isn't ideal. That method worked a couple of times then also stopped working.
So I tried changing the URL of the feed, maybe that was the problem. Nope that didn't work either; it would pull in the new feed and the latest posts but then get stuck again. It was only when I noticed a link to Ping and Extended Ping XML-RPC API that it finally clicked; I had disabled XML-RPC on the blog while playing with some of the settings.
Once checked you will see this code added to your WordPress header:
Now it could be a complete coincidence that it just happened to start working when I enabled XML-RPC, but as long as it works I'll keep it checked.
Update: Okay, so maybe I spoke to soon, the issue still seems to be occurring quite randomly, I'm thinking it could be a plug-in issue. I'll update again if I find a solid solution.
--- End: WordPress and Feedburner Woes
--- Start: The append and appendTo jQuery methods
Published on: 21 February 2010
https://nooshu.com/blog/2010/02/21/the-append-and-appendto-jquery-methods/
Main Content:
With every new release of jQuery more and more features are added. A set of features I use all the time for manipulating the DOM are the prepend() and append() methods. In addition to these methods you also have prependTo() and appendTo(); they vary slightly in the fact that you create your new content first, then choose an element to add it to:
//Create our content
var appendHTML = "I'm going to be added to the DOM
";
//Select our element, then add the html
$("#container").append(appendHTML);
//Create our content, then select the element to append to
$(appendHTML).appentTo("#container");
Prep-end works exactly the same only it adds the content as the first-child of the container rather than the last-child.
With version 1.4 of jQuery came a great addition to both methods;they can now accept a function which returns the index in the current set of elements, and the original HTML string of the element. The addition allows you to loop through a whole set of elements and easily add content to the beginning / end whilst including the original content:
//Loop through all tags and prep-end "I love jQuery."
$("p").prepend(function(index, html){
var newHTML = "I love jQuery. " + html;
$(this).html(newHTML);
});
//Loop through all
tags and append ", now with added spice!"
$("p").append(function(index, html){
html += ", now with added spice!";
$(this).html(html);
});
Very handy! I've put together a little demo to demonstrate this functionality in action.
--- End: The append and appendTo jQuery methods
--- Start: SWFObject 2.2 and wmode transparent
Published on: 18 February 2010
https://nooshu.com/blog/2010/02/18/swfobject-2-2-and-wmode-transparent/
Main Content:
Just a quick post on a snippet of code I always forget (I think it must be my age). I use SWFObject (v2.x) to include Flash into pages, but I always forget how to embed it with a transparent background; not anymore:
var flashvars = {},
params = {wmode:"transparent"},
attributes = {};
swfobject.embedSWF("/swf/yourSWF.swf", "anim", "300", "200", "9.0.0","/swf/expressInstall.swf", flashvars, params, attributes);
It's just so simple, I have no idea why I never remember it. Simply pass an object with 'wmode' set to 'transparent' when you call embedSWF().
On a side note you can always load SWFObject from the Google AJAX Libraries API:
It can take some pressure off your own server in serving the file and there's a chance that the user will have the file cached from a previous site using SWFObject.
Update: Have removed the quotation marks around wmode as it was causing issues, thanks junats!
--- End: SWFObject 2.2 and wmode transparent
--- Start: New jQuery delay() method
Published on: 15 February 2010
https://nooshu.com/blog/2010/02/15/new-jquery-delay-method/
Main Content:
I'm a little late with this post as jQuery 1.4 (and since then 1.4.1) came out on January 14th but I'll write it anyway. A simple little method that has been added to the core is delay(); it allows you to delay the execution of functions that come later in the queue. There have been times in the past where I've wanted a transition to pause for a couple of seconds, then continue; so to do this I was using a snippet of code from Karl Swedberg:
jQuery(function($){
$("#selectedElement").fadeOut().animate({opacity: 0.0}, 2000).fadeIn();
});
The code above animates at 0 opacity for 2 seconds; since the element already has 0 opacity (from the fadeOut) nothing happens, then it fades back in. The method worked but it was a bit of a hack. So now we can use the delay method:
jQuery(function($){
$("#selectedElement").fadeOut().delay(2000).fadeIn();
});
Simple! The method can take a value (in milliseconds) for the delay or it can take the usual 'slow' and 'fast' strings for 200 and 600 milliseconds respectively. The delay method is just the tip of the iceberg with jQuery 1.4, it's well worth an upgrade.
--- End: New jQuery delay() method
--- Start: Google broke my Gmail Labels
Published on: 11 February 2010
https://nooshu.com/blog/2010/02/11/google-broke-my-gmail-labels/
Main Content:
This morning I had a very annoying problem with my Gmail account; it looks like Google have been tweaking since the release of Buzz. All my inbox folders and labels had disappeared. Viewing from Firefox everything was fine, but in Google Chrome nothing! Arghh!
After a bit if thinking, the only difference between the two setups (apart from the browser of course) was the fact that in Chrome I'm using Offline mode (Google Gears). After quickly disabling this and re-enabling, everything worked perfectly again. I will keep that in mind for future issues.
Note: When re-enabling Offline mode Gears will have to sync with the mail server again which could take a while.
--- End: Google broke my Gmail Labels
--- Start: Finding WordPress Administrator User IDs
Published on: 10 February 2010
https://nooshu.com/blog/2010/02/10/finding-wordpress-administrator-user-ids/
Main Content:
I've been adding a couple of new features to Post Ideas+ over the past few days. One feature in particular required knowing the ID's of users with the role of 'administrator'. Now usually you can assume that the ID will be 1, as that'ss what the initial adimin account setup by WordPress on install gets assigned. But as the code is going to be used in a plug-in you can't really assume that.
Some people may have deleted the default account for security reasons (very good idea) or they have more that one administrator account. After hunting about on the WordPress forums for a while I managed to piece together a little snippet of code to do this:
//Get all admin user ID's in the DB
function admin_user_ids(){
//Grab wp DB
global $wpdb;
//Get all users in the DB
$wp_user_search = $wpdb->get_results("SELECT ID, display_name FROM $wpdb->users ORDER BY ID");
//Blank array
$adminArray = array();
//Loop through all users
foreach ( $wp_user_search as $userid ) {
//Current user ID we are looping through
$curID = $userid->ID;
//Grab the user info of current ID
$curuser = get_userdata($curID);
//Current user level
$user_level = $curuser->user_level;
//Only look for admins
if($user_level >= 8){//levels 8, 9 and 10 are admin
//Push user ID into array
$adminArray[] = $curID;
}
}
return $adminArray;
}
//Usage
$adminIdArray = $this->admin_user_ids();
I placed it into it's own function within my plug-in Class so it can be called whenever needed. It could also be used for finding users with different levels in WordPress if needed. If you wanted you could modify the function to accept an argument admin_user_ids($the_user_level_i_need); allowing you to get the IDs of users at whatever level you like.
There seemed to be a few ways of doing this on the forums, but this one works for me at the moment.
--- End: Finding WordPress Administrator User IDs
--- Start: Firefox Extensions for Web Developers
Published on: 08 February 2010
https://nooshu.com/blog/2010/02/08/firefox-extensions-for-web-developers/
Main Content:
Firefox is my development browser of choice, and has been for a long time (since Firebird 0.6 from what I remember). The browser on its own has a basic set of tools for debugging but with extensions you can turn it into the perfect tool for developing websites.
Note: This is in no way a comprehensive list; there are hundreds out there to choose from, these are the few that I use every day. You only need to take a quick search of delicious to find 'X number of Firefox extensions you must use!!' lists; I'm not a big of those types or posts as they all seem to post the same info.
Firebug
I think every Web Developer has heard of Firebug; I honestly can't remember how I managed to get anything done before I started using it, it's such a time saver. It comes packed with useful tools like a HTML inspector, CSS inspector, JavaScript debugger and website performance analysis (Net tab). You can even extend it's functionality using plug-ins e.g Firecookie and ySlow.
One word of warning when using Firebug; make sure you disable / close it when you aren't using it as it will increase page render time massively.
Web Developer Toolbar
Yet another tool that most Web Dev's must have heard of as it is such a brilliant extension. There are way to many features to list here but my personal favourites are: quickly disable/enable JavaScript, view alternative media stylesheets, view page document size, display line guides and resize the browser window to a specific resolution. Most of it's functions I've never used but you never know when they may come in useful; download the Web Developer Toolbar.
Colorzilla
Colorzilla is one of those extensions that you don't realise how much you use it until it isn't available to you. This little tool allows you to hover over any colour (color) on a page and it will give you the corresponding Hex / RGB value. Great for when you don't want to go hunting through a stylesheet for the colour.
It has a few options I very rarely use such as the colourpicker and the ability to save favourite colours, I prefer Photoshop and a notepad to be honest but each to their own I guess.
FireFTP
For a long time I was a FlashFXP user; that was until I stumbled upon FireFTP. The extension embeds an FTP client directly into a Firefox tab! My favorite feature (which is in most FTP clients) is the ability to keep local and server folders in sync. It's also possible to drag files directly from a folder on you computer straight to the server (not vice versa though unfortunately).
One feature I wish it had was the ability to ignore certain file types when uploading e.g. .svn folders. It's possible to get round this issue by hiding hidden files / folders; then of course you fail to upload the hidden .htaccess file and break your URLs…. oh well not a bad compromise when it's free to use (the author does accept donations which go to a generous charity for children).
Fireshot
Fireshot is one of many screenshot tools available for Firefox; it comes in both free and pro versions, but I've never needed any of the pro features. Gone of the days of pressing the 'Prnt Scrn' button and stitching long pages together, Fireshot does it all for you. Another great feature is the ability to screenshot Flash on a page which doesn't usually show up using print screen.
HTML Validator
My final extension is HTML Validator, this places a small icon in the bottom right of your status bar and tells you when it runs into invalid HTML. Now I don't always use this but its good when you are editing large pages and your layout is breaking due to a missing closing tag; it may not solve the issue but it will give you a line number of where to start looking.
I would recommend disabling the plug-in by default then creating a ‘whitelist' of sites you wish it to be enabled, as it can seriously slow down your browser.
If you have any recommendations for extensions let me know, maybe I'm missing a treat in that 'must use!' extension.
--- End: Firefox Extensions for Web Developers
--- Start: More Frog CMS Magic
Published on: 08 February 2010
https://nooshu.com/blog/2010/02/08/more-frog-cms-magic/
Main Content:
Over the weekend I was working working on a small website build that required a simple CMS so I decided to put Frog CMS to use again; it continues to impress me. What at first looks like a very simple CMS actually has a powerful API behind it.
First thing I had to do (for my own sanity) was move the layout template outside of the CMS and into an external file. This gives you 2 advantages, you get to use whatever code editor you usually use to edit the template, and the file is then exposed so it can be committed to version control like any other file. It is simple to do with some very basic PHP:
Paste that code in to your layout with a content type of 'text/html' and you are done.
The second code snippet allows you to generate a specific ID and class for every page; great if you need some CSS style / JavaScript hooks on different pages.
slug();
endif;
if($this->parent() && $this->parent->slug()=="services"):
$bodyClass = "event";
else:
$bodyClass = "";
endif;
?>
The first if else statement simply sets the home ID to 'home' then every other page to 'page-slug-name-here' (slug is set in the 'Meta' tab). The second one I use on 'article' pages; it simply says if the current page has a parent and its parent is the services page add a class of 'event'. So now I can style every article page in the same way, and it's safe for a client to add event pages themselves.
You may ask why the $this->parent(); this is to stop the site breaking when you hit the home page since the homepage has no parent, it is the parent of all other pages.
--- End: More Frog CMS Magic
--- Start: Frog CMS - Nice and simple CMS
Published on: 03 February 2010
https://nooshu.com/blog/2010/02/03/frog-cms-nice-and-simple-cms/
Main Content:
You often find that most small websites that require a CMS don't require all the features that some of larger solutions offer. While the likes of MODx, Expression Engine and even WordPress are amazing platforms to work from, they can be a little overkill for very small sites. (WordPress isn't strictly a CMS, but it can be hacked to perform similar actions).
I decided to look for a simple solution; that's when FrogCMS popped up. It's free, open-source and very simple to setup. Upload to your server, create your MySQL database with relevant privileges, run the install script and there you go. A big plus point with Frog is the administration page is very straight forward to use, so even the most technophobic client shouldn't have a problem editing their pages.
The templating system is a breeze to use if you know a bit of basic PHP. For example say you want to add a main navigation that automatically updates as you add pages:
href="">Home
find('/')->children() as $menu): ?>
link($menu->title, (in_array($menu->slug, explode('/', $this->url)) ? ' class="active"': null)); ?>
The 'foreach' just loops through the children off the main site route and generates the navigation as an unordered list. Defining editable areas in a layout is just as simple:
//Add a snippet
includeSnippet('top-navigation'); ?>
//Add your main page content
content(); ?>
//Add another area of content called 'sidebar'; Controlled via a tab on the page admin.
content('sidebar'); ?>
//Test to see if we have content, then show
hasContent('sidebar')) echo $this->content('sidebar'); ?>
Even with just those simple lines of code it is possible to create a dynamic user managed website. If it doesn't do exactly what you want you could always write a [You often find that most small websites that require a CMS don't require all the features that some of larger solutions offer. While the likes of MODx, Expression Engine and even WordPress are amazing platforms to work from, they can be a little overkill for very small sites. (WordPress isn't strictly a CMS, but it can be hacked to perform similar actions).
The only negative point I have to say is that it doesn't seem to get updated very often, but for most projects that shouldn't be a problem as it's already has a solid code base with lots of support and docs available.
--- End: Frog CMS - Nice and simple CMS
--- Start: Flot and chaos
Published on: 01 February 2010
https://nooshu.com/blog/2010/02/01/flot-and-chaos/
Main Content:
Recently I started re-reading a book by now Professor, Ian Stewart, called "Does God play dice?". A truly fascinating book about how the universe isn't always predictable. It all comes down to Chaos Theory.
In the first chapter page 14 & 15 the reader is invited to grab a calculator and create a little chaos. With a few key presses it's possible to create a completely chaotic pattern of numbers. Ian Stewart has also added a little graph to show what that pattern looks like; this is where Flot comes in.
Flot is an pure JavaScript graphing engine for jQuery. It can create great looking graphs in a matter of minutes. Pass your data in an array to Flot, it does all the hard work and a graph pops out the other end using the HTML5 canvas tag with some VML magic. It is even supported by IE, just add a conditional tag with a script tag pointing to excanvas.pack.js.
The equation to create this set of chaotic data is very simple:
x = k*(x*x)-1;
As you can see from the formula above, the equation is a feedback loop. With each iteration a new value of 'x' is created and fed back in. The amazing thing about this equation is how simple it is to get both order and chaos. Set your value of 'k' to 1 and after a few iterations order is achieved; set 'k' to 2 and you get chaos.
I will be posting a demo to play with in the next few days, it isn't quite finished yet but you can see a screenshot above.
--- End: Flot and chaos
--- Start: WordPress plug-in: Post Ideas+
Published on: 29 January 2010
https://nooshu.com/blog/2010/01/29/wordpress-plug-in-post-ideas-plus/
Main Content:
Note: This plug-in is no longer maintained.
For a while now I've been using a great little plug-in for WordPress called 'Post Ideas' by Aaron Robbins. It was released in early 2008 but unfortunately hasn't been updated since. Aaron's website now seems to be a bog standard install of WordPress that hasn't been updated so there was no way of getting in contact with him.
So I decided to update the plug-in myself. I've updated the admin area and added 2 dashboard widgets; A widget to view your latest 'X' number of post ideas and a widget to quickly add a post idea to the database. Both can be disabled from the "Screen options" menu above the dashboard.
The plug-in stores a title, description, tags, links and priority associated with the post. Easy to update, write and delete from the admin menu or dashboard widget.
Installation is the same as with any other WordPress plugin:
Download the zip file and extract. Upload all files to the '/wp-content/plugins/'. Make sure you upload in the correct folder structure e.g. /wp-content/plugins/post-ideas-plus/.
Activate the Post Ideas+ plugin through the 'Plugins' menu in WordPress.
Under 'Tools' you should see an new option 'Post Ideas+'. You can add / edit / delete ideas from this page.
You should also see 2 new dashboard widgets 'Add post idea' & 'Latest post idea'. These can be disabled via the screen options.
If the script fails to install the required mysql table please use the included wp_piplus.sql file and import it to your wordpress database using phpMyAdmin (if your table prefix is not wp_ you will need to change it in the sql file)
If you have any questions, comments or suggestions please leave a comment or get in contact and I'll see what I can do.
NOTE: Download no longer available.
--- End: WordPress plug-in: Post Ideas+
--- Start: A little Google Chrome search tip
Published on: 26 January 2010
https://nooshu.com/blog/2010/01/26/a-little-google-chrome-search-tip/
Main Content:
Google Chrome has quickly become my new favourite browser. For a good few years Firefox (or Firebird as it used to be called) was my primary browser, but I found with all the web development extensions installed it was becoming slow and bloated. That's when I decided to give Chrome a try.
Based on WebKit; an open-source browser engine, it's standards compliant and very fast. Chrome has a very simple interface that has lots of nice touches. One I find I use all the time is the "keyword search" function. Here's how it works:
First navigate to your favourite website; one I use all the time is delicious. Quickly search for something in the search box, it doesn't matter what you search for, this is just to let Chrome know it is possible to search the site.
After a successful search right click on the Chrome address bar.
Find the 'Edit search engines' option and take a look inside. You should now see your favourite website listed.
Edit your favourite website and you will see "Keyword:". This is the shortcut key that allows you to quickly search the site. Edit it, make it short and something you will remember. In my case it is 'del' for delicious.
Now the fun bit; when you want to search the website again type in your keyword then the search term you're searching for e.g. "del photography".
And there you have it! A very quick way to search all of your favourite websites directly from the Chrome address bar.
It's also worth noting that Firefox can also do this and I'm sure there are similar features in other browsers.
--- End: A little Google Chrome search tip
--- Start: The tools of my trade
Published on: 25 January 2010
https://nooshu.com/blog/2010/01/25/the-tools-of-my-trade/
Main Content:
Like with anything else in life there's always a time where you wish you could take the knowledge you know now and pass it onto yourself a few years ago. I think Rod Stewart put it best in the song 'Oh La La'.
I wish what I knew now when I was younger
I've listed a few tools I use everyday as a web developer. It's not a definitive list and I'm sure there are lots of other solutions out there to do the same thing. Let another few years pass and I'll be thinking the exact same thing: "I can't believe I used to do it THAT way, how stupid of me."
XAMPP
XAMPP is an easy to install Apache web server that contains all you need to develop modern dynamic websites. It comes bundled with MySQL, PHP and Perl. Even if you only develop HTML / CSS it's still a good idea to setup your own development environment.Try and mimic the live server so you fix any issues that occur before you push them to the live server.
It's available for Windows, OS X and Linux so it covers all bases. It has a bright orange web front end with a few controls to allow you to edit various settings, but you may need to get your hands dirty at first with the initial setup. Editing your HOSTS file and the vhosts file in the XAMPP directory is a must.
Aptana
As I've mentioned before in previous blog posts,](http://aptana.com/) is my IDE of choice. It's based on Eclipse, an IDE written in Java and can be used to develop applications in many different languages. Both Eclipse and Aptana are open source so you can even dive in a fix bugs you come across yourself (Aptana on Github).
It comes bundled with a whole host of features, code auto-complete, project explorer, file sync over (S)FTP, code validation / error checking, JSLint and SubVersion integration to name just a few. If you're not sure where to start you could try taking a look at their video tutorials and the huge number of documents available. If you are still stuck you could always ask on the well established community forums.
One thing I will mention is at times it can seem a little bloated at times. Having been using it for a few years now I've noticed it getting bigger / slower. Quite a few times I've resorted to using a smaller text editor for quick code changes simply because](http://aptana.com/) takes too long to start up or it just seems to be running slowly. It's a shame you can't easily disable some unused features, but what with some modules depending on others to work you could end up breaking the install.
All in all though I've not found a better IDE with the number features available at such a low price (Free!).
Notepad++
The "smaller text editor" I noted above is Notepad++, a project hosted on Sourceforge and is free to download an use. You only have to look at the homepage to see the number of features it has available. And the best thing about it is it's fast, really fast.It loads instantly with no delay when typing / editing and does everything you need a code editor to do.
Firefox
Where would any web developer be without Firefox and it's extensions. Firefox is my code tester / debugger of choice. With thousands of extensions to download the possibilities for expansion are endless. Once you add Firebug and the Web Developer toolbar you have the perfect browser for refining and debugging your website.
TortoiseSVN
If you aren't using any form of version control on your projects you really don't know what you're missing. Version control allows multiple developers to work on the same code at the same time without fear of conflicts (this isn't strictly true, but with version control it notifies you of them and allows you to fix them).
Even if you are a freelancer who works on his own 90% of the time, version control is still something you should set up and use. Using version control means you can always roll back to a previous version when you break / delete something. Another big plus point is your work is now hosted on an external server. Should your hard drive break or your computer fall into someone else's bag, you will still have a backup of all your important work.
TortoiseSVN is simply a nice GUI for the (SVN) version control system. You can use the command prompt too if you so wish, but I've always preferred a GUI.
There are various types of version control available, each with there own pros and cons. Git is one I'm looking into, but as an SVN repository is bundled with my hosting provider I'll stick with it for the moment.
Conclusion
So there you have it, my web developer toolbox laid out for everyone too see. Now if only I could email this to myself in 2005, it would have saved a lot of frustration. Wouldn't have been as much fun learning though would it?
--- End: The tools of my trade
--- Start: WordPress: Are you sure you want to do this?
Published on: 22 January 2010
https://nooshu.com/blog/2010/01/22/wordpress-are-you-sure-you-want-to-do-this/
Main Content:
While writing a plug-in for WordPress recently I came across a very strange error message:
Are you sure you want to do this?
Now my initial reaction was "Well yes, I do want to do this". Unfortunately that wasn't an option. It just told me to try again… same message… ad nauseam. What I was actually trying to do was pass some form information from the plug-in dashboard panel to the plug-in tables in the database.
After searching the web for a while and not having much luck I decided to 'view source' on the Quickpress widget which was doing a similar function. I noticed these two hidden inputs:
After a brief search in google about 'Cryptographic nonce' it occurred to me that's what was missing. A vital security feature that WordPress uses to validate that the form information came from the current site rather than an external source. Very clever, but quite frustrating if you don't know about it.
Adding the following to the form code fixed the issue.
$content = '
The hidden inputs are inserted into the form allowing WordPress to validate where the request came from.
--- End: WordPress: Are you sure you want to do this?
--- Start: IE6 and the Abbreviation tag
Published on: 21 January 2010
https://nooshu.com/blog/2010/01/21/ie6-and-the-abbreviation-tag/
Main Content:
While testing a WordPress theme in various browsers (IE) I noticed a strange issue that was occurring in IE6, but fine in IE7+. After a little head scratching I realised IE6 doesn't recognise the abbreviation(abbr) tag. I'd never noticed before as I very rarely use the tag.
As a quick fix you could edit your theme:
Abbreviation here
Abbreviation here
Then apply any styles to the inner span rather than the abbr. Or if hard coding a span isn't your thing you could always use a little bit of jQuery(1.2+) goodness to add the spans for you:
jQuery(function($){
$("abbr").each(function(){
$(this).wrapInner(' ');
});
});
The effect on page render time will be minimal since we are only grabbing a single tag with no complex selectors.
--- End: IE6 and the Abbreviation tag
--- Start: Processing & Aptana make a good couple
Published on: 20 January 2010
https://nooshu.com/blog/2010/01/20/processing-aptana-make-a-good-couple/
Main Content:
I've been learning Processing on and off for three or four months now since i started reading 'Learning Processing' by Daniel Shiffman. A great book that makes learning easy and fun. One thing that frustrated me from the start was Processing's own IDE (Integrated Development Environment).
Now there's nothing wrong with PDE, it's just quite limited. Having come from Aptana (and before that Eclipse) it's missing quite a few features I'm used too. The main two being code complete and line numbers (Your current line number is displayed in the bottom left, but that's it). Lucky it is possible to use either Aptana or Eclipse (since Aptana is a modivied version of Eclipse) to program Processing.
The Processing website has a great step by step tutorial on how to do this 'Processing in Eclipse'.
Once complete you have all the features of the Eclipse IDE, including auto complete and line numbers (yay!). It will be a shame to not have all the code examples from PDE, but it's always possible to copy and paste where needed.
--- End: Processing & Aptana make a good couple
--- Start: Full Frontal 2009
Published on: 19 January 2010
https://nooshu.com/blog/2010/01/19/full-frontal-2009-in-brighton/
Main Content:
This post is slightly late as the conference was on the 20th November 2009. But better late than never i guess!
The day was very wet and rainy but that didn't take anything away from a brilliant conference. Some great speakers there: Simon Willison, Christian Heilmann and Peter-Paul Koch(ppk) to name a few.
The two highlights for me were the very entertaining talk on 'Optimising where it hurts' by Jake Archibold and a great introduction to node.js by Simon Willison. It was quite a technical talk and after a long day of listening to various people present it did make my brain hurt a little. I've added node.js to the 'TODO' list of things to look at eventually.
Hopefully there will be another Full Frontal in 2010, if there is I'll be going again.
--- End: Full Frontal 2009
--- Start: jQuery, WordPress and your functions.php
Published on: 18 January 2010
https://nooshu.com/blog/2010/01/18/jquery-wordpress-and-your-functions-php/
Main Content:
It's always interesting running ySlow on a website you are working on, getting that 'warm fuzzy feeling' when you finally get that 'A'. I noticed while using it on nooshu that jQuery was being included twice. Version 1.4 by me in the footer.php and version 1.3.2 being included by a plug-in (or WordPress itself). Not Good. The user gets an extra 40Kb download and an added HTTP request.
A quick way to fix this is to add this to your functions.php file (located in the theme directory). The admin section will still be able to use it's own version of jQuery due to the if statement.
if(!is_admin()){
wp_deregister_script('jquery');
}
If you don't have a functions.php file you can create a new one and paste that code inside. While in there you may also want to include this:
remove_action('wp_head', 'wp_generator');
That will remove your current WordPress version from your 'head' tag in your templates. Not a big issue but could be useful information to a malicious individual.
For more information on both functions in the WordPress codex see remove_action and wp_deregister_script.
--- End: jQuery, WordPress and your functions.php
--- Start: Equal height columns using jQuery
Published on: 18 January 2010
https://nooshu.com/blog/2010/01/18/equal-height-columns-using-jquery/
Main Content:
A while ago I was presented with a design that was split into 3 columns all of equal height. This isn't usually an issue but the content within the columns was going to be content managed by the client so would always be changing (or breaking). The designer was adamant that all the columns should line up across the bottom so I decided to write a quick jQuery plug-in to do this.
/**
* Simple equal height columns jQuery plugin
* Usage: $(".col").equalCols();
*/
(function($){
$.fn.equalCols = function(){
//Used to sort the array
var sortNumber = function(a,b){return b - a;};
//Empty array
var heights = [];
//Save the jQuery object for manipulation at the end
var $all = this;
return this.each(function(i){
var $this = $(this);
//Push all the heights into the array
heights.push($this.height());
//Once we have looped through all elements
if($.length === i){
//Sort the array
heights.sort(sortNumber);
//Set all elements to the same height
$all.css({'height': heights[0]});
}
});
};
})(jQuery);
As I haven’t had much need to create custom jQuery plug-ins so far this is great practice. It also shows how easy it is to add functionality using jQuery.
The downside to this is the user will need JavaScript enabled for it to work as is always the case with client side solutions. Since the user can still see the content, even with JavaScript off I see this as no big issue.
Update: I had a comment on my Snipplr account informing me about an example given on the jQuery.map() method API page. A lot less code than what I have above but may take a few minutes to get your head around what exactly is happening.
$.fn.equalizeHeights = function(){
return this.height(
Math.max.apply(this,
$(this).map(function(i,e){
return $(e).height()
}).get()
)
)
}
--- End: Equal height columns using jQuery
--- Start: Decode at the V&A
Published on: 18 January 2010
https://nooshu.com/blog/2010/01/18/decode-at-the-va/
Main Content:
Yesterday I took a little trip down to South Kensington to visit the Victoria & Albert museum (V&A). The reason i took this slight de-tore from north London was to see an exhibition they currently have on called 'Decode'.
It consists of 15-20 different art insulations, some interactive, some not; and is a collaboration between the V&A and digital arts organisation onedotzero. Not all insulations seemed to be working which is a pity; I guess that's a problem with digital art, the blue screen of death. The ones that were, were very inspiring. The interesting part for me was where these art insulations get there data from, be it from the internet, user input or even the wind blowing past the museum at that very moment!
My personal favourite was one called Weave Mirror (2007) by Daniel Rozin. It consisted of 744 semi-circles painted black / cream with a gradient running between the two extremes. Each one was motorised and rotates between light and dark. These semi-circles are then used to recreate a shadow on a wall that is controlled by the user. It's quite hard to explain, the image above will give you more of an idea of how it works.
I noticed a few of the art pieces were using Proccessing, an open-source programming language for people who want to program images, animation, and interactions. Now since I have a great book by Daniel Shiffman called "Learning Processing" I was very excited by this. It has been sitting on my bookshelf for a couple of months now, but I think it's about time I dusted it off.
For anyone who is interested in interactive art or data visualisation, I'd highly recommend going to see it while it's still on.
--- End: Decode at the V&A
--- Start: My first blog post
Published on: 17 January 2010
https://nooshu.com/blog/2010/01/18/my-first-blog-post/
Main Content:
So today I finally plucked up the courage to write a blog post. I've had this domain/blog sitting here for over a year now with every intention to do something with it. It didn't happen, until now!
I started my first blog in 2005 for a college project. I managed to write the grand total of 1 blog post, then it was left to fade away and die. The domain name wasn't renewed (looking at it now I'm quite glad about that). My new goal is for 2 posts on the site, at least then I won't be disappointed.