Quite a while ago, I wrote an article about jQuery .on() and off() – an improved way of attaching events in jQuery – and still the best way to attach events to DOM elements in jQuery.
Being able to apply and remove events with on() and off() is great, but sometimes there is a requirement to either trigger or remove a subset of events that have been added to an element. For example:
$('.item').trigger('click'); // both functions are triggered
$('.item').off('click'); // both functions are removed.
Using event namespacing we can assign names to event handlers when we create them, and then use them later on to target specific functionality when we call trigger() or off(). The name you choose for your event namespace should be relevant for the functionality you are calling. For example:
$('.item').trigger('click.navigate'); // only the function assigned to the namespace navigate would be triggered.
$('.item').off('click.notify'); // only the function assigned to the namespace notify would be removed.
It’s also possible to use multiple namespaces, like so: $('.item').on('click.navigate.notify', doThisCoolThing);
$('.item').trigger('click.navigate'); // will trigger the click event function.
$('.item').off('click.notify'); // will remove the click event.
Namespacing events in jQuery has been available for some time and isn’t limited to just on() and off(). It also works with .bind() and .unbind() too.
Inspired by a post I read earlier this week on how difficult it can be for newcomers to get in to the industry (I’ve lost the link, if you know what I’m referring to please let me know), I decided that I wanted to write a post with some hints and advice for developers who are just starting out their careers.
This post does not include any code or best practices and it is not a tutorial or guide to writing web pages. Instead the points below are aimed toward explaining what to expect as a web developer, and some of the key things you should consider as early in to your journey as possible.
There are so many things to learn in web development now that it can feel incredibly overwhelming – but it can also be very rewarding. What fascinated me about web development was the ability to create – I love to create – and when I started out building web pages I found it incredibly easy to express my creativity with HTML and CSS in just a few lines of code. I could create something and then publish it on the web for others to see very quickly (which at the start of your career will likely just be your Dad and your best friend).
There Are Multiple Ways To Do The Same Thing.
One of the hardest concepts to get your head around when you start working in web development is that there can be be multiple ways to do exactly the same thing. For example, if you want to create a 2 column blog layout, there are a multitude of ways to do this. For most things, there is no single answer – there are multiple solutions to the same problem. Sometimes there will be solutions that are better suited than others, but there are also solutions that are equally valid as others; or solutions that are better in certain scenarios.
Try not to look at this as a negative thing, but instead use it as a way to encourage your creativity. Make a decision on the solution to use this time around and as you use it see what works and what doesn’t work. You’ll learn more by trying a solution than forever searching the Internet for the perfect answer, because the truth is…
Your Code Will Never Be Perfect.
When you look back at the code you have written previously – whether it’s one, two or six months later, or even the next day or after the weekend – you will see ways you can make things better. This is a good thing. It means you are learning and improving. Don’t be afraid to write imperfect code. With every site you develop, there will be a time that you have to let it go. It is better to be feature complete than to have 5 immaculate lines of code that do 10% of what you were trying to achieve. If someone wants to discuss with you about what you have written, it’s an opportunity to ask them how you can make it better. It’s a great way to learn; and you will find that different people with different backgrounds will have different experiences they can share.
You Will Never Know Everything About Web Development.
(But that doesn’t mean you should stop trying)
Nobody can honestly say that they know everything about web development – not every feature, every property and every browser bug. The scope of front end web development is so broad that it covers three completely different languages – HTML (markup), CSS (design and style) and JavaScript (logic).
Each has their own structure, concepts and quirks and each is continually updated with new features. Unless you are building pages from a template, each site you build is likely to require a different configuration and with that come new challenges. There are also libraries, frameworks and APIs that you will need to become accustomed with over time as the situation demands.
The truth is that you don’t need to know everything straight away. You need to know how to build a web page that meets your initial basic requirements. Then going forward, you will need to know how to learn; who to talk to or where to go to find out what you need to know to do your next task. Knowing where to look and how to pick things apart in a skill in itself and one that is very useful. You’ll pick up knowledge and learnings as you go along.
Google, MDN and Stack Overflow Are Your New Best Friends.
If you have a problem, there is a 99.99% chance that it has already been solved. Multiple times. Using Google to search for a problem can often return the right results if you include the language and browser you are experiencing the issue in, e.g. “CSS IE6 Margin”. MDN (the Mozilla Developer Network) is an excellent source for finding out more detail about HTML elements and attributes; CSS styles and properties; and JavaScript APIs and methods. Stack Overflow is a place where developers can ask questions and receive answers from other members of the community. It is always worth searching their answers database – particularly if you are unsure of the exact term as the chances are someone with a similar amount of knowledge has asked the question with similar wording before. In fact so many people have asked questions, I often find I skip the Google search and go straight to Stack Overflow for an answer nowadays.
If you’ve yet to start your web development journey, Code Academy is as good a place to start as any.
Not Everyone or Everything on the Web is Right.
(Especially me)
Just because someone has written a blog on a subject and that blog is the number one result on Google, it doesn’t make what your reading correct. The author may just be really good at optimising their site for search engines (known as Seach Engine Optimisation or SEO).
For instance, there are lots of articles and tutorials online but it can easy to be mislead by one that is out of date. Check the date timestamp on the tutorial you are reading to check if it is using current best practices. If the tutorial doesn’t have a date, then its worth cross referencing the material against another article.
You can check comments on articles to see if others have left feedback saying something doesn’t work (people tend to be more vocal when something is broken) before you go ahead and implement it. Stack Overflow and MDN work well for getting the right answers. On Stack Overflow, the first or second answer will usually be the answer that you are looking for; and you can see how well received an answer is by the community by looking at the number of votes it has next to it. On MDN, the wiki nature of the documentation means that it can be kept up to date by anybody rather than relying on one particular person to make updates – meaning it is current most of the time.
This also goes for libraries and APIs. Just because a library exists and has a nice site, doesn’t mean the library is actually any good. Running a quick Google search for problems with the library takes minutes and can save hours of frustration.
Things Will Always Change.
The web is constantly evolving. It has to. It needs to keep up with all the new devices and the functionality that comes with those devices. Some browser vendors now release new versions of their software every 6 weeks and with that new release comes new features.
As an example of change, look at the devices people now use the browse the web. Increasingly people browse on their mobile phones or tablet. Just 3 years ago, the majority of people browsed the web on their computer. Not long before that, there was no such thing as a tablet! Who knows what will happen next.
Don’t ever expect to stop learning. There will always be something new to learn.
Know Your Tools.
In any career, you can do a better job if you know the tools you are working with. In web development as well as three separate languages, there are lots of tools to learn.
Pick a text editor which highlights HTML, CSS and JavaScript syntax for you and learn useful keyboard shortcuts so you have a smooth development experience.
Choose a browser that will be your primary browser for development and get accustomed to it’s Browser Developer Tools. The first thing to find out how to do in the Browser Developer Tools is to see a list of the files that have loaded on your page as an incorrect URL to something the page relies on can stop styles, scripts or images from loading. A 404 error means the file could not be found.
Finally, know the tools your user will visit your site in – download as many browsers as your machine allows – there’s Safari, Chrome, Opera, Firefox and Internet Explorer. Get used to checking your work in each of these to learn the quirks and differences between them. The developer tools in each of these browsers include similar functionality, so if you find something useful to debug in one browser, generally there will be a way to do it in the other browsers’ tools.
Experiment.
When children are learning they often go through a phase of trying things that they know are wrong in order to see what effect it has. They are experimenting, and if you are developing for the web – so should you. I could tell you to make sure you always close your brackets in CSS, but then you are getting second hand information. Try it yourself, see what happens. If you ever see the problem later on in your career (and you will) you will know exactly what to do and where to start looking in order to fix it.
Pick Apart Other People’s Code.
One of the best things about the web is that it is open. You can view the source of any page and see the HTML markup, CSS and JavaScript using the Browser Developer Tools. Do you like the rounded corners used on your mates’ blog? Right click on it and select “Inspect Element” in most browsers to see how they did it.
Open projects such as the HTML5 Boilerplate and read the comments to analyse why certain parts of code are included.
Start a Blog.
The best way to remember what you have learnt is to keep a log of your findings. Writing down what you have learnt will reinforce it in your head and may encourage you to think of “what if” situations. Since we live in a digital age, why not start a blog? This way, people are invited to read what you have learnt and contribute advice to help make you a better developer; and you can use your blog as a test bed for trying out your new coding skills!
For the web developers who are beginning their career, I hope that you have found this list useful and wish you the best of luck with your future webpages! For me, becoming a web developer was the best career choice I ever made.
I’m always looking for talking opportunities so if any schools, colleges or universities (particularly in the UK) would like me to come give a talk on this, please contact me.
If you are a web developer and have any further points to add to this list, feel free to leave a comment! If this post proves popular, I will likely write a follow up that focuses on tips for each of the languages.
2012 really felt like a progressive step forward for Responsive Web Design. As big corporate companies like Starbucks and Microsoft as well as governments began to introduce breakpoints in to their web pages to cater for the diverse range of devices now available on the market, it no longer felt like the technology was only for use for blogs and news sites. Responsive Design proved it was ready for mass consumption.
In parallel, using a responsive grid became popular as a convienent way of handling column configurations over breakpoints. From simple grids like the one used in Twitter Bootstrap to the SASS driven SUSY that allows you to keep semantic markup while managing columns over breakpoints; grids in a responsive design became popular.
Using these techniques, we could ensure that content was king and provide the optimal experience for our users regardless of how they were viewing our web page.
There Appears To Be a Problem.
But for all the possibilities media queries allow, there appears to be a problem with the current selection of available conditions. We’re often told that we should build for content first and not design, yet the most widely used media queries are built in completely the opposite way: min-width and max-width. These two media queries measure the width of the page – often this is useful but there are situations where this isn’t helpful, particularly on larger scale websites.
Suppose we were to create a small module on our page, for example a carousel, which sits across two columns of our three column grid. This module will be used across multiple pages and we are unsure how it will be configured over these pages.
In a responsive design, we may create two or more breakpoints for this module to ensure that items resize as the page gets smaller, such as reducing the size of the font. Our module is responsive. But the media queries that determine when these breakpoints occur are based on the page width not the container width, so this module is actually only responsive within the context of placing it within two columns.
If we use the same module on another page, but give it a different number of columns, then the breakpoints we created before may be rendered impractical (or worse). Let’s look at the same carousel module but sitting across three columns:
Because we’ve changed the size of the container, the breakpoints set for this search module are now sub-optimal for the configuration of columns. The things we reduced in size before now shrink too early, and we are left with a lot of extra space.
This is not such a big problem for three columns, it’s a bit small but we can usually get away with this. Let’s see what happens when we reduce the number of columns our module spans.
If we change our module container to span a single column the problem is much worse. Now the module container is too small, so the media queries we provided to shrink our content are inappropriate. Our page looks a mess.
There’s no point complaining about a problem without proposing a solution; and the solution in this case seems to be the argument for a new type of media query which can react to a container’s properties rather than the page properties. In the case of our example, this would be a media query that can react based on the width of a container defined by the user rather than the whole width of the page.
In an ideal world, perhaps we’d solve this problem in CSS like this:
But CSS doesn’t support nested queries like SASS and LESS does, so perhaps a more suitable solution to the problem would be to create new media queries conditions min-width-of and max-width-of (and the equivalent height conditions) like so:
Now when we resize the page, our content would be able to resize when the container meets the condition, rather the page.
Conclusion
For rich content web sites, responsive web design can be a complicated procedure; and as developers push responsive in to 2013 the problem is only going to get more complicated.
Grids can help reduce complexity, but we are still reliant on measuring page properties rather than the properties of the actual container that holds our content. Here’s hoping that in the future it becomes possible to create media queries based on containers so that we can allow greater flexibility on our web pages.
Appendix: Until Then
Not wanting to detract from the article above, I did want to share a solution that is possible in today’s browsers, although it isn’t particularly ‘nice’ and relies on JavaScript.
By using JavaScript to calculate and compare the container and page widths, we could apply a class to our container to determine how many columns it is currently occupying. This class would then drive the size of our content in the same way our media queries were in the above examples. Like I said, not a pretty solution – but a workaround until the bigger issue is resolved.
They say that a workman is only as good as his tools, and the same is true for a web developer. The more you know about the tools, the better you’ll get at performing the task at hand. There are now many tools that can speed up web development – from Browser Developer Tools to build scripts like Grunt; but the most important tool of all is the tool you write your code in – your code editor. For me, that’s Sublime Text 2 and there are a ton of keyboard shortcuts available to make life easier available.
So as my Christmas present to you, here are 2 cheatsheets (one for Mac, one for Windows) so you can learn and reference those shortcuts to improve yourself and your developer skills.
PC (click thumbnail to open):
MAC (click thumbnail to open):
A couple of months ago, I gave a PechaKucha talk about creating a 3D animated particles effect with the canvas element.
For those who’ve not come across the concept of a PechaKucha before, the idea is to present on a topic for 20 slides with 20 seconds per slide. The event I attended was slightly different with just 5 minutes to show those 20 slides (so 15 seconds a slide).
Whenever I talk to web developers I find that the canvas element still remains a mystery to most, so I wanted to do a short presentation that could introduce developers who had not used the canvas element before to the concepts and show how it’s not quite as scary as it seems.
It was my first PechaKucha, and during rehearsal I learnt that the format doesn’t lend itself too well to explaining how to implement lines and lines of code. I tried to balance out the slides so there wasn’t too much new information on each. The aim of the talk was less about teaching developers everything about canvas and more about showing how simple it can be to create an effect.
Below is a write up of the talk, and I’m going to purposefully keep it short (hopefully a 5 minute read) to allow you time to experiment. You can view the original presentation here, the slides move on every 15 seconds and the animated demos start themselves – each demo is deliberately self contained so you can dive in to the code. Please use, abuse and learn.
The 5 Minute 3D Effect
Quick note: this is a 3D effect in 2D, not a WebGL demo. The effect we are going for is a simple space effect with particles flying out of the center of the canvas element, it looks like the following:
The Canvas element
Allows us to place a 2D drawing canvas on our page
Interfaced with JavaScript
Default dimensions: 300 x 150
Works in IE9+
1
2
3
<canvasid="particles">
StoprunningIE6-8dude,it'snotcool!
</canvas>
The Canvas Context
The context is like an artists toolbox. We use it to:
Draw lines, rectangles and arcs
Set colours and styles
Fill shapes
Clear the canvas
Get/use image data
1
2
varcanvas=document.getElementById('particles'),
context=canvas.getContext('2d');
Set up our Drawing Area
We will create a function called draw() that will be called for each frame of our animation. This function will need to carry out a number of tasks:
Clear the canvas – as our canvas is a bitmap we cannot move items on it, so for each frame we have to redraw the canvas.
Translate our canvas so our point of origin (0, 0) is the center, not the top left.
We use save() and restore() to save/restore the state of the context (e.g. point of origin, colors). It does not save an image of the canvas.
1
2
3
4
5
6
7
8
9
10
functiondraw(){
context.clearRect(0,0,width,height);
context.save();
context.translate((width/2),(height/2));
// draw particles
context.restore();
}
Decide On a Amount of Particles
We need to decide how many particles we wish to show. Naturally in a presentation, the audience will always choose the highest number you offer (10,000) – but in real life consider number of particles vs. performance. Our particles will live in an array in JavaScript.
1
2
varAMOUNT=10000;
varparticles=[];
Create Those Particles!
Each particle is an object and for each particle we:
Make an object with x, y, z co-ordinates
Push it on to our particles array
1
2
3
4
5
6
7
8
9
10
11
12
13
functioncreate(){
vari=AMOUNT,
particle;
while(i--){
particle={
x:0,
y:0,
z:0
};
particles.push(particle);
}
}
Generate Random Numbers
At the moment all of our particles are sitting at the same co-ordinates (the center), so we need to give them some random coordinates, which means we need a simple function to generate random numbers. This function:
Gets the difference between max and min
Multiplies the difference by Math.random()
Adds min back to our value to ensure it’s within our range
1
2
3
functionrandomNumber(min,max){
return(Math.random()*(max-min))+min;
}
Create Random Particles!
Now we’ve done that, we adjust our particle creation loop for each particle to:
Set x to a random number based on half the width (remember our origin is the center)
Set y to a random number based on half the height
Set z to 0 (for the moment)
1
2
3
4
5
particle={
x:randomNumber(-(width/2),(width/2)),
y:randomNumber(-(height/2),(height/2)),
z:0
};
Draw Our Particles!
Now we have differing co-ordinates, we loop through our particles array and make each particle a circle using context.arc.
Here, we are choosing to color our particles white, during our arc and then filling it. I’ve added a nice semi-transparent effect to the color by specifying an alpha in our rgba color value. You can improve performance by only setting the colour once rather than for each particle.
Field of Vision
The z coordinate measures how close or far away our particle is from our view. If it gets too close, it will obscure our view so we want to simulate it going past us at some point. If it gets too far away, we are spending time rendering a particle that is practically invisible. So we use this value to tell our draw function when to draw the particle. It’s up to you which value you use, ~250 seems to work well.
1
2
3
4
5
6
varFIELDOFVISION=250;
particle={
x:randomNumber(-(width/2),(width/2)),
y:randomNumber(-(height/2),(height/2)),
z:randomNumber(-FIELDOFVISION,FIELDOFVISION)
};
Scaling Our Particles
Particles should be different sizes at different points on the z axis, so we use scale to position them and to change the radius of our circles.
1
2
3
4
scale=(FIELDOFVISION/(particle.z+FIELDOFVISION));
x=(particle.x*scale);
y=(particle.y*scale);
context.arc(x,y,scale,0,Math.PI*2,true);
Animation
Our particles are now pretty, scaled and scattered, but still static. We use requestAnimationFrame to draw when the browser reflows, for the best performance.
To make the particles move, for each frame we need to change the z co-ordinate.
1
SPEED=-4
Within our draw loop:
1
particle.z+=SPEED;
We also want to test for the field of vision and move our particles to the front or back when they are no longer in vision. This has the bonus of reducing the amount of array manipulation (we’re just editing values rather than splicing and splitting arrays) improving performance.
1
2
3
if(particle.z<-FIELDOFVISION){
particle.z=FIELDOFVISION;
}
Done!
And that’s it, we have particles that move! Simple, and nothing really to be scared of.
Last week, I spoke at AKQA Anoraks on Real Time Communications with WebRTC. I spoke about the WebRTC project and specification; and how we can output the webcam and microphone streams to the HTML5 video element and Web Audio API to create fun effects.
I received some great interest from the talk on the night, so thanks to everyone who came. The slides to my talk are available here. If you already follow my blog you may notice it was loosely based on a couple of blog posts I wrote last July; but updated to include the latest developments in the specification.
I’m interested in re-running this talk at meet ups and conferences near London, so if you are interested please get in contact!
Last week Adobe announced the launch of a new suite of tools for the web known as Edge. In conjunction with this release, they are touring four locations across the globe to discuss the future of the web, and the future of web tools. It was London’s turn this week, and I had the opportunity to take a training day at work and attend.
Overall it was a day packed with useful information and insight in to where Adobe is headed with their contributions to the web and the tools they are creating. I had already been aware of the Edge set of tools from the announcement last week but had been hesitant over whether Animate and Reflow would produce poor source code in the same way Dreamweaver had years ago. However, seeing them demoed today gave me new hope that Adobe are on to something great. These tools seem to be heading in the right direction, providing more useful ways to create web content.
Features such as the inline editing mode shown in Brackets filled me with a real sense of enthusiasm for what Adobe are trying to acheive, showing that their team really are thinking about the problems and challenges with current web development and how we can solve them. Animate and Reflow’s user interfaces are incredibly well thought out; and it appears they are at least trying to ensure the final code output is as optimal as can be expected for a visual editor. Even if the code these tools produce does turn out that they can not be used for production code (without trying them it’s too early to say either way), they would still work well for creating UE and animation prototypes.
One concern – everything shown today did seem to be Chrome/Webkit focused. Edge Inspect used a Chrome plugin; all the demos used Chrome; I could only see Webkit prefixes in editor code examples; Adobe’s patches are for Webkit… I hope Adobe are helping to make sure we can also use these tools with other browsers. It would be great to hear that they are working with other browser vendors; otherwise it feels like we are just dividing the web all over again.
My notes on the event are below, I really encourage you to check out the tools.
For the last few months I have been co-organising evening meet-ups in London known as AKQA Anoraks. These meetups are primarily aimed at techies who work for digital agencies, but much of the content is useful for any web developers or software engineers.
The latest of these meetups occurs this Thursday 27th September at 6.30pm at AKQA London and covers the following subjects:
Unit Testing JavaScript
Adventures in NodeJS
and Making an Integration Sandwich When You’ve Run Out of Bread
In previous months we have had talks on a wide range of subjects from Responsive Design to Web Sockets; and Continuous Delivery to Regression Tests; and have gathered some very positive feedback. And back in July I gave a talk on “Layouts of the Future” where I covered CSS Columns; CSS Regions; CSS Exclusions; Flexbox; CSS Box Alignment and CSS Grids.
If you are interested in coming to our meetups, live in or around London and are free this Thursday you can pick up a free ticket on Eventbrite. Alternatively, come check us out on the last Thursday of any month. We are also always looking for new speakers so if you are interested, please drop me a line.
It’s been a while since my last blog post, but I’ve actually been working on a number of exciting things in the last couple of months, so I’m going to take this opportunity to write about one of them – video/audio capture.
For a long time in the “Flash vs HTML5″ comparison arguments, one advantage Flash had was the ability to capture audio and video from the users computer. With upcoming browser releases, it is now possible to do this with JavaScript and the HTML5 video element, and its very simple to do. Unfortunately, audio doesn’t work through the <audio> element at the time of writing, but video does – so let’s use that!