My first npm module

Finally, I found the time to update the Greek in Tech site and create my very first npm package! The idea was to extract all the entries from the backbone single page application, create a very simple API for all these data / entries and distribute them as an npm package. That way, I could easily use it as a dependency to the SPA site, with all the benefits of an npm module like reusability, easier maintenance, single responsibility etc.

You can still contribute entries on the package’s official repository learn more about it from its official npm page (yes the package’s name is still greek-in-tech). Feel free to use it on your own projects and star it if you like it!

Coffeescript gotchas (part 3): Switch statement and loops

Welcome to the third part of Coffeescript gotchas. If you haven’t yet read the first and second part of the series I strongly recommend to have a look. The main topic today is loops plus the switch statement. CoffeeScript offers a lot of enchantments and syntactic sugar to them.

Update: Table of contents

Switch statement

At last, an easier way to write switch statements. If your switch case contains a single line of code, you can write the entire thing in a single line using the then keyword (see second example).

name = "John"

# normal switch statement
switch name
  when "John"
    console.log "This guy rocks!"
  when "Jon"
    console.log "Still cool guy"
  else
    console.log "Good lad."
    
# switch statement using the then keyword
switch name
  when "John" then console.log "This guy rocks!"
  when "Jon" then console.log "Still cool guy"
  else console.log "Good lad."

See the Pen Coffeescript gotchas (part 3): switch statement and loops by John Tsevdos (@tsevdos) on CodePen.

For Loops

For loops have many flavors and great potential in CoffeeScript. You can loop through arrays and objects and still keep your code clean and hassle-free. Just take a deep breath and try to absorb as many flavours as you can. They can all come very handy.

Arrays

Iterating Arrays have never been easier…

arr = ["Ned Stark", "Jon Snow", "Arya Stark", "Jaime Lannister"]

# basic array iteration
for name in arr
    console.log name

# array iteration (with index)
for name , i in arr
    console.log "#{i}: #{name}"

# array filtering (with index)
for name, i in arr when name.indexOf "J" is 0
    console.log "#{i}: #{name}"

# array iteration for every second item
for name , i in arr by 2
    console.log "#{i}: #{name}"

See the Pen Coffeescript gotchas (part 3): switch statement and loops by John Tsevdos (@tsevdos) on CodePen.

Objects

Looping through an object’s key/value pairs is also very easy. You can also loop through just the direct key/value pairs (not the inherited ones) by using the own keyword (which will use the hasOwnProperty method under the hood).

ned =
  name : "Ned Stark"
  house : "Stark"
  words : "Winter is coming"

# print all properties of an object
for key, value of ned 
  console.log "#{key} : #{value}"

# print all own properties of an object
for own key, value of ned
  console.log "#{key} : #{value}"

See the Pen Coffeescript gotchas (part 3): switch statement and loops by John Tsevdos (@tsevdos) on CodePen.

While Loops

The while loop has 3 syntax flavors to make your code more descriptive and your life easier. Try to use unless instead of while not, as it’s easier and preferable.

# Normal while
num = 10
while num
  console.log num
  num--

# while not
num = 10
while not (num is 0)
  console.log num
  num--

# exactly the same as the above example
num = 10
until num is 0
  console.log num
  num--

See the Pen Coffeescript gotchas (part 3): switch statement and loops by John Tsevdos (@tsevdos) on CodePen.

As you can see CoffeeScript is very handy when it comes to loops. Keep in mind and stay tuned for the fourth and final part of the Coffeescript gotchas series where we’ll have a look at the syntactic sugar that CoffeeScript provides on Scope and Objects.

CoffeeScript gotchas (part 1): Comments, strings, booleans, arrays and functions

In the last couple of months I took some time to learn and work on a CoffeeScript project. Writing CoffeeScript is a lot of fun, and if you know plain Javascript you already know most of the Coffeescript syntax – just start removing all the syntax cluttering like semicolons, parenthesis and square brackets and suddenly you are writing Coffeescript!

The really cool stuff begins when you dig a bit more into the language. There’s some nice demonstrations of features that I had to learn the hard way.

Before jumping into these, have a look at the well-written, free on-line book Coffeescript Cookbook. This excellent resource saved me a lot of time in many situations.

Update: Table of contents

Comments

You can have single-line and multi-line comments in CoffeeScript. Always keep in mind that during compilation, the compiler will completely ignore the single line comments (they wont appear in your final Javascript file) but will keep the multi-line comments intact. In the Codepen examples below you can click the “view compiled” link to see the generated JS code and the result tab to see the result (if any)…

# Single-line comment
###
Multiline comment
###

See the Pen CoffeeScript gotchas (part 1): Comments by John Tsevdos (@tsevdos) on CodePen.

String Interpolation

Probably the best feature Coffeescript provides! You can finally do things like this:

name = "John"
greeting1 = "Hello, #{name}!" # -> Hello, John!
greeting2 = 'Hello, #{name}!' # -> Hello, #{name}!

document.write greeting1
document.write '
'
document.write greeting2 

See the Pen CoffeeScript gotchas (part 1): Strings by John Tsevdos (@tsevdos) on CodePen.

Keep in mind that double quotes are needed to compile correctly. You can even use functions!

mrFunc = (name) -> "Mr. " + name
message = "Hello, #{mrFunc 'John'}"

document.write message

See the Pen CoffeeScript gotchas (part 1): Strings by John Tsevdos (@tsevdos) on CodePen.

Heredoc (multiline strings)

You can also use Heredocs. They even support interpolation!

multiline = """
This is 
a multiline
string
of #{3+2}
lines
"""


document.write multiline

See the Pen CoffeeScript gotchas (part 1): Strings by John Tsevdos (@tsevdos) on CodePen.

Booleans

Not much news here, apart from some syntax goodies… You can use true with two more keywords, yes and on and you can use false with the opposites, no and off. Sometimes it makes more sense to use these keywords instead of the normal true/false.

# true === yes === on
if true
  document.write 'true
'
  
if yes
  document.write 'yes
'

if on
  document.write 'on

'

# false === no === off
if !false
  document.write 'false
'
  
if !no
  document.write 'no
'

if !off
  document.write 'off
'

See the Pen CoffeeScript gotchas (part 1): Booleans by John Tsevdos (@tsevdos) on CodePen.

Arrays

CoffeeScript allows a very convenient syntax to create specific array ranges. You can create any range using the two dots syntax (inclusive range, which simply means that it will include the last value). Adding three dots instead excludes the last value (exclusive range). Finally you can use reverse ranges the same way. Have a look at the examples, they are much easier than they sound…

range1  = [0..10]  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range2  = [0...10] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range20 = [20..0]  # [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

See the Pen CoffeeScript gotchas (part 1): Arrays by John Tsevdos (@tsevdos) on CodePen.

Functions default values

One of the coolest and most usable CoffeeScript features is the default values on functions. Instead of checking if a value exists, etc. you can simply apply the default value right next to the parameter.

greeting = (name = "friend") -> 
  "Hello #{name}"

document.write greeting('John')
document.write '<br />'
document.write greeting()

See the Pen CoffeeScript gotchas (part 1): Functions by John Tsevdos (@tsevdos) on CodePen.

IIFE – Immediately Invoked Function Expressions

Another tricky part when start to learn CoffeeScript is how you write an IIFE. The syntax is a bit tricky, so have a look below (keep in mind that only CoffeeScript 1.3 and above supports default values on IIFE).

do (doc = document, jQuery = $) -> 
  document.write "IIFE magic"

See the Pen CoffeeScript gotchas (part 1): Functions by John Tsevdos (@tsevdos) on CodePen.

Stay tuned for more CoffeeScript 😉

Responsive media (images and videos) using only CSS

There’s no reason to explain everything from scratch, there are plenty of posts on this topic, but if you are building a responsive layout, don’t forget to apply these media rules to your CSS file.

See the Pen Responsive media (images and videos) using only CSS by John Tsevdos (@tsevdos) on CodePen

With the above styling rules we ensure that all of our media files (images and videos) are ready for responsive layouts. The first two rules are very easy to understand and probably the safest and simplest way to publish media online (since we are talking about pure HTML5 elements). The final two rules are for embedded media (objects, embeds and iframes), that we simply wrap into a container/wrapper element (with a class of video). I first read of this technique on a post entitled “CSS: Elastic Videos” and personally I believe that it’s the best solution for responsive video embeds. I’m usually against Javascript solutions/alternatives, like for example FitVids.JS, since it’s a pure presentational (CSS) issue and not a functional (Javascript) one.

So if you’re building a responsive layout, try treating your media with the pure CSS approach. It’s the fastest, simplest and cleanest way to achieve responsive media

jQuery lights off effect

I’ve been working on a “lights off” effect for videos the other day. Here’s a demo page (with the appropriate code) that I might turn into a proper plugin if there is enough interest. Enjoy…

$(document).ready(function(){
	
		// Build the link
		$('.lightsoff').append('<div class="lightsoffbtn"><a href="#">Lights Off</a></div>');
		
		// Prepare the overlay
		$('body').append('<div class="lightsoff-ovelay off" style="position:relative; z-index:1; display:none;">close</div>');
		
		// Variables
		var $overlay = $('.lightsoff-ovelay'),
			$containers = $('.lightsoff'),
			$lightsoffTrigger = $('.lightsoffbtn a');
	
			
		// LightsOff events
		$lightsoffTrigger.each(function(){
		
			// Variables
			var $container = $(this).parent().parent();
	
			// Apply some CSS
			$container.css({ 'position': 'relative' });
	
			$(this).click(function(e){
	
				e.preventDefault();
					
				if ( $overlay.hasClass('off') ) {
	
					$container.css({
						'z-index': 4000
					});
	
					$overlay.css({
						'position': 'fixed',
						'display': 'block',
						'text-indent': -99999,
						'background-color' : '#000000',
						'width': '100%',
						'height': '100%',
						'top': 0,
						'left': 0,
						'z-index': 3000,
						'opacity': 0.7,
						'cursor': 'pointer'
					});
	
					$overlay.removeClass('off').addClass('on').fadeIn();
	
				} else if ( $overlay.hasClass('on') ) {
					e.preventDefault();
					$containers.css({ 'z-index': 0 });
					$overlay.removeClass('on').addClass('off').fadeOut();
				}
			
			});
		
		});
		
		$overlay.click(function(e){
			e.preventDefault();
			$containers.css({ 'z-index': 0 });
			$overlay.removeClass('on').addClass('off').fadeOut();
		});
	
	});Check out this Pen!

jQuery window.onload equivalent

Last week a reader contacted me noting that my equal heights script was not working. When I took a closer look at his code, I found out that the reason for it not working correctly wasn’t my script but the way jQuery works! The normal jQuery behaviour is to run the code when the DOM is ready and won’t wait for images/graphics etc, to load. There are some cases though, that someone needs to run a piece of code after the entire page is fully loaded. You can achieve that with the code bellow :

$(window).load(function() {
	// When the entire page is fully loaded
	$('#content, #sidebar').equalHeights();
});Check out this Pen!

The elements that needed equal heights contain images, so the script was miscalculating the max-height value because it wasn’t getting the correct height of the images (since they were still loading). The above code will fix that, since it will load the script when the entire window is fully loaded (including images).

Keep in mind that this is an event handler method (a shortcut for .bind('load', handler) ) and has nothing to do with the ajax load() method.

How to load styles and scripts on a WordPress theme

WordPress provides two useful functions to help you keep the head section on your header.php template file clean. The wp_enqueue_style will help you load your styles and the wp_enqueue_script will help you load your scripts. Both take the same parameters (name, source, dependencies, version, media – only for wp_enqueue_style – and in_footer – only for wp_enqueue_script) and the official WordPress documentation explains everything in great detail. Below I’ll demonstrate a simple way to use them, this is the same way it works on my latest free WordPress theme, Ambrosia.

These two functions “live” into the functions.php file. So let’s load the styles first. We only have to create an include function (for example ambrosia_load_styles()) that will load all the files using one or multiple wp_enqueue_style functions. To be more  specific, we’ll only load styles in our wordpress theme and not at the admin area (!is_admin()). Then an action hook will run the include function (ambrosia_load_styles()), just before the header.php template file is loaded. It’s simpler than it sounds, have a look at the below code.

It’s much more simple to load script files. We only include our scripts using the wp_enqueue_script function (again excluding the admin area).

Don’t forget that you can create dependencies on both CSS and javascript files, and of course load your javascript files in your footer area (after the page content is fully loaded).

Unfortunately, wp_enqueue_style and wp_enqueue_script functions don’t support any conditional comment mechanism, so if you have Internet Explorer (IE) only styles and scripts, you have to include them manually to your header.php file.

That’s all you need to know, so next time you’re building a theme, keep your header.php file clean by doing all the dirty work into the functions.php file!

Organizing jQuery Code

Organizing jQuery code is not easy. Up to now, especially on small/medium scale projects, I used to have a huge jQuery ready function and place all my code there. Some times if I needed to run something on specific elements I was just doing a quick test to check if the element was on the document.

$(document).ready(function(){
	//jQuery code...
	if ( $('.someClass').length ) { // if element exists then run the below code
		// Do something
	}
});Check out this Pen!

The above technique is not too bad, it works just fine for a small or medium sized site, but what happens with a larger site that uses heavy javascript code? The answer came from a presentation I watched recently (Simple JavaScript & CSS Management With Rack by Mr. Avand Amiri – I strongly encourage you to watch it as well). The solution is really clean and pretty smart. Just create a javascript file (actually you can break it to as many files as you want) that will hold all your main objects. Below is a very basic “Greetings” object.

var Greetings = {
	alertFn: function () {
		alert('OK');
	},
 
	john: {
		sayHelloToJohn: function() {
			alert ('Hello John!');
		}
	}
// do something else, etc.
}Check out this Pen!

At the example above the object “Greetings” contains two methods (functions). As you can see, I could go further and create nested objects with their own methods. The idea is to organize my methods as well as I can.

Then I only have to call them into our usual jQuery ready function like this.

$(document).ready(function(){
  Greetings.alertFn();
});
// or
$(document).ready(function(){
	Greetings.john.sayHelloToJohn();
});Check out this Pen!

Keep in mind that this way I can follow any code structure/organization I need, so for example I can follow my application’s controllers structure and naming convention, or whatever makes more sense for my app. This way we get a simple, more robust, well-organised jQuery code, and not the classic document ready soup…