• Shortcuts : 'n' next unread feed - 'p' previous unread feed • Styles : 1 2

» Publishers, Monetize your RSS feeds with FeedShow:  More infos  (Show/Hide Ads)


Date: Wednesday, 30 Jul 2014 01:25

Read the full article at: Abusing console.log to Remove Debug Code

Treehouse
Wufoo

One of the big efforts of this blog is to make it as fast and compact as possible. I shave bytes and do everything I can to make the site as lightning fast as possible. I even remove ” /” from IMG, LINK, and META tags to save those few bytes, just to be as slim as can be. In looking at my site’s main JavaScript file, I saw a few blocks which have no value on production, even after minification. After some basic experimentation, I realized that we can abuse console.log statements, which are removed by minifiers, to execute functions on development servers but not on production!

The JavaScript

The traditional call to console.log is one or several strings, but you can pass a self-executing function if you want:

console.log((function() {
  // Do whatever...

  // Example for local dev: convert live links to local

})());

The console.log method really doesn’t do much here, but we get the added benefit of not only function execution but removal during uglify runs.

Using console.x methods is a big help during development, and it’s awesome that we can bastardize a minifier to work during both development and productions!

Author: "David Walsh" Tags: "JavaScript, Quick Tips"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 29 Jul 2014 14:37

Read the full article at: Popular Tools and Resources That a Web Designer Should Use (Sponsored)

Treehouse
Wufoo

Just as every client project is unique, each designer is different by nature, and has distinct tastes, skills, style and experience. Yet, web/graphic designers always like to think they’ve made the best decisions and signed the most handsome deals when it comes to resources and tools, which are indispensable to their work. While fully aware that opinions on these matters may differ, I would like to share some of the most useful resources and tools in terms of website builders, WordPress themes, hosting providers, design deals, font and vector resources, stock photos, icons, project management tools, PSD to HTML services, and E-commerce solutions.

Website Builders

ALLYOU

A good website builder has the power to transform your work by allowing you to channel your creativity without dealing with the irksome task of coding. ALLYOU.net is all about professionally crafted showcase websites that require minimum effort to set up. The Swiss platform was originally created in 2011 to serve the needs of creative individuals from various fields of experience. Graphic designers, as well as photographers, or stylists, can make fabulous portfolios with the utmost simplicity.

As long as you’re not fixed on ending up with a sophisticated interface, feel free to single out a template and then use the drag-and-drop front end editor to customize it and piece your website together. ALLYOU does not charge a single dime for its services, not even for cloud hosting. However, it’s possible to further upgrade the portfolio site starting from $8/month, by opting for the Carbon or the Titanium pricing plan.

Wix

Wix is rounding up more and more users every day. I’m not surprised, since it’s a handy cloud-based tool that helps people deliver clean-cut HTML 5 websites without writing a single line of code. Besides, it offers a multitude of apps or allows you to add them to your site from a third party source, and add functionalities like E-commerce, social plug-ins, contact forms, community forums, and e-mail marketing.

Moonfruit

Admittedly, it takes a little while to get the hang of this website builder, but once you’ve crossed that bridge, nothing is holding you back from creating beautiful websites for your clients. You may even notice that Moonfruit presents several advantages that are hard to come by with other online tools, such as well designed site templates to choose from, and effective SEO calibrating on the platter.

WordPress themes

X Theme

Versatility is the operative word when you’re creating WordPress websites. You may be asked to build an online store, a blog, a business website, a portfolio, a photography website, an event website, and so on, and so forth. Considering the supersaturated theme market out there, I believe that X Theme is one of a kind.

The magnificent brainchild from ThemeForest has got you covered on any occasion, so this may well be the only WordPress theme you’ll ever need. The so-called ‘Stacks’ make sure of that. With any other theme, you’d be confined to choosing a skin and then customizing its appearance. The X Theme comes with four unique designs in one package, and allows you to easily edit your site in a live previewer.

Template Monster

Template Monster is a giant library of site templates where you’re bound to find anything you could possibly wish for. Well over 20.000 items are vying for your attention. You can browse through them and take your pick, depending on the format you prefer: HTML format, CSS with flash, or PSD.  If your services are solicited by small or medium-sized companies, you can use Template Monster to provide them with fully supported and hosted turnkey websites.

Another interesting fact about this service is the way you go about acquiring templates. You can either opt for a limited use license, or purchase a unique license to keep anyone else from using a specific template – whichever route suits your needs best.

CrocoBlock

There’s one more collection of themes for WordPress sites that I absolutely have to mention here. A team of dedicated theme developers work hard to contribute to a superb database that presently holds more than 80 responsive specimens. The CrocoBlock Club has a helpful support team, and is counting on Cherry Framework to power all of its offerings.

If you try out some of their themes, you’ll see that they’re ready to go right after you’ve installed them, and besides, the admin panel is very easy to navigate. Apart from that, advanced options are at placed your disposal whenever you’re working on a portfolio or a blog. You’d also get constant upgrades, a built-in SEO tool, customized widgets, and an integrated plugin with shortcodes.

Hosting

HeartInternet

Your job also requires that you sometimes ensure trustworthy web hosting for websites, emails and applications. HeartInternet is a viable solution, regardless of the magnitude of your client’s business. Moreover, it’s good to know that help is always just within reach and that they don’t outsource – the support team being entirely based in U.K.

Pixeno

UK based Pixeno offers a top notch reseller hosting service for web designers and developers. You can request a 30 day free trial to test drive the service (no credit card required). Their reseller hosting platform is scalable, meaning that it can be adjusted as the consumer grows. Moreover, Pixeno provides WHM (web host manager) for all resellers who can then add websites to their package, each with their own cPanel account. Lastly, their planning to launch a new U.S location in the upcoming weeks. Use coupon code DESIGN15 and get 15% off their awesome service.

Design deals

Mighty Deals

It can’t hurt to be on the lookout for practical designer bargains that may be waiting around the corner. Who knows, you might just come across useful resources that would otherwise cost tremendous amounts of money. Mighty Deals  is the perfect venue for frequent discounts.

Take a minute to subscribe to their newsletter and take advantage of special offers while they stand. The discounts titan has daily discounts of 50-90%  for web development lessons, Mac toolkits, professional templates, and design tools like Photoshop actions or royalty-free vectors, but they are only available for a very short period of time. Besides, you can rest assured that this service is altogether free, so you don’t have to register or pay any fees.

Medialoot

Of course, not all design deal services on the market are free of charge. However, that doesn’t mean that they’re not worthy of your attention. Case in point, a Medialoot membership may cost you $14 per month or $99 for the entire year, but keep in mind that there is much you stand to gain.

Members get unlimited access to top class resources, which are altogether created by Medialoot designers and hence carry a solid quality guarantee. You can expect to get your hands on many types of treats, including web and UI kits, mobile-specific design kits, vector and illustration kits, individual icon sets, countless font families, and hundreds of Photoshop add-ons.

Font resources

UrbanFonts

Images and graphics aside, we all know how important it is to also display content in a proper manner. The headings and body text used in a website, for instance, have to be attractive and hold everyone’s attention. Therefore, it’s crucial that you seek and use the appropriate fonts for the project at hand. UrbanFonts has one of the best collections on the web. Just take your pick from over 8k free fonts, as well as loads of premium fonts, and dingbats.

WhatFontIs

At times, you may happen to see an image that contains a word written in pleasant typography, and you don’t have a clue what font that is, so you get the sudden urge to try and find out. There’s no telling how long the web search turns out to be. WhatFontIs.com exists just for that type of emergencies. This is an excellent tool for designers, who work against deadlines and don’t have anytime to waste.

You won’t believe how fast you’d get that elusive font, either by entering the URL with the location of that image, or by taking a screenshot, and uploading it onto the platform. Soon enough, you’d receive a list with the exact or closest matches to that font.

Vector resources

Shutterstock

When you’re scouting for the best microstock agencies to get vectors from, remember to visit Shutterstock. It’s one of my top options, and it’s been a favorite for years. This marketplace is very popular, and makes it a habit of favoring brand new items, so contributors are encouraged to create and keep adding new vectors on the website.  

Vector Open Stock

If you don’t want to spend any money, than there’s always time to scan through websites that offer high quality free vector graphics. You may wish to consider Vector Open Stock above all others, as it has almost 7k precious freebies on its shelves, just waiting to be snatched. While some items are subject to Creative Commons license, others are under an Open Stock License.

In addition, Vector Open Stock also sports some sort of a Social Network. As such, you will find useful features here, which you can use to browse collections, as well as like other people’s works, follow them, and voice your opinion.

Stock images

Unsplash

Creative professionals are often forced to sort through rubbish until they find the perfect images to work with. Unsplash is an example of stock photo merchant that has top notch content, which is really worth your while. Not to mention, ten new photos are added once every ten days, and they are all associated with CC0 license, so you can use them freely.

PicJumbo

I have only just discovered the small treasure called PicJumbo. Its owner keeps uploading incredibly neat looking photographs of 10 megapixels that look like anything but stock photos. In fact, most of them are made available for free, and can be used in the making of templates, themes, and websites, as long as you’re not selling them.  You can also go Premium for $6/month and receive a monthly intake of beautiful images.

Project management

Azendoo

Without proper organizing skills, teamwork would turn to chaos. Project management is particularly important in web design, so reaching out to helpful software is highly recommended. My favorite tool is Azendoo, which is available on the web and on mobile. The free version allows you to create an endless number of workspaces, as well as set tasks and subjects indefinitely. With Premium comes advanced admin capabilities and increased storage.

Azendoo is complete with integrations like Dropbox, Evernote, Google Drive, and Box. Thus, you are at liberty to link accounts, and share all work in one place, so that you and your team-mates are in sync.

Casual

We’re not project managers, we’re designers. In case you feel that most project management software out there is cumbersome, and the vast majority of designers get that feeling sooner or later, then I know what can deliver you. If you’re looking for something more visual and generally uncomplicated, your salvation lies in a handy tool called Casual.

You’ll be happy to notice that Casual doesn’t overwhelm you with heavy Gantt charts or other managerial features that come across as unfriendly to designers. Instead, you can draw a MindMap of your tasks, plan easily, and have absolute control over your projects from beginning to end.

Icons

Picons.me

Next time you’re interested in acquiring icons, check out Picons.me – that’s where you’ll find some crisp and hand-crafted items that will stick to your memory for a very long time, and compliment your website, offline media, desktop or mobile app. The icon sets are vectorized, created with Illustrator, and can be scaled to any size.

An 80-strong set is at your service, cost-free: the Social bundle contains icons pertaining to the most popular networks. Lastly, be sure to follow Picons.me on Twitter, seeing as they announce promotions from time to time.

Roundicons

Roundicons commands the largest collection I’ve seen so far. No less than 5K icons are stacked in the vaults and organized in sets. Here are icons that fit every style, taste, and format, from flat colorful elements, to flat scenes, lines, outlines, and filled icons. They are available either as PSD, AI, SVG, PNG, or CSH.

I love the fact that all icons from this source have Extended License. What’s more, once you’ve purchased an icon set, all the items that appear thenceforth and belong to that set are automatically sent to you, without any extra fees.

PSD to HTML services

Direct Basing

When you’ve designed a PSD and don’t wish to mess around with coding in order to launch it in the online world, it’s time to enlist a PSD to HTML service. Direct Basing should be among your first choices, because they have one of the fastest turnarounds in the industry.When needed it’s also possible to let them implement one of your favourite CMS systems such as: WordPress, Joomla or Magento eCommerce.

Furthermore, when you place your order, you’re also invited to choose several layout and JavaScript features. The (x)HTML/CSS code written by the expert team from Direct Basing will optimize your website for search engines, and make it function well on all browsers, old or new.

XHTMLized

Yet another first-rate PSD to HTML service is XHTMLized. It takes pride in having a staggering experience: with 10 years of dedicated service as back-end developers, top quality is in their DNA. The moment you ask for their help, you sign a non-disclosure agreement that protects your data and your property. The only people who come in contact with your designs will be on first name basis with you, because XHTMLized believes that a healthy relationship with the clients is essential. Moreover, the Project Producer assigned to you can be reached at any moment, should you raise any questions or have anything at all to add.

E-commerce solutions

Shopify

As far as online stores are concerned, Shopify is the perfect answer for retailers and for designers who would rather sidestep technicalities altogether. This tools allows you to easily customize the site design, manage orders, add new products, and accept credit cards. Heavy faces like Encyclopaedia Britannica or Amnesty International work with Shopify, so what’s holding you back?

WooCommerce

If you’re currently engaged in the sphere of WordPress websites and need an E-commerce plugin, WooCoomerce is your best bet. You can use it entirely free of charge, and so create stores that sell anything from software, to clothing, photos, music, and even products that originate from an affiliate marketplace.  

This list could go on for ever, but I’ve only singled out the tools and resources that I believe would make the biggest difference in the life of a graphic/web designer. Naturally, I don’t expect everyone to agree with me on the best options, and I wholeheartedly welcome other opinions.

Author: "David Walsh" Tags: "Sponsored"
Comments Send by mail Print  Save  Delicious 
Date: Sunday, 27 Jul 2014 19:15

Read the full article at: Diving Deeper With ES6 Generators

Treehouse
Wufoo

ES6 Generators: Complete Series

  1. The Basics Of ES6 Generators
  2. Diving Deeper With ES6 Generators
  3. Going Async With ES6 Generators (Coming soon)
  4. Getting Concurrent With ES6 Generators (Coming soon)

If you’re still unfamiliar with ES6 generators, first go read and play around with the code in “Part 1: The Basics Of ES6 Generators”. Once you think you’ve got the basics down, now we can dive into some of the deeper details.

Error Handling

One of the most powerful parts of the ES6 generators design is that the semantics of the code inside a generator are synchronous, even if the external iteration control proceeds asynchronously.

That’s a fancy/complicated way of saying that you can use simple error handling techniques that you’re probably very familiar with — namely the try..catch mechanism.

For example:

function *foo() {
    try {
        var x = yield 3;
        console.log( "x: " + x ); // may never get here!
    }
    catch (err) {
        console.log( "Error: " + err );
    }
}

Even though the function will pause at the yield 3 expression, and may remain paused an arbitrary amount of time, if an error gets sent back to the generator, that try..catch will catch it! Try doing that with normal async capabilities like callbacks. :)

But, how exactly would an error get sent back into this generator?

var it = foo();

var res = it.next(); // { value:3, done:false }

// instead of resuming normally with another `next(..)` call,
// let's throw a wrench (an error) into the gears:
it.throw( "Oops!" ); // Error: Oops!

Here, you can see we use another method on the iterator — throw(..) — which “throws” an error into the generator as if it had occurred at the exact point where the generator is currently yield-paused. The try..catch catches that error just like you’d expect!

Note: If you throw(..) an error into a generator, but no try..catch catches it, the error will (just like normal) propagate right back out (and if not caught eventually end up as an unhandled rejection). So:

function *foo() { }

var it = foo();
try {
    it.throw( "Oops!" );
}
catch (err) {
    console.log( "Error: " + err ); // Error: Oops!
}

Obviously, the reverse direction of error handling also works:

function *foo() {
    var x = yield 3;
    var y = x.toUpperCase(); // could be a TypeError error!
    yield y;
}

var it = foo();

it.next(); // { value:3, done:false }

try {
    it.next( 42 ); // `42` won't have `toUpperCase()`
}
catch (err) {
    console.log( err ); // TypeError (from `toUpperCase()` call)
}

Delegating Generators

Another thing you may find yourself wanting to do is call another generator from inside of your generator function. I don’t just mean instantiating a generator in the normal way, but actually delegating your own iteration control to that other generator. To do so, we use a variation of the yield keyword: yield * (“yield star”).

Example:

function *foo() {
    yield 3;
    yield 4;
}

function *bar() {
    yield 1;
    yield 2;
    yield *foo(); // `yield *` delegates iteration control to `foo()`
    yield 5;
}

for (var v of bar()) {
    console.log( v );
}
// 1 2 3 4 5

Just as explained in part 1 (where I used function *foo() { } instead of function* foo() { }), I also use yield *foo() here instead of yield *foo() as many other articles/docs do. I think this is more accurate/clear to illustrate what’s going on.

Let’s break down how this works. The yield 1 and yield 2 send their values directly out to the for..of loop’s (hidden) calls of next(), as we already understand and expect.

But then yield* is encountered, and you’ll notice that we’re yielding to another generator by actually instantiating it (foo()). So we’re basically yielding/delegating to another generator’s iterator — probably the most accurate way to think about it.

Once yield* has delegated (temporarily) from *bar() to *foo(), now the for..of loop’s next() calls are actually controlling foo(), thus the yield 3 and yield 4 send their values all the way back out to the for..of loop.

Once *foo() is finished, control returns back to the original generator, which finally calls the yield 5.

For simplicity, this example only yields values out. But of course, if you don’t use a for..of loop, but just manually call the iterator’s next(..) and pass in messages, those messages will pass through the yield* delegation in the same expected manner:

function *foo() {
    var z = yield 3;
    var w = yield 4;
    console.log( "z: " + z + ", w: " + w );
}

function *bar() {
    var x = yield 1;
    var y = yield 2;
    yield *foo(); // `yield*` delegates iteration control to `foo()`
    var v = yield 5;
    console.log( "x: " + x + ", y: " + y + ", v: " + v );
}

var it = bar();

it.next();      // { value:1, done:false }
it.next( "X" ); // { value:2, done:false }
it.next( "Y" ); // { value:3, done:false }
it.next( "Z" ); // { value:4, done:false }
it.next( "W" ); // { value:5, done:false }
// z: Z, w: W

it.next( "V" ); // { value:undefined, done:true }
// x: X, y: Y, v: V

Though we only showed one level of delegation here, there’s no reason why *foo() couldn’t yield* delegate to another generator iterator, and that to another, and so on.

Another “trick” that yield* can do is receive a returned value from the delegated generator.

function *foo() {
    yield 2;
    yield 3;
    return "foo"; // return value back to `yield*` expression
}

function *bar() {
    yield 1;
    var v = yield *foo();
    console.log( "v: " + v );
    yield 4;
}

var it = bar();

it.next(); // { value:1, done:false }
it.next(); // { value:2, done:false }
it.next(); // { value:3, done:false }
it.next(); // "v: foo"   { value:4, done:false }
it.next(); // { value:undefined, done:true }

As you can see, yield *foo() was delegating iteration control (the next() calls) until it completed, then once it did, any return value from foo() (in this case, the string value "foo") is set as the result value of the yield* expression, to then be assigned to the local variable v.

That’s an interesting distinction between yield and yield*: with yield expressions, the result is whatever is sent in with the subsequent next(..), but with the yield* expression, it receives its result only from the delegated generator’s return value (since next(..) sent values pass through the delegation transparently).

You can also do error handling (see above) in both directions across a yield* delegation:

function* foo() {
    try {
        yield 2;
    }
    catch (err) {
        console.log( "foo caught: " + err );
    }

    // now, throw another error
    throw "Oops!";
}

function *bar() {
    yield 1;
    try {
        yield *foo();
    }
    catch (err) {
        console.log( "bar caught: " + err );
    }
}

var it = bar();

it.next(); // { value:1, done:false }
it.next(); // { value:2, done:false }

it.throw( "Uh oh!" ); // will be caught inside `foo()`
// foo caught: Uh oh!

it.next(); // { value:undefined, done:true }  --> No error here!
// bar caught: Oops!

As you can see, the throw("Uh oh!") throws the error through the yield* delegation to the try..catch inside of *foo(). Likewise, the throw "Oops!" inside of foo() throws back out to *bar(), which then catches that error with another try..catch. Had we not caught either of them, the errors would have continued to propagate out as you’d normally expect.

Summary

Generators have synchronous execution semantics, which means you can use the try..catch error handling mechanism across a yield statement. The generator iterator also has a throw(..) method to throw an error into the generator at its paused position, which can of course also be caught by a try..catch inside the generator.

yield* allows you to delegate the iteration control from the current generator to another one. The result is that yield* acts as a pass-through in both directions, both for messages as well as errors.

But, one fundamental question remains unanswered so far: how do generators help us with async code patterns? Everything we’ve seen so far in these two articles is synchronous iteration of generator functions.

The key will be to construct a mechanism where the generator pauses to start an async task, and then resumes (via its iterator’s next() call) at the end of the async task. We will explore various ways of going about creating such asynchronicity-control with generators in the next article. Stay tuned!

Author: "Kyle Simpson" Tags: "Guest Blogger, JavaScript"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 24 Jul 2014 16:11

Read the full article at: Array: Insert an Item at a Specific Index with JavaScript

Treehouse
Wufoo

There are many tasks related to arrays that sound quite simple but (1) aren’t and (2) aren’t required of a developer very often. I was encountered with one such task recently: inserting an item into an existing array at a specific index. Sounds easy and common enough but it took some research to figure it out.

// The original array
var array = ["one", "two", "four"];
// splice(position, numberOfItemsToRemove, item)
array.splice(2, 0, "three");

array;  // ["one", "two", "three", "four"]

If you aren’t adverse to extending natives in JavaScript, you could add this method to the Array prototype:

Array.prototype.insert = function (index, item) {
  this.splice(index, 0, item);
};

I’ve tinkered around quite a bit with arrays, as you may have noticed:

Arrays are super useful — JavaScript just makes some tasks a bit more … code-heavy than they need to be. Keep these snippets in your toolbox for the future!

Author: "David Walsh" Tags: "JavaScript, Quick Tips"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 23 Jul 2014 03:16

Read the full article at: Velocity New York: Ticket Giveaway

Treehouse
Wufoo

Velocity Conference

A few months back, O’Reilly gave me two free tickets to give away  for Velocity Conference in Santa Clara.  The chosen two reported back to me that the conference was incredible, as did a Mozilla colleague that quickly came back and implemented a bunch of speed updates for the Mozilla Marketplace.   Well, you’re all in luck – O’Reilly has given me four (!) tickets to give away over the weeks leading up to the next Velocity Conference in New York from September 15–17.

You know the deal — I can’t just, you know, give you a ticket for a lame comment.  In the interest of teaching something through this giveaway, I’d like you to post a link to an article you’ve read recently that taught you something brilliant for the front end.  CSS, JavaScript, HTML5, WebGL, Canvas, whatever — share a link to an article that others will learn from.

If you don’t want to risk not winning and simply want to save some cash on the conference, click here and use promo code AFF20.  Good luck!

As always, remember to provide a real email address in case you’re the lucky winner.

Author: "David Walsh" Tags: "Giveaways"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 22 Jul 2014 14:00

Read the full article at: From Webcam to Animated GIF: the Secret Behind chat.meatspac.es!

Treehouse
Wufoo

My team mate Edna Piranha is not only an awesome hacker; she’s also a fantastic philosopher! Communication and online interactions is a subject that has kept her mind busy for a long time, and it has also resulted in a bunch of interesting experimental projects that have fostered an unexpected community and tons of spontaneous collaboration, plus have helped unearth a browser bug or two!

We could spend hours just going through her list of projects and getting amazed by all the ways in which she’s approaching the same aspect (human interaction) from different angles, both philosophical and technical, but this isn’t Edna Piranha’s Fan Club Blog, and David only asked me to write about Animated GIFs in the widely successful Meatspace Chat, so let’s focus on that.

It all started about a year ago. Edna had just built a decentralised microblogging engine with Redis, and was trying to find a use case for a database she had just heard about, called LevelDB.

She showed me a real time chat app she had hacked in a couple of hours, using LevelDB as the temporary, ephemeral storage. Anyone could sign in using Persona, and start sending messages to the one chat room. The avatar associated to your Persona account would be shown along with the message you sent, and messages would be deleted after a few minutes.

By that time I had been working on rtcamera, a camera app that could generate animated GIFs using your webcam as input, and somehow our thought trails converged: wouldn’t it be super cool to use the webcam’s input instead of an static avatar?

It was easy to implement this using the two libraries that I had extracted out from rtcamera: gumHelper and Animated_GIF, and the rest is history!

But for those of you who don’t know about history: we kept the chat in private for a while because Edna was going to present it at RealtimeConf. And then… it just exploded! People started coming to the site in flocks and being both puzzled by the unexpected cheerness and the general Back to the True Web raw and honest spirit: no sign up forms, no name to fill in, no identity to build and maintain; just a text input and your face to show the world what you were up to in that very moment. If you haven’t been to Meatspaces Chat yet, I recommend you go there now to familiarise yourself with how it looks and works before I get into technical details. You can also watch Edna‘s keynote at jQuery Con San Diego, where she talks about all this.

To the juicy technical details!

Are you all intrigued now? Cool!

But before we start deep diving into the code, let me add a little warning: Meatspaces chat is constantly being improved by the amazing community, so I will be referring to lines using a specific commit hash too. If you go directly to the project page and access the master branch, both the code and line numbers might differ from what this article says.

And we are really ready to go!

Accessing the camera

Everything starts with requesting access to the user’s camera. We are using the gumHelper library for this. No, it has nothing to do with dental hygiene; it actually means “getUserMediaHelper”, where getUserMedia is the part of the WebRTC API that allows us to obtain a live media stream containing live audio or video which we can then use in our websites. In this case we’re only interested in video, as GIFs are (sadly) silent.

If you’re running this on a laptop or a desktop–i.e. a full blown computer– we’ll access the webcam. If you’re running this on a phone, it will not only ask you for permission to use the camera, but also show you a drop down so you can select which camera to use, if applicable (some devices only have a back camera).

We’ll attempt to start streaming by calling gumHelper.startVideoStreaming:

gumHelper.startVideoStreaming(function (err, stream, videoElement, videoWidth, videoHeight) {
    // ...
}, { /* options */ });

startVideoStreaming takes a callback and an optional options object as parameters. In fairly standard node.js style, the callback function first parameter is err, which we check first. If it is truthy, we just give up on accessing the video. In earlier versions of the site, your messages would be accompanied by a giant meat cube avatar if video wasn’t enabled for whatever the reason, but it was changed to disallow sending messages to prevent trolls from posting.

Supposing the stream was successfully started, the next step is to use the videoElement returned by gumHelper. This is just a plain HTML5 <video> element that we will place in the page to serve as preview, so the user can ensure they are in the frame when they press ENTER.

Capturing frames

The other thing we’re doing is creating a VideoShooter instance. This is a little class that attaches to an existing video element and will start generating a GIF whenever we press ENTER, using frames from that video element:

videoShooter = new VideoShooter(videoElement, gifWidth, gifHeight, videoWidth, videoHeight, cropDimens);

The function to get a video capture is VideoShooter.getShot, which accepts a few parameters: callback (called to return the encoded GIF), numFrames (to specify how many frames to capture), interval (for setting the interval between capturing frames) and progressCallback (which is used to show a sort of progress indicator overlay over the video preview).

Internally, what getShot does is creating an instance of Animated_GIF and then periodically tells it to capture a frame as many times as requested, using Animated_GIF’s addFrame method.

How often the frames are captured (and therefore how smooth the animation will be) depends on the interval parameter. The more frames and the more frequently they are captured, the better and less jerky the GIF will look, but it will also be bigger. We played a bit with the parameters and decided to settle on two second GIFs (10 frames shot every 0.2 seconds make 2 seconds). Hence the “lemma” of the site: “your two seconds of fame”.

Animating the GIF

Each time we add a frame to the Animated_GIF instance, we pass videoElement as source parameter. It is then copied into an internal canvas to extract the image data and store it on a list of frames, taking advantage of the drawImage function that allows you to render HTML elements into CanvasRenderingContext2D objects.

Once the ten frames have been captured, the VideoShooter instance will call the getBase64GIF method from Animated_GIF.

This part is probably the most involved of all in the whole process, since we are ultimately generating binary data in JavaScript. Fortunately, it is all abstracted enough that we only need to call the method and wait for it to be generated on the background using Web Workers.

We use Web Workers because rendering is quite an intensive process and can easily block the main thread, making the whole app unresponsive–that’s something we don’t want to happen!

The callback function is invoked and sent the rendered GIF when it’s ready. Since it is a Base64 string we can just include it without further processing on the submission object that is then posted to the server.

And that’s how your funny faces get captured and travel down the wire to people all over the world. Or almost!

GIFWall

I thought that maybe perusing the entire codebase of Meatspaces Chat would be a bit too much if you’re only interested in the GIF side of things, so I build this little demo app that periodically captures GIFs using your webcam and adds them to the page.

It also uses gumHelper, Animated_GIF and a simplified version of the VideoShooter module.

To demonstrate how easy it is to capture data from the webcam and turn it into a GIF with the right libraries to abstract the tedium, here is the main code from GIFwall:

var main = document.querySelector('main');
var mosaicContainer = document.getElementById('mosaic');
var videoWidth= 0, videoHeight = 0;
var videoElement;
var shooter;
var imagesPerRow = 5;
var maxImages = 20;

window.addEventListener('resize', onResize);

GumHelper.startVideoStreaming(function(error, stream, videoEl, width, height) {
    if(error) {
        alert('Cannot open the camera. Sad times: ' + error.message);
        return;
    }

    videoElement = videoEl;
    videoElement.width = width / 4;
    videoElement.height = height / 4;
    videoWidth = width;
    videoHeight = height;

    main.appendChild(videoElement);

    shooter = new VideoShooter(videoElement);

    onResize();

    startCapturing();

});

function startCapturing() {

    shooter.getShot(onFrameCaptured, 10, 0.2, function onProgress(progress) {
        // Not doing anything in the callback,
        // but you could animate a progress bar or similar using the `progress` value
    });

}

function onFrameCaptured(pictureData) {
    var img = document.createElement('img');
    img.src = pictureData;

    var imageSize = getImageSize();

    img.style.width = imageSize[0] + 'px';
    img.style.height = imageSize[1] + 'px';

    mosaicContainer.insertBefore(img, mosaicContainer.firstChild);

    if(mosaicContainer.childElementCount > maxImages) {
        mosaicContainer.removeChild(mosaicContainer.lastChild); 
    }

    setTimeout(startCapturing, 10);
}

function getImageSize() {
    var windowWidth = window.innerWidth;
    var imageWidth = Math.round(windowWidth / imagesPerRow);
    var imageHeight = (imageWidth / videoWidth) * videoHeight;

    return [ imageWidth, imageHeight ];
}

function onResize(e) {

    // Don't do anything until we have a video element from which to derive sizes
    if(!videoElement) {
        return;
    }

    var imageSize = getImageSize();
    var imageWidth = imageSize[0] + 'px';
    var imageHeight = imageSize[1] + 'px';

    for(var i = 0; i < mosaicContainer.childElementCount; i++) {
        var img = mosaicContainer.children[i];
        img.style.width = imageWidth;
        img.style.height = imageHeight;
    }

    videoElement.style.width = imageWidth;
    videoElement.style.height = imageHeight;

}

This is essentially Meatspace Chat, but without chatting and without sending the data to other connected people. Some homework for the reader could be to show a progress bar or other fancy similar effect while GIFs are being encoded, or even improve this so that the captured GIFs are actually sent to other users via real peer to peer connections over WebRTC.

There are so many things you can do on the web nowadays! Isn’t that exciting? Now go get the sources, play with the code and have fun, and don’t forget to share your work so we can all learn and have fun too! :-)

Author: "Soledad Penadés" Tags: "Demos, Features, Guest Blogger, HTML5, J..."
Comments Send by mail Print  Save  Delicious 
Date: Monday, 21 Jul 2014 21:03

Read the full article at: The Basics Of ES6 Generators

Treehouse
Wufoo

ES6 Generators: Complete Series

  1. The Basics Of ES6 Generators
  2. Diving Deeper With ES6 Generators
  3. Going Async With ES6 Generators (Coming soon)
  4. Getting Concurrent With ES6 Generators (Coming soon)

One of the most exciting new features coming in JavaScript ES6 is a new breed of function, called a generator. The name is a little strange, but the behavior may seem a lot stranger at first glance. This article aims to explain the basics of how they work, and build you up to understanding why they are so powerful for the future of JS.

Run-To-Completion

The first thing to observe as we talk about generators is how they differ from normal functions with respect to the “run to completion” expectation.

Whether you realized it or not, you’ve always been able to assume something fairly fundamental about your functions: once the function starts running, it will always run to completion before any other JS code can run.

Example:

setTimeout(function(){
    console.log("Hello World");
},1);

function foo() {
    // NOTE: don't ever do crazy long-running loops like this
    for (var i=0; i<=1E10; i++) {
        console.log(i);
    }
}

foo();
// 0..1E10
// "Hello World"

Here, the for loop will take a fairly long time to complete, well more than one millisecond, but our timer callback with the console.log(..) statement cannot interrupt the foo() function while it’s running, so it gets stuck at the back of the line (on the event-loop) and it patiently waits its turn.

What if foo() could be interrupted, though? Wouldn’t that cause havoc in our programs?

That’s exactly the nightmares challenges of multi-threaded programming, but we are quite fortunate in JavaScript land to not have to worry about such things, because JS is always single-threaded (only one command/function executing at any given time).

Note: Web Workers are a mechanism where you can spin up a whole separate thread for a part of a JS program to run in, totally in parallel to your main JS program thread. The reason this doesn’t introduce multi-threaded complications into our programs is that the two threads can only communicate with each other through normal async events, which always abide by the event-loop one-at-a-time behavior required by run-to-completion.

Run..Stop..Run

With ES6 generators, we have a different kind of function, which may be paused in the middle, one to many times, and resumed later, allowing other code to run during these paused periods.

If you’ve ever read anything about concurrency or threaded programming, you may have seen the term “cooperative”, which basically indicates that a process (in our case, a function) itself chooses when it will allow an interruption, so that it can cooperate with other code. This concept is contrasted with “preemptive”, which suggests that a process/function could be interrupted against its will.

ES6 generator functions are “cooperative” in their concurrency behavior. Inside the generator function body, you use the new yield keyword to pause the function from inside itself. Nothing can pause a generator from the outside; it pauses itself when it comes across a yield.

However, once a generator has yield-paused itself, it cannot resume on its own. An external control must be used to restart the generator. We’ll explain how that happens in just a moment.

So, basically, a generator function can stop and be restarted, as many times as you choose. In fact, you can specify a generator function with an infinite loop (like the infamous while (true) { .. }) that essentially never finishes. While that’s usually madness or a mistake in a normal JS program, with generator functions it’s perfectly sane and sometimes exactly what you want to do!

Even more importantly, this stopping and starting is not just a control on the execution of the generator function, but it also enables 2-way message passing into and out of the generator, as it progresses. With normal functions, you get parameters at the beginning and a return value at the end. With generator functions, you send messages out with each yield, and you send messages back in with each restart.

Syntax Please!

Let’s dig into the syntax of these new and exciting generator functions.

First, the new declaration syntax:

function *foo() {
    // ..
}

Notice the * there? That’s new and a bit strange looking. To those from some other languages, it may look an awful lot like a function return-value pointer. But don’t get confused! This is just a way to signal the special generator function type.

You’ve probably seen other articles/documentation which use function* foo(){ } instead of function *foo(){ } (difference in placement of the *). Both are valid, but I’ve recently decided that I think function *foo() { } is more accurate, so that's what I'm using here.

Now, let's talk about the contents of our generator functions. Generator functions are just normal JS functions in most respects. There's very little new syntax to learn inside the generator function.

The main new toy we have to play with, as mentioned above, is the yield keyword. yield ___ is called a "yield expression" (and not a statement) because when we restart the generator, we will send a value back in, and whatever we send in will be the computed result of that yield ___ expression.

Example:

function *foo() {
    var x = 1 + (yield "foo");
    console.log(x);
}

The yield "foo" expression will send the "foo" string value out when pausing the generator function at that point, and whenever (if ever) the generator is restarted, whatever value is sent in will be the result of that expression, which will then get added to 1 and assigned to the x variable.

See the 2-way communication? You send the value "foo" out, pause yourself, and at some point later (could be immediately, could be a long time from now!), the generator will be restarted and will give you a value back. It's almost as if the yield keyword is sort of making a request for a value.

In any expression location, you can just use yield by itself in the expression/statement, and there's an assumed undefined value yielded out. So:

// note: `foo(..)` here is NOT a generator!!
function foo(x) {
    console.log("x: " + x);
}

function *bar() {
    yield; // just pause
    foo( yield ); // pause waiting for a parameter to pass into `foo(..)`
}

Generator Iterator

"Generator Iterator". Quite a mouthful, huh?

Iterators are a special kind of behavior, a design pattern actually, where we step through an ordered set of values one at a time by calling next(). Imagine for example using an iterator on an array that has five values in it: [1,2,3,4,5]. The first next() call would return 1, the second next() call would return 2, and so on. After all values had been returned, next() would return null or false or otherwise signal to you that you've iterated over all the values in the data container.

The way we control generator functions from the outside is to construct and interact with a generator iterator. That sounds a lot more complicated than it really is. Consider this silly example:

function *foo() {
    yield 1;
    yield 2;
    yield 3;
    yield 4;
    yield 5;
}

To step through the values of that *foo() generator function, we need an iterator to be constructed. How do we do that? Easy!

var it = foo();

Oh! So, calling the generator function in the normal way doesn't actually execute any of its contents.

That's a little strange to wrap your head around. You also may be tempted to wonder, why isn't it var it = new foo(). Shrugs. The whys behind the syntax are complicated and beyond our scope of discussion here.

So now, to start iterating on our generator function, we just do:

var message = it.next();

That will give us back our 1 from the yield 1 statment, but that's not the only thing we get back.

console.log(message); // { value:1, done:false }

We actually get back an object from each next() call, which has a value property for the yielded-out value, and done is a boolean that indicates if the generator function has fully completed or not.

Let's keep going with our iteration:

console.log( it.next() ); // { value:2, done:false }
console.log( it.next() ); // { value:3, done:false }
console.log( it.next() ); // { value:4, done:false }
console.log( it.next() ); // { value:5, done:false }

Interesting to note, done is still false when we get the value of 5 out. That's because technically, the generator function is not complete. We still have to call a final next() call, and if we send in a value, it has to be set as the result of that yield 5 expression. Only then is the generator function complete.

So, now:

console.log( it.next() ); // { value:undefined, done:true }

So, the final result of our generator function was that we completed the function, but there was no result given (since we'd already exhausted all the yield ___ statements).

You may wonder at this point, can I use return from a generator function, and if I do, does that value get sent out in the value property?

Yes...

function *foo() {
    yield 1;
    return 2;
}

var it = foo();

console.log( it.next() ); // { value:1, done:false }
console.log( it.next() ); // { value:2, done:true }

... and no.

It may not be a good idea to rely on the return value from generators, because when iterating generator functions with for..of loops (see below), the final returned value would be thrown away.

For completeness sake, let's also take a look at sending messages both into and out of a generator function as we iterate it:

function *foo(x) {
    var y = 2 * (yield (x + 1));
    var z = yield (y / 3);
    return (x + y + z);
}

var it = foo( 5 );

// note: not sending anything into `next()` here
console.log( it.next() );       // { value:6, done:false }
console.log( it.next( 12 ) );   // { value:8, done:false }
console.log( it.next( 13 ) );   // { value:42, done:true }

You can see that we can still pass in parameters (x in our example) with the initial foo( 5 ) iterator-instantiation call, just like with normal functions.

The first next(..) call, we don't send in anything. Why? Because there's no yield expression to receive what we pass in.

But if we did pass in a value to that first next(..) call, nothing bad would happen. It would just be a tossed-away value. ES6 says for generator functions to ignore the unused value in this case. (Note: At the time of writing, nightlies of both Chrome and FF are fine, but other browsers may not yet be fully compliant and may incorrectly throw an error in this case)

The second next(12) call sends 12 to the first yield (x + 1) expression. The third next(13) call sends 13 to the second yield (y / 3) expression. Re-read that a few times. It's weird for most, the first several times they see it.

for..of

ES6 also embraces this iterator pattern at the syntactic level, by providing direct support for running iterators to completion: the for..of loop.

Example:

function *foo() {
    yield 1;
    yield 2;
    yield 3;
    yield 4;
    yield 5;
    return 6;
}

for (var v of foo()) {
    console.log(v);
}
// 1 2 3 4 5

console.log(v); // still `5`, not `6` :(

As you can see, the iterator created by foo() is automatically captured by the for..of loop, and it's automatically iterated for you, one iteration for each value, until a done:true comes out. As long as done is false, it automatically extracts the value property and assigns it to your iteration variable (v in our case). Once done is true, the loop iteration stops (and does nothing with any final value returned, if any).

As noted above, you can see that the for..of loop ignores and throws away the return 6 value. Also, since there's no exposed next() call, the for..of loop cannot be used in situations where you need to pass in values to the generator steps as we did above.

Summary

OK, so that's it for the basics of generators. Don't worry if it's a little mind-bending still. All of us have felt that way at first!

It's natural to wonder what this new exotic toy is going to do practically for your code. There's a lot more to them, though. We've just scratched the surface. So we have to dive deeper before we can discover just how powerful they can/will be.

After you've played around with the above code snippets (try Chrome nightly/canary or FF nightly, or node 0.11+ with the --harmony flag), the following questions may arise:

  1. How does error handling work?
  2. Can one generator call another generator?
  3. How does async coding work with generators?

Those questions, and more, will be covered in subsequent articles here, so stay tuned!

Author: "Kyle Simpson" Tags: "Guest Blogger, JavaScript"
Comments Send by mail Print  Save  Delicious 
Date: Monday, 21 Jul 2014 01:46

Read the full article at: Check GZip Encoding with curl

Treehouse
Wufoo

Last week I detailed how I enabled gzip encoding on nginx servers, the same server software I use on this site.  Enabling gzip on your server exponentially improves the site load time, thus improving user experience and (hopefully) Google page ranks.  I implemented said strategy and used another website to check if the gzip encoding worked, but little did I know, you can use the curl utility check if the encoding update worked.  Here’s how you can check if the gzip encoding worked:

curl -H "Accept-Encoding: gzip" -I http://davidwalsh.name

After executing the shell command, you’ll get a response that looks like this:

HTTP/1.1 200 OK
Server: nginx
Date: Mon, 21 Jul 2014 01:12:36 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 20
Connection: keep-alive
X-Pingback: http://davidwalsh.name/xmlrpc.php
Cache-Control: max-age=1, private, must-revalidate
Expires: Mon, 21 Jul 2014 01:12:37 GMT
X-Powered-By: PleskLin
MS-Author-Via: DAV
Vary: Accept-Encoding
Content-Encoding: gzip

From the above response, you can see that the page was served gzipped via the Content-Encoding: gzip header.  You can check individual files instead of pages to ensure they have been gzipped as well.  The amount of effort you put into gzipping your site is worth it — imagine how fast it makes your site to the thousands and millions of visitors you have each day!

Author: "David Walsh" Tags: "Apache / Server"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 17 Jul 2014 01:35

Read the full article at: Enable GZIP Compression on nginx Servers

Treehouse
Wufoo

Speed kills, and there’s nothing like a speedy website.  When you come to this blog, I want you to have a great experience, which is why I’ve worked tirelessly to compress every asset and avoid unnecessary synchronous interactions.  In reviewing my site with Google Pagespeed Insights, I noticed that my virtual private server from Media Temple wasn’t configured to serve assets gzip compressed.  Oh no!  Here’s how I enabled gzip compression and made my site miles faster!

Create a file at /etc/nginx/conf.d/gzip.conf with the following content:

gzip on;
gzip_proxied any;
gzip_types text/plain text/xml text/css application/x-javascript;
gzip_vary on;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";

With that file now in place, restart your server and you will now be serving site assets with gzip compression.  Google takes site speed into account when ranking and placing your sites in their search engine so do your users a favor and strive for the fastest site possible – especially for mobile users!

Author: "David Walsh" Tags: "Hosting / Domain, Mobile"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 15 Jul 2014 17:53

Read the full article at: 6 Tips for Designing Crisp, Readable Icons

Treehouse
Wufoo

Dave Gandy is the creator of Font Awesome, the open source icon font and CSS toolkit. He is currently running a Kickstarter to support his all new commercial icon font, Black Tie. If you use Font Awesome, please consider supporting the Black Tie Kickstarter! There’s less than 24 hours left!

After designing hundreds of vector icons that render beautifully at 14 pixels or less, I’ve learned a few things about designing crisp, readable icons. Here are a few of my secrets.

How Vectors Become Pixels

Before we start, let’s chat a bit about how an icon font goes from a vector to individual pixels. Basically, it overlays your vector on top of your pixel grid, then looks at how much of the vector shape lies in each individual pixel. If the pixel has no vector shape overlaid, it renders as 100% of the background color. If it is 100% full, it renders as 100% of the vector shape color. When the pixel is exactly half full (or, ahem, half empty), it would render as 50% transparent. (Real font rendering is a good bit more complex than this, but this model will serve us for now.)

1. Render Crisp Straight Lines

This one is the most straightforward. When your lines are straight, you can make sure your icons are perfectly crisp at 14px. If we have lines that are exactly 1 pixel thick, we have a choice for how to render them. Let’s look at the first example where we want to create a series of vertical lines that are each 1 pixel wide and 1 pixel apart. If we do it perfectly wrong, we can actually end up with a square with 50% opacity and no indication that we intended to render vertical lines:

Half-pixel offset in vector design causes image to render blurred at 50% gray.

Half-pixel offset in vector design (left) causes image to render blurred at 50% gray (right).

However, if we align the edges inside the pixels correctly, we can get perfectly crisp edges:

No pixel offset in vector design causes image to render crisply.

No pixel offset in vector design (left) causes image to render crisply (right).

2. Render Crisp Diagonals

Diagonals turn out to be a bit more complex than straight lines. In the good ole days of pixel editing, you could get a crisp diagonal by stair-stepping down an edge. Let’s see what happens when we do something similar with our vector shape, creating a triangle with points at pixel corners:

Vector design splits pixel directly in half, causing image pixels to render blurred at 50% gray.

Vector design splits pixel directly in half (left), causing image pixels to render blurred at 50% gray (right).

This makes sense when we think about it. We’ve split the line of pixel perfectly in half, so of course it renders blurred at 50% opacity! But if we shift the line any direction a half-pixel, we’ll improve the result. We’ll get one set of pixels that are 12.5% gray and another set that’s 87.5% gray. Visually, that’s pretty close to our stair-step, and we can keep our straight line:

Vector design splits pixel directly in half, causing image pixels to render blurred at 50% gray.

Vector design splits offset by a half-pixel (left), causing image pixels to render crisply at 87.5% and 12.5% gray (right).

3. Keep Outer Edges Crisp

If you’re choosing the width of a line, use whole pixels when you can to render crisp lines. But if you need a fractional width for a border, make the inner border blurry instead of the outer. This improves the crispness of the icon, as the eye is first drawn to the outer border.

Vector design offset by a half-pixel on the outside, causing blurred pixels on the outer border.

Vector design offset by a half-pixel on the outside (left), causing blurred pixels on the outer border (right).

Vector design offset by a half-pixel on the inside, causing blurred pixels on the inner border.

Vector design offset by a half-pixel on the inside (left), causing blurred pixels on the inner border (right).

4. Pathfinder is Your Friend

Often icon shapes quickly become complex and layered, but you’ll need to get them down to just a single layer for consumption by your favorite font editor. Illustrator’s Pathfinder tool (or the Sketch equivalent) is your friend. It allows you to easily take layers of shapes and do lots of helpful things like combine, find intersection, minus-front, and lots more. Learn it. It’s invaluable.

Pathfinder is a great tool for simplifying complex layered icons.

5. Remember Retina, but Design for Non-Retina

Retina displays are gorgeous. And icon fonts are a great way to take advantage of them. But when creating icons, I recommend designing for non-Retina displays. If the icons look good on non-Retina, they’ll also look great at 4x the resolution. Our examples above would all render perfectly crisp on Retina, but aren’t nearly as good as they can be on non-Retina displays.

6. Experiment!

Most often, your shapes are more complex than straight lines and 45° diagonals. The best way to know how an icon is going to render at 14px is to just give it a shot and iterate, learning along the way. When designing an icon for Font Awesome, it isn’t uncommon to go through twenty iterations and spend 8+ hours on a tricky icon. But it’s worth it in the end to create crisp, readable icons that render great at small sizes.

This article builds off the seminal work of GitHub designer Cameron McEfee in his article The Making of Octicons. If you haven’t read it, start there.

Author: "Dave Gandy" Tags: "Guest Blogger, Markup"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 15 Jul 2014 00:32

Read the full article at: How I Stopped WordPress Comment Spam

Treehouse
Wufoo

I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database with that trash slows down my blog in every which way, and recently I decided I was done with it.  I was also tired of moderating comments and seeing loads of SPAM comment notifications in my email inbox.  Done.  And like a boss…I stopped it.  Dead.  Here’s how I did it!

How I Was Getting Spammed

There’s no way to tell, but I suspect bots detected that I had a WordPress blog, knew the form keys for submitting comments, and did so accordingly.  I was getting comments for Viagra, Cialis, Michael Kors, Nike shoes, and more.  Stuff only bots would spend the time on.  It all had to be a detected, automated attack — nothing targeted.

What Wasn’t Working

Everything.  I had used different WordPress plugins and continued to get SPAM.  Akismet is the premier WordPress SPAM protector and it wasn’t able to prevent the problems — and included 100KB+ of JavaScript which slowed down my site.  I never used a CAPTCHA utility because any barrier to commenting on my site should be a problem I deal with, not all of you.  In the end, I was let down by numerous utilities.  I was disappointed but refused to give in.

What Worked

The first step was removing all of the anti-spam plugins, as there was a good chance they were messing with each other and letting the SPAM in.  My solution was allowing the generic anti-spam solution:  adding an INPUT to the form which should remain empty during the submission process.  Empty in value but present via key:  the premise is that bots that read form inputs would populate the form field values with rubbish just to make sure submissions weren’t rejected based on empty values.

How I Implemented Spam Protection

You can’t simply add inputs on the server side — they are output to the page and the bot can read those and populate (or not populate) them.  Creating those fields on the client side eliminates the simple bot / curl readers.  You can add said form fields with JavaScript (via any framework) and that’s your best bet.  Before we do that, however, let’s implement the server-side SPAM block check.

The WordPress PHP

Before accepting a comment on the server side, we need to check for the dynamic key presence.  All we need is an isset check:

// Fuck off spammers
function preprocess_new_comment($commentdata) {
	if(!isset($_POST['is_legit'])) {
		die('You are bullshit');
	}
	return $commentdata;
}
if(function_exists('add_action')) {
	add_action('preprocess_comment', 'preprocess_new_comment');
}

If the check fails, we reject the comment.  Of course this means that users without JavaScript support will have their comments rejected, but the chance of being spammed is probably greater than that of users without JS support so I’m fine with that.  If the key isn’t set, we outright reject the comment all together.  This is a chance, of course, but statistics show it’s worth it.

The JavaScript

The easy answer here is using basic JavaScript to inject the form field, and since every JS framework has its own syntax, I’ll pass on providing code for all of them.  Adding said field upon page load seems a bit suspect to me, as an intelligent bot may be able to detect that.  In the case of my blog, I use MooTools and submit comments via AJAX, so I simply append the secret field within the JavaScript code upon submission:

var form = $('comment-form');

new Request({
    url: form.action,
    method: 'post',
    onRequest: function() {},
    onSuccess: function(content) {},
    onComplete: function() {}
  }).send(form.toQueryString() + '&is_legit=1');
});

Adding that key upon submission has proven safe to this point.

WINNING

After two weeks I’ve received 0 SPAM comments.  Zero.  None.  Nil.  Absolute zip.  I went from over 8,000 per day to none.  Better than Akismet, better than any plugin.  Take WordPress SPAM prevention into your own hands — use client-side magic with a small PHP function to make your life easier!

Author: "David Walsh" Tags: "JavaScript, PHP, WordPress"
Comments Send by mail Print  Save  Delicious 
Date: Monday, 14 Jul 2014 13:11

Read the full article at: Parallax Sound Waves Animating on Scroll

Treehouse
Wufoo

Sound Waves Parallax

Scrolling animations are fun. They are fun to create and fun to use. If you are tired of bootstrapping you might find playing with scrolling animations as a nice juicy refreshment in your dry front-end development career. Let’s have a look how to create animating sound wave using Skroll.js.

The HTML

Firstly we’ll create a container with all our parts.

<div id="soundWave">
    <div class="part p1"></div>
    <div class="part p2"></div>
    <div class="part p3"></div>
    <div class="part p4"></div>
    <div class="part p5"></div>
    <div class="part p6"></div>
    <div class="part p7"></div>
    <div class="part p8"></div>
    <div class="part p9"></div>
    <div class="part p10"></div>
    <div class="part p11"></div>
    <div class="part p12"></div>
    <div class="part p13"></div>
</div>

Each part represents a block in the wave.

The CSS

Add CSS to position our sound wave in the middle of the page and give each part a different background color.

.soundWaves {
    border-bottom: 1px #222222 solid;
    width: 300px;
    height: 200px;
    position: fixed;
    top: 50%;
    left: 50%;
    margin: -200px 0 0 -150px;
}
.partsContainer {
    position: relative;
    width: 240px;
    height: 200px;
    left: 30px;
}
.part {
    width: 20px;
    height: 1px;
    float: left;
}
.p1 {background-color: #4fdc3f;}
.p2 {background-color: #fbe91b;}
.p3 {background-color: #fe9836;}
.p4 {background-color: #fd5064;}
.p5 {background-color: #ff159b;}
.p6 {background-color: #da0638;}
.p7 {background-color: #755eca;}
.p8 {background-color: #0dc2c0;}
.p9 {background-color: #00ae4c;}
.p10 {background-color: #00239b;}
.p11 {background-color: #fe9836;}
.p12 {background-color: #fd5064;}
.p13 {background-color: #ff159b;}

Sound Waves Parallax

Using float to position our parts won’t create a good base for us — we need to tweak the CSS to align everything with the bottom edge of the parent container. Let’s change it from float: left to position: absolute.

.part {
    width: 20px;
    height: 1px;
    position: absolute;
    bottom: 0;
    left: 0;
    transform-origin:50% 100%;
    -ms-transform-origin:50% 100%; /* IE 9 */
    -webkit-transform-origin:50% 100%; /* Chrome, Safari, Opera */
}
.p1 {background-color: #4fdc3f;}
.p2 {background-color: #fbe91b; left: 20px;}
.p3 {background-color: #fe9836; left: 40px}
.p4 {background-color: #fd5064; left: 60px}
.p5 {background-color: #ff159b; left: 80px}
.p6 {background-color: #da0638; left: 100px}
.p7 {background-color: #755eca; left: 120px}
.p8 {background-color: #0dc2c0; left: 140px}
.p9 {background-color: #00ae4c; left: 160px}
.p10 {background-color: #00239b; left: 180px}
.p11 {background-color: #fe9836; left: 200px}
.p12 {background-color: #fd5064; left: 220px}
.p13 {background-color: #ff159b; left: 240px}

We have changed the position of all the parts to position:absolute and bottom: 0, which means that we also need to define left offset, otherwise all parts would be sitting on top of each other.

Sound Waves Parallax

Now when we have them aligned to the bottom edge, changing their scaleY will make them animate up instead of down.

Notice that we have also included transform-origin: 50% 100%. This moves the point from which the scaleY is calculated to the bottom of the element instead of the default center point.

Step 3 – Init Skrollr and Add Some Jazz

We’ll initiate Skrollr below the reference to Skrollr.min.js just before the end of the body.

<script src="js/skrollr.min.js"></script>
<script type="text/javascript">
var s = skrollr.init();
</script>

And add our first data attributes. We’ll use absolute values in this demo.

<div class="part p1"
    data-start="transform: scaleY(1)"
    data-1000-start="transform: scaleY(200)"
    data-2000-start="transform: scaleY(1)"
    anchor-target="body"
></div>

By setting these data attributes we are creating an animation keyframes.

data-start contains our initial value, that is similar to our value in the stylesheet.

data-1000-start is the scale of the part when the user scrolls 1000 pixels down the page and data-2000-start is the scale at 2000 pixels scroll top position.

We want to create a wave, which means that we will need to add the same increment to each of the following parts.

    <div class="part p2" data-start="transform: scaleY(1)" data-1250-start="transform: scaleY(200)" data-2250-start="transform: scaleY(1)" anchor-target="body"></div>

We are increasing the second and third offset value, which creates the desired wave effect. We are also repeating the same increment for all other 13 parts.

Also notice that we don’t need to set the height of out page, Skrollr is smart enough and calculates it for us automatically.

There you have it: a nice simple sound wave created using Skroll.js. Learn more about Skrollr, parallax and scrolling animations in Petr’s Parallax Scrolling Master Class, enter our giveaway below.

Giveaway

Enter to WIN a Parallax Scrolling Master Class by Petr Tichy. An online course teaching you how to create a parallax scrolling website from start to finish using Skrollr.js! How do you throw your hat in the ring? In the comments below, post a link to your favorite use of the parallax effect. There are many great ones out there so to win you better bring an A-quality effect!

Author: "Petr Tichy" Tags: "CSS, CSS Animations, Demos, Guest Blogge..."
Comments Send by mail Print  Save  Delicious 
Date: Friday, 11 Jul 2014 13:28

Read the full article at: Prepend and Append Text to WordPress Titles

Treehouse
Wufoo

I was thinking about little ways to improve my blog and one small enhancement I wanted to make was adding more information to post titles when they show up in RSS feeds.  Something about notifying the user via title outside of the site itself seemed like a good idea.  For example, some posts are just small “quick tips”, and more readers may take the time to peruse it quickly because they know it won’t take too long.  Here’s how I accomplished that feat with WordPress.

The PHP

The first step is creating a function, which is provided the post title and ID, that does a category check and prepends text accordingly:

function show_as_tip_in_feed($title, $id) {
	if(is_feed() && in_category('tips', $id)) {
		$title = 'Quick Tip: '.$title;
	}
	return $title;
}

Once the function is there, the add_filter hook enables the original function:

if(function_exists('add_filter')) {
	add_filter('the_title', 'show_as_tip_in_feed', 10, 2);
}

Of course you don’t need to do the category check or RSS feed check — you can append or prepend text to any and every title, and much like other WordPress functionalities, the API easily allows developers to do so.  Win!

Author: "David Walsh" Tags: "PHP, Quick Tips, WordPress"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 10 Jul 2014 16:58

Read the full article at: The Difference Between Anchors, Inputs and Buttons

Treehouse
Wufoo

HTML5 Buttons

One of the things I love about CSS is how easy it is to make one element look like another. In the example above, the first element is an anchor, the second is a button and the third is an input. I’ve overridden the click behavior of all three so they do the same thing.

If all three elements look and behave the same, does it matter which one you use? In this article, I’ll explain the difference between anchors, inputs and buttons, and I’ll show you when to use each one.

Semantics

The question of which element to use boils down to semantics, which is using markup that reflects the meaning of the content. Using semantic HTML makes your content explicit, which gives you better browser compatibility, accessibility and SEO.

Anchors

Anchors (the <a> element) represent hyperlinks. What’s a hyperlink? A hyperlink is a resource a person can navigate to or download in a browser. If you want to allow your user to move to a new page or download a file, then use an anchor.

Inputs

An input (<input>) represents a data field. The type attribute tells the browser which type of data the input controls. There are five input types related to buttons.

  • <input type="submit">: This is the most common button input. It’s a button that, when clicked, submits a form.
  • <input type="image">: Like an <input type="submit">, this input submits a form. However, it also takes a src attribute and is displayed as an image.
  • <input type="file">: This control is used to upload files and is shown as a label and a button. There’s no good cross-browser way to style file inputs, so you’ll usually set its display to hidden and use a second button to trigger it.
  • <input type="reset">: This is a button that resets a form.
  • <input type="button">: This is a button with no default behavior. You can use to it add non-standard behavior to a form using JavaScript.

Buttons

The <button> element represents a button! Buttons do the same things as the inputs mentioned above. Buttons were introduced into HTML as an alternative to inputs that are much easier to style. Unlike inputs, a button’s label is determined by its content. This means you can nest elements within a button, such as images, paragraphs, or headers. Buttons can also contain ::before and ::after pseudo-elements.

Like an input, a button has a type attribute. This attribute can be set to submit, reset or button and does the same thing as the input’s type. By default, the type is submit. If you place a button in a form and don’t set its type, when it’s clicked it will submit that form! If you don’t want this behavior, set the type to button.

One nifty feature of inputs and buttons is they support the disabled attribute. This makes it easy to turn them on and off. Sadly, anchors don’t have this capability.

Which one?

So should you use an anchor, input or button? When you’re navigating the user to a page or resource, use an anchor. Otherwise, both inputs and buttons are valid. Personally, I prefer to use inputs for submitting and resetting forms and buttons for custom behavior because I think it makes the intent clearer. However, the element you use is entirely up to you. Go nuts!

Author: "Landon Schropp" Tags: "Guest Blogger, HTML5"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 09 Jul 2014 12:27

Read the full article at: Top 20 WordPress Theme Creators from 2014 (Sponsored)

Treehouse
Wufoo

What better way to advertise your business than create a website? And one of the easiest platform to use is WordPress. So, to get you started, we’ve listed below the 20 best designers of WordPress themes. You’ll be pleased to find that all these greatly designed themes they offer are not only good looking but also responsive and very flexible so you can customize them to better fit your needs. Whether you’re looking for a photography, a magazine, a travel or a medical theme, you will not be disappointed, as there is a great variety of templates you can choose from. So what are you waiting for? Start browsing!

Meanthemes

Experience, dedication, passion and talent are just some of the words that could be used to describe Meanthemes. You’ve probably already seen some of their work online and you most certainly haven’t been disappointed. They do have 10+ years of experience to recommend them after all. Anything you might dream you need from a WordPress theme, it’s a safe bet that this team will make it a reality. How are we so confident? Well, they’ve been with with WordPress ever since it was just a blog.

Meanthemes is a team that is interested in acquiring client for the long run. They want to create the best client-supplier relationship possible and make sure that you are completely satisfied with their product. Their goal is to create beautiful themes that will be very apt at displaying your content as best as possible. Your work relationship will be based on trust and respect between both parts. To show you they mean business, they’ve invested time and energy into making their interfaces and installation process as easy to use as possible. They have been consistently putting out creative, flexible, cutting-edge themes and providing you with top notch support for every one of them. Go now to their website and as soon as you buy one of their themes you will have access to a dedicated support system that is willing and able to resolve all your issues within 48 hours, if not (as is usually the case) sooner.

SoloStream

Limited time offer – 37 themes for just $79, coupon code “141258″

If you want fresh, elegant themes; a passionate team with extensive attention to your needs and first rate support, SoloStream has it all. This team has set off on their mission to create themes that are very good at showcasing content through attractive and memorable design and will definitely meet your every need. They consistently respect values such as: freedom, simplicity, integrity and growth, thusly creating an image for themselves as trust-worthy and hard-working.

You can be assured that what you purchase from SoloStream will be a robust and easy to use product. With more than 30 themes under their belt, the team keeps on going and promise to put out more and more themes that are flexible and user-friendly. Add to that complete browser compatibility and search engine optimization and you’re sure to have a winner. Go to their website right now and by purchasing a membership for only $89 and $9/month, you’ll get full access to extensive documentation, tutorials and one of the best online support forums. 

WPZOOM

WPZOOM has a gallery of more than 50 fine-designed themes that work smoothly and run very fast. They all look amazing to the tiniest details and can handle heavy-content sites. The themes are very flexible and easy to customize using shortcodes to create buttons or columns and changing colors with a single click. Plus, there’s a built in slideshow shortcode that allows you to create great animated image galleries without installing other plug-ins. The themes also come with basic SEO features and Import&Export options that allow you to easily move your theme and settings from one domain to another. If you’re not sure what to choose, don’t worry. You can take the themes for a test-drive through their Live Demos. Moreover, you can read theme documentation at the support center or ask the team if you’re having any trouble. They will be happy to help. Have fun browsing through the gallery of great WPZOOM themes.

Shape5

Looking for creative designs and easy to use themes? Shape5 is a top choice. With a 7 year experience, the team of professionals can offer an amazing variety of themes such as restaurant, travel, salon, school, game, news or political. The themes are responsive and easy to install, so you can have your website up and running in just a few minutes. Moreover, the themes are very flexible and customizable, so you can easily change some settings, like layouts or colors, without using codes. For each theme you are provided with a demo that helps you figure out how your future website will look and work. For any questions or problems, the team offers support and also comes up with regular updates for their items.

ProteusThemes

Responsive themes are a priority for ProteusTheme, so they make their items compatible to any device. Besides being responsive, all templates are created with focus on performance and loading speed and are also easy to use. The team is very client-oriented and they recorded video-tutorials so even beginners can easily use their products, besides answering any queries within 12 hours. You should start browsing!

MintThemes

Mintthemes has managed to put out a portfolio of themes that have satisfied the needs of very diverse clients, from church organizations, to production companies, music blogs and jewelry stores. You can’t deny that by the time you’ve got more than 12500 happy clients, you have most assuredly found the recipe for success. But don’t take our word for it, go on to their website right now and take a look for yourself.

PixFlow

PixFlow is a young team but has already put out a series of impressive themes that all include beautiful design, amazing user experience and a high degree of flexibility. The team prides itself with their talent and proficiency and they’ve got both in spades. Browse to their home page and be ready to be impressed.

TeslaThemes

TeslaThemes offers a variety of attractive themes with eye-catching designs. Browse their website right now and it’s very unlikely that you’ll not find a theme that will suit your needs perfectly. Add to this dedicated 24/7 support for all their premium themes, responsive design and in-house framework that will assure stability and your experience with TeslaThemes will set off on the right foot. Also, go to their site right now and use the code “TESLAPROMO” to get 20% off any purchase.

Skywarrior

Don’t be intimidated by their name, SkywarriorThemes are a team of passionate and talented web designers and developers that are ready to turn your dream website into a reality. They specialize in anything related to sci-fi and fantasy, but they’ve branched out to more social oriented themes as well, like crowdfunding and social reach. Get in touch with them and let them turn your vision to reality.

ThemeIsle

If you’re feeling marooned because you cannot find the perfect WordPress theme, the pirates of Themeisle might save you. They offer over 15 themes that will give your visitors a great visual experience. Moreover, the themes will be very easy for you to install and use, as they are customizable. If you encounter any problem, the crew will be there to offer you support.

Themes Awesome

The themes from Themesawesome manage to live up to their given name pretty well. There are around 14 themes that look really great and are customizable. You can browse through them and see the demos before making up your mind. For any information you should require the team is at your service and will provide you with the help you need.

ShopitPress

With extensive experience and relentless passion, ShopitPress have been putting out amazing themes consistently every month for quite a while now. Their themes have assured fast loading, compatibility cross browser and attractive design. With a starting price of $59/theme, they also come with full access to support forums and documentation and 12 months of technical support.

Kubasto

Despite providing only few themes, Kubasto makes up for it through the great designs and usability their templates have to offer. You can catch a glimpse of how the theme looks and works through a demo. The themes are flexible and responsive and the team offers support for their clients.

InkThemes

You can’t find a proper theme for your business’ website? Try Inkthemes. They have a great variety of themes, more than 40, of which you can choose. Sports, travel, spa, magazine – any business or hobby you have, there surely is the theme for it on Inkthemes. Besides, all themes are easy to install and the team offers support to all their clients.

Pixel Union

From minimal or illustrative to glossy of vintage, whether you’re looking for something simple or more extravagant, Pixel Union is the place you can find many great looking themes that meet your requirements. All easy to use and flexible the themes from Pixel Union are a great choice for either beginners or professional when it comes to WordPress themes.

Hogash

Hogash has created one of the most versatile themes you’ll encounter. It uses the latest technologies and trends available, it comes with clean design and increased flexibility, SEO optimization, custom pages and cross browser compatibility. And you haven’t heard the best news yet all of this is available for only $55/theme.

QodeInteractive

It’s unlikely that you’ve never come across an interactive or animated website by now. You thought it was pretty amazing, right? Well, if you want that for your website, Qodeinteractive is prepared to offer you their Retina Multi-purpose themes that will give your site an edge over your competition. Go to their homepage right now and see exactly what they can do for you.

Ait-Themes

When looking for a theme, you should browse through the wide variety Ait-themes offers. Their themes are well designed, visually appealing, easy to use and customizable. You get to create your website just in a few minutes and any help you need will be provided by the team through the support forum.

Obox Themes

We could go on and on about how skilled the Obox team really are and how their themes cover a variety of customer websites, like photography, blogging or ecommerce, but the best way is for you to see for yourself. Go to their home page right now and browse their 20+ theme portfolio to get a sense of how awesome they truly are.

Author: "David Walsh" Tags: "Sponsored"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 08 Jul 2014 18:41

Read the full article at: Prevent Widows with PHP and JavaScript

Treehouse
Wufoo

One of the small touches you can add to your website is preventing “widows” in your H1-H6 tags.  For those who aren’t aware, a widow (in terms of text and headings) means only one word of a title wraps to the next line — a bit of an ugly sight if you ask me.  The way to prevent widows with just text is by adding a &nbsp; between the last two words of the text instead of a regular space character.  Here are two snippets for preventing widows in your website:  one using JavaScript and another using PHP!

// With JavaScript
var text = text.replace(/\s(?=[^\s]*$)/g, '&nbsp;');
// With PHP
$text = preg_replace( '|([^\s])\s+([^\s]+)\s*$|', '$1&nbsp;$2', $text);

As I mentioned originally, widows are not necessarily a bug, but a small visual quirk that just doesn’t look great.  Keep these regex usages handy so you can prevent such a smudge!

Author: "David Walsh" Tags: "JavaScript, PHP"
Comments Send by mail Print  Save  Delicious 
Date: Thursday, 03 Jul 2014 16:32

Read the full article at: Try Treehouse!

Treehouse
Wufoo

Treehouse Coupon Code

Treehouse has been a mainstay of web learning for a few years now and I’m amazed at how they’ve grown.  You’d expect them to teach basic stuff like web design and JavaScript, but they’ve moved on to broader but important topics like jQuery, DNS, and entrepreneurship.  Treehouse doesn’t just get you started in web development, they try to encompass the entire web development and admin sphere.  The only thing missing are the fire drills you experience those first few years on the job!  I thought I’d put together a list of reasons to try Treehouse, even for the biggest skeptics in you!

They Flipped the Web Learning Process on its Head

I went the “low route” to a web development career, meaning I went to a small technical college and then went on to another two-year school to get my bachelor degree.  What did I learn from that?  A piece of paper costs a lot.  I was paying thousands of dollars for a piece of paper than no one has ever asked for.  Treehouse is much more direct and cost-effective.  Videos, quizzes, detailed documentation, and best of all:  it’s focused on the set of tasks important to the topic you’re looking to learn; imagine that.

Treehouse iPad App

They Have an Epic iPad App

I wrote about Treehouse’s iPad app a while back, but it bears repeating:  it’s awesome.  It’s usable, well designed, and provides all of the videos, quizzes, and code sample creation you’d find on the site.  Learning on the go!

Get One, Give One

For every gold account purchased, Treehouse gives one to a public school student.  That’s absolute class.  Knowledge of the web and how to create beautiful websites and apps is a gift that will last a long time, especially considering public schools generally don’t (in my experience) teach the topic very well, especially at early ages.  I encourage you to read Treehouse’s public school initiative, as it sheds light on why they do it.

You Can Start For Free

Treehouse lets you start for free, so you aren’t tied into paying a bunch before you get a chance to give their online education system a real go!  There’s no reason to not give it a try!

If only I had treehouse when I was younger.  I enjoyed my struggles learning but a more structured learning environment would have better taught me basics I learned later on by making mistakes, sometimes in production.  As a seasoned dev now, I still use Treehouse to learn about advanced DNS and web design principles, and occasionally even the entrepreneurship instruction.

Author: "David Walsh" Tags: "Blog"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 02 Jul 2014 13:33

Read the full article at: Scroll IFRAMEs on iOS

Treehouse
Wufoo

For the longest time, developers were frustrated by elements with overflow not being scrollable within the page of iOS Safari.  For my blog it was particularly frustrating because I display my demos in sandboxed IFRAMEs on top of the article itself, so as to not affect my site’s AJAX pageload strategy.  Some research revealed that there are only two CSS properties to set and one element to set them on.  Here we go!

The HTML

In the case of an IFRAME and all other HTML elements, you’ll want a wrapping element like a DIV:

<div class="scroll-wrapper">
	<iframe src=""></iframe>
</div>

This DIV will serve as the base container for what’s scrollable inside.

The CSS

One familiar property and one lesser-known property will be used to allow scrolling for the IFRAME:

.scroll-wrapper {
	-webkit-overflow-scrolling: touch;
  	overflow-y: scroll;

	/* important:  dimensions or positioning here! */
}

.scroll-wrapper iframe {
	/* nada! */
}

The -webkit-overflow-scrolling: touch; property and value were created especially for the case of overflow scrolling within the browser.  Without this the page will scroll when you scroll the IFRAME area; with it you get control of the IFRAME! For my site’s case, I use the following:

.demo-iframe-holder {
  position: fixed; 
  right: 0; 
  bottom: 0; 
  left: 0;
  top: 0;
  -webkit-overflow-scrolling: touch;
  overflow-y: scroll;
}

.demo-iframe-holder iframe {
  height: 100%;
  width: 100%;
}

Keep this tip handy and remember the special CSS goes on the wrapper and not the scrollable element itself!

Author: "David Walsh" Tags: "CSS, Demos, Markup, Mobile, Quick Tips"
Comments Send by mail Print  Save  Delicious 
Date: Tuesday, 01 Jul 2014 17:44

Read the full article at: Wrap Long Links with CSS

Treehouse
Wufoo

Developers have loads to think about when creative websites, and much of that is ensuring child elements don’t stretch past the parent width.  We worry about images, IFRAMEs, and other popular elements pushing past their parent width, but then we see a basic link with a long URL and we look down, just shaking our heads.  Why doesn’t the URL just break?

To prevent that issue, you can apply the following CSS:

/*
	Problem:  

	<a href="">//someurl.com/a-really-really-really-really-really-really-really-really-really-long-url</a>
*/
a {
	word-wrap: break-word;
}

Should this be a global setting for A elements, or simply something that we as developers should set?  Surely this is an annoyance we shouldn’t have to deal with, right?

Author: "David Walsh" Tags: "CSS, Markup, Quick Tips"
Comments Send by mail Print  Save  Delicious 
Date: Monday, 30 Jun 2014 13:23

Read the full article at: JavaScript Once Function

Treehouse
Wufoo

Every so often you have a function which you only want to run once.  Oftentimes these functions are in the form of event listeners which may be difficult to manage.  Of course if they were easy to manage, you’d just remove the listeners but that’s a perfect world and sometimes you simply want the ability to only allow a function to be called once.  Here’s the JavaScript function to make that possible!

The JavaScript

Think of this once function as a wrapper for the function you provide:

function once(fn, context) { 
	var result;

	return function() { 
		if(fn) {
			result = fn.apply(context || this, arguments);
			fn = null;
		}

		return result;
	};
}

// Usage
var canOnlyFireOnce = once(function() {
	console.log('Fired!');
});

canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // nada

The wrapping function is fired only once because a tracker variable is used to ensure the function is only executed once.  Many JavaScript toolkits offer this as a feature but the code to accomplish this feat is so small that it’s good to have available in the case that you can dodge a JavaScript toolkit!

Author: "David Walsh" Tags: "JavaScript, Quick Tips"
Comments Send by mail Print  Save  Delicious 
Next page
» You can also retrieve older items : Read
» © All content and copyrights belong to their respective authors.«
» © FeedShow - Online RSS Feeds Reader