Detecting When A User Clicks Outside of An Element

I was recently working on a complex problem involving a popup element. I wanted the popup to disappear when the user interacted with any other element on the page, except for the popup itself.

Like most, I Googled the problem and very few elegant solutions came up. There was one however. Take a look below:

$(document).mouseup(function(e) {
    var container = $("SELECTOR");

    if (!container.is(e.target) && container.has(e.target).length === 0) {
        container.hide();
    }
});

The snippet of code checks if the click element is either the popup itself or one of it's children. You can read more about the has method in the jQuery API documentation.

EDIT

It was pointed out by Ben Howdle and Dan Harper that there is an even simpler way to solve this problem. Check it out:

var popup = $('#popup');

$(document).on('click', function(){
    popup.hide();
});

popup.click(function(e) {
    e.stopPropagation();
});

You can see this in action and readup about e.stopPropagation in the jQuery documentation.

The Best Packages, Shortcuts and Customisations in Sublime Text 2

The best thing about Sublime Text 2 is the amount of customization it gives the user and the ease in which it does this. Here are a list of the best features I use on a day-to-day basis...

Projects

During the day I can work on up to 5 or 6 various tasks, so having my different codebases setup into projects is extremely useful. All you need to do to create a new project is drag a folder into your sidebar, go to Project in the menu bar and click save as. You can add multiple folders to a project.

To easily switch between projects, hit Ctrl+Alt+P (Cmd+Shift+P on Mac) and start searching for the project you're after.

Once within a project, you can hit Ctrl+P (Cmd+P) and search for any filename within that project. Pretty cool stuff!

Packages

There are loads of packages out there for Sublime. The number is always growing, and to keep most of them in one place, Package Control was created.

You first need to install Package Control. Once that's done, hit Ctrl+Shift+P (Cmd+Shift+P). This is the command palette and lists all available commands currently installed. Start typing "Install Package" and hit enter. From here you can search for packages within the Package Control repo. You can even manually install them using a link (usually a public GitHub link).

Here are the packages I used often:

  • SublimeCodeIntel - Code intelligence plugin ported from Open Komodo Editor
  • SublimeLinter - SublimeLinter comes with built in linters for loads of languages
  • Prefixr - A Sublime Text 2 plugin to run CSS through the Prefixr API
  • Emmet - (previously Zen Coding) lets you use shortcuts to generate HTML and CSS
  • Clipboard History - Saves previously copied text for easy retrieval
  • Code Alignment - Easily align code using colons, commas etc
  • JsFormat - Formats given JavaScript code
  • CssLisible - Tidy up CSS based on given rules
  • FileDiffs - Compares two given files
  • LESS build - Adds a build engine to compile LESS
  • Markdown Previewer - Lets you see a temp file of your markdown code. Comes with GitHub flavoring option
  • Sidebar Enhancements - Adds windows functionality to the sidebar (right-click menu)
  • Themes - Colour Schemes : Tomorrow Theme

There a loads more out there, so let me know if you find some more useful ones

Special Customizations

Sublime comes with lots of various options that you can configure to your needs. You'll find all the available settings in the default settings file (Preferences > Settings - Default). It's filled with comments explaining what each option does, so if some of the ones below don't make sense, do a quick search for them:

"font_face": "Consolas",
"font_size": 9,
"caret_style": "phase",
"highlight_line": true,
"line_padding_top": 1,
"line_padding_bottom": 1,
"bold_folder_labels": true,
"highlight_modified_tabs": true,
"tab_size": 4,
"translate_tabs_to_spaces": true,
"trim_trailing_white_space_on_save": true,
"dictionary": "Packages/Language - English/en_GB.dic"

These are some more handy settings to look into:

"spell_check": false,
"gutter": true,
"line_numbers": true,
"save_on_focus_lost": false,
"highlight_modified_tabs": false,
"folder_exclude_patterns": [".svn", ".git", ".hg", "CVS"],
"file_exclude_patterns": ["*.pyc", "*.pyo", "*.exe", "*.dll", "*.obj","*.o", "*.a", "*.lib", "*.so", "*.dylib", "*.ncb", "*.sdf", "*.suo", "*.pdb"],

You can have specific settings set for each project as well. So I have a project which contains all my blog posts. Within this project, I have the option spell_check turned on. You can enable settings for projects by going to Projects > Edit Project and adding your settings

{
    "folders":
    [
        {
            "path": "/C/folder/project_location"
        }
    ],
    "settings":
    {
        "spell_check": true,
        "dictionary": "Packages/Language - English/en_GB.dic"
    }
}

Shortcuts

Knowing shortcuts in any program can increase productivity massively. Here are the ones I use most often (replace Ctrl for Cmd on a Mac). Again, all the key bindings live in Settings > Key Bindings - Default

Ctrl+P                 => Search for file in project
Ctrl+Shift+P       => Launch command palette

Ctrl+F                  => Find
Ctrl+H                 => Find and Replace
Ctrl+Shift+F        => Find in Project

Ctrl+D                 => Select current word
Ctrl+Shift+D       => Duplicate line or selected text

Ctrl+Shift+Up         => Move line up
Ctrl+Shift+Down    => Move line down

Alt+Shift+1        => Split into 1 of columns
Alt+Shift+2        => Split into 2 of columns
Alt+Shift+3        => Split into 3 of columns
Alt+Shift+4        => Split into 4 of columns

Alt+Shift+5        => Split into a grid of 4

Alt+Shift+8        => Split into a 2 rows
Alt+Shift+9        => Split into a 3 rows

Ctrl+B                  => Build
Ctrl+R                  => Shows all methods/functions/selectors in that file
Ctrl+K, Ctrl+B      => Hide/Show sidebar
Shift+F11             => Distraction Free Mode

One shortcut that gets it's own special mention is Ctrl+T. This bad boy allows you to create a new file relative to the file you are in now. A small bar will appear at the bottom of the window allowing you to type the folder and file names. Here are some examples:

// Lets say we are currently editing the file' /css/main.css' and we hit Ctrl+T
// If we create a new file from here with the following paths...

fonts.css                => creates the file 'fonts.css'
module/file.css     => creates the file 'file.css' in the 'modules' folder
../index.html         => creates the file index.html in the parent folder

// if a folder doesn't exist, Sublime will create it for us
// you can't create a new file which already exists

Snippets

Snippets are incredible useful. They are the things that popup in the autocomplete box as you type. If you find yourself writing the same code over and over, put it into a snippet.

To create a snippet, go to Tools > New Snippet. A new window will open with some code and some options.

Firstly, the snippet content is the code we want to produce. The text mark with a $ signifies a tab point. So when the user selects the snippet, the cursor moves to position one ${1:this}. If tab is hit, then the cursor moves to position 2 ${2:snippet}.

The text within the brackets is the default values and will be highlighted when you get to that position. Alternatively, if you don't want a default value, just use $1 or $2.

<snippet>
    <content><![CDATA[
Hello, ${1:this} is a ${2:snippet}.
]]></content>
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <!-- <tabTrigger>hello</tabTrigger> -->
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <!-- <scope>source.python</scope> -->
</snippet>

You can set a tabTrigger, which is the word or phrase to trigger than snippet showing up in the autocomplete results. Pick something you will easily remember. The final option is scope which only shows that snippet up for a certain syntax

Here are a few examples I created...

// creates console.log('') and places the cursor inside of the parentheses

<snippet>
    <content><![CDATA[
console.log('$1');
]]></content>
    <tabTrigger>console</tabTrigger>
    <scope>source.js</scope>
    <description>console.log</description>
</snippet>


// quickly adds jQuery source to a file

<snippet>
    <content><![CDATA[
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
]]></content>
    <tabTrigger>jQuery</tabTrigger>
    <description>imports jQuery</description>
</snippet>

Beware of Trailing Slashes When Using Disqus

I ran into a small bug with the commenting system Disqus today. After migrating all my posts from WordPress to Disqus, I noticed that comments weren't appearing on some blog posts. With some further investigation, it turned out that my WordPress URLs all had a trailing slash at the end, whereas in the new build of my site, they don't. This meant that the URLs I was serving visitors and those that were in the system didn't match.

It's not a complicated bug to deal with, but something that can be easily missed. To solve the problem, I added this to my htaccess file. It redirects all URLs without a trailing slash to one does:

# add trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*[^/]$ /$0/ [L,R=301]

How to Setup and Work with Virtual Hosts using WAMP Server

What you'll need:

What is a virtual host?

The Wikipedia definition is:

Virtual hosting is a method for hosting multiple domain names (with separate handling of each name) on a single server (or pool of servers)

In my workflow, I use the prefix 'local' to keep my local sites separate from real ones. So for a site called 'test-site', I would create the virtual host 'http://local.test-site'. This allows the site to act like it would if I pushed it to a live server.

Creating a Virtual Host

We'll need to modify a few configuration files to do this. So open the WAMP directory and navigate to:

C:\wamp\bin\apache\apache2.2.22\conf\

Open up httpd.conf, scroll to the bottom and uncomment the following line by removing the hash:

Include conf/extra/httpd-vhosts.conf

Now navigate to the extra folder and open up httpd-vhosts.conf

This file show be pre-populated with some dummy examples for you to use. Feel free to keep them, but I removed them. Add the following to create a new virtual host:

<VirtualHost *:80>
    DocumentRoot "c:/wamp/www/test-site"
    ServerName local.test-site
    <Directory "c:/wamp/www/test-site">
      Allow from all
    </Directory>
</VirtualHost>

Here, we are defining a new virtual host with the server name we want to use, the root of our site and the settings for this directory.

Now open up our machine host files, which can be found at C:\Windows\system32\drivers\etc\hosts.

This file keeps your host file entries. Here we tell the machine where to go if we request a certain URL. So here's an example of routing Google to our local host:

127.0.0.1       www.google.com

Every request made to the url 'www.google.com' from this machine will redirect it to the IP 127.0.0.1 (our localhost)

To route to our test site, we create a new host entry:

127.0.0.1       local.test-site

This will redirect any requests to http://local.test-site to our localhost, which will then make the test-site folder our default location.

You will find that there is already an entry for 'localhost'. Just add our new entry below this one.

Summary

Easy peesy. So whenever you add a new site, create a new virtual host by changing the server name and root location, then add the server name to your host entries.

Our final step is to restart the WAMP server. You can do this by clicking on the WAMP icon in the system tray and hitting 'Restart all services'

Note: All this switching between host files can get annoying, so if you use Sublime Text, here's a neat tip - LINK

Setting Up a WAMP Server on Windows

What you'll need:

  • A Windows machine

What is a WAMP server?

WAMP stands for Windows, Apache, MySQL and PHP and is a set of applications allowing a web server to run locally on a Windows machine. This makes build websites with server side content (PHP in our case) super easy.

This post, along with some others, is a guide to setting up a Linux server on your machine...

Installing WAMP

Firstly, we need to grab a copy of WAMP. Head over to the WampServer website, click the "start using WampServer" and download the correct version for you, depending on whether you're running a 32 or 64 bit version of Windows. (to see your version, right-click on 'My Computer' and find 'System Type'). I normally select 'WampServer (64 bits & PHP 5.4) 2.2E.

Install the program, leaving all settings as default.

When the install is finished, launch http://localhost in your browser. You may be greeted by a pleasant message saying "Forbidden - You don't have permission to access / on this server". Let's fix this.

By default, the server we created will deny all incoming connections, so we need to change this. Click on the WAMP icon in the system tray, hover over Apache then click httpd.conf. Open this file and search for:

<Directory "c:/wamp/www/">

Change this to Allow from all.

Now, when you go to http://localhost, you should see the WAMP homepage!

Creating A Site

Open the WAMP directory again, and go to www folder. This is the where all your sites are going to be kept.

You should already see a index.php file in here. Open that within your text editor, add some text, save and close. Now head back to your browser and refresh the page to see the change.

Create a new folder called test-site and within this copy the index.php file, delete everything in it and add some markup:

<h1>Welcome to Test-Site</h1>

Now go to http://localhost/test-site in your browser. As you can see, we have created a new website on our local server.

Note: If you are currently using Dropbox to sync projects across multiple machines, you can change the location of your Dropbox folder to the www folder. This will allow all your environments to sync automatically. (I have this setup on my work/home PC and laptop).

Summary

Stopping here is fine. You can work using this directory format, but things can get tricky with larger sites when it comes to htaccess and image/file paths (they did for me). So to combat this we create 'virtual hosts'. They allow you to point a custom URL to a certain project folder, i.e. http://local.test-site redirects to our test-site folder.

To read more about this, checkout this post on "How to Setup and Work with Virtual Hosts using WAMP Server"

Logo by: Seahawk Studios