Wrapping an element in Vanilla JavaScript

This is more of a snippet for my own memory — but here is a function to wrap an element (or set of elements with any arbitrary text. jQuery’s solution works well, but there’s no need to include such a heavy library for this small requirement.

Additionally, there are many (many) solutions on StackOverflow — but all take special care to work in old browsers. This is a optimized for new browser support and speed:

 

See the Pen PwwmEb by Michael Jasper (@mdjasper) on CodePen.

Javascript Object – Next and Previous Keys

I often need to perform “next” and “previous” operations on standard JavaScript objects or JSON objects. There is no built-in functionality to do this, so here are some helper functions I’ve created to perform these basic operations:

There is a caveat: The EcmaScript specification doesn’t define an order in which keys are returned in an object — unlike an array. However, all modern browsers (as of Feburary 2014) do return them in the order they are supplied.

Functions with mock data and tests:

See the Pen object keys next and previous by Michael Jasper (@mdjasper) on CodePen.

Creating your own JavaScript Library – part 2 – Event Handling

write-your-own-javascript-libraryIn Part 1 of Creating your own JavaScript library, we cover the library essentials: library design, creating a solid object constructor, and adding functions by extending the object prototype. This post focuses on extending our basic library with event handling.

Out of the box event handling can be accessed  through Javascript and DOM apis, shown in the first 3 examples:

Simple event handling:

Assigning functions to events this way can be problematic, as only one function can be assigned at any given time. Mozilla Developer Network recommends that the addEventListener method be used instead, because of its flexibility.

Better Event handling

The addEventListener method accepts three parameters:

Assigning an anonymous function:

We can easily wrap this built in functionality with our library by creating a click function with a parameter that is passed to this native DOM event. This parameter will be an anonymous function (like the previous example) that will then bound to the element’s handler.

Handler wrapped by our library:

This pattern can be applied to any event natively exposed, such as:

  • onclick
  • onmouseover
  • blur
  • keydown

Non-standard or browser specific events

In the case where one browsers event api differs, it is simple to account for this in our event handler:

Optimizing our code

Instead of duplicating the addEventListener code in each event wrapper, we can optimize by creating an internal addListener(event, callback) function which will be called by other exposed functions, such as click, onMouseOver, etc

This separates the public wrapper from the internal event binding, allowing us to easily modify or expand the actual event binding code without modifying it in numerous places

 

Custom events system in JavaScript – LightEvents.js

Needing an event subscription and publishing system for a HTML5/canvas game I’m creating, I wrote a very light event system.

Anything than can call JavaScript (link, button, etc) can raise an event:

LightEvents.publishEvent('event name', data);

Subscribing to events is equally easy:

Here is the LightEvents object, demo is embedded below

JS Bin

Quick and reliable ad-rotator

In the course of my work, I’ve created and refined a simple ad rotator. It is built in JavaScript, and does not rely on any library, like jQuery, to function.  In my experience, it defeats ad-block, and loads easily on all mobile, tablet, and desktop browsers.

The rotator can be included multiple places on one page without any conflicts or collisions, so just drop-in where needed. Some coding is required to customize — basically copying and pasting your links and image urls, but nothing too heavy.

 

Interesting interview question #1

During an interview (for a software developer position) with a major employer in the state of Utah, I was asked an interesting programming question:

Create a function that, given an integer parameter, will return the middle three digits

I mentally wiped the sweat away from my forehead: whew — not computing bigO notation,  inventing a new search algorithm, or performing my favorite song!

I verbally walked through my thought process:

There will be a need for some looping to trim off the first and last digit of the integer each iteration — perhaps a while loop with the condition that the value is greater than 99? No, there is a better way: I’ll trim the digits recursively.

I asked for some feedback on my thought process, then set out writing some code. I came up with something like this:

“Nice solution,” the interviewer replied. “How will your function handle 4501?” Uh-oh: It will trim 4 and 1, and return 50. “Hmm… What about 40251?” Darn: It will trim 4 and 5, recursing on 025, which will be interpreted as 25 and fail.

So, as it turns out, programming questions in interviews might not be about creating the elegant, recursive solution — but about asking the right questions. Thorough requirements gathering.  Lesson learned.

After the interview, I couldn’t get the question out of my mind, and spent some time giving it a proper solution: handling input less than 999, error-ing on even values (finding the middle three of an even digit value is a somewhat undefined behavior), and polishing it off with some unit testing.

See a live version here

 

Installing WordPress on a Windows Server (not through Gallery)

I administer a Windows server which runs multiple instances of WordPress.  Today I needed to install another instance, but the Gallery Installer through IIS kept failing. I resorted to installing manually, and wrote up this guide to installing WordPress on a Windows server manually. Hopefully this is what you are looking for!

This guide makes two assumptions:

  1. PHP is already installed on your server (PHP Install Guide)
  2. MySql is already installed on your server (MySql Install Guide)

1. Download the latest stable release of WordPress

The latest release is available for download a http://www.wordpress.org/download. Choose the .zip package.

2. Extract the .zip file

Locate and extract the .zip file (named “wordpress-[versionnumber].zip” to the location of choice. Typically this will be in your “inetpub>wwwroot” directory. Rename the default folder “WordPress” to your site name.

3. Add site in IIS

In IIS, right click on your server name in the treeview, and choose “Add Web Site…”. Enter your site name and path into the Add Site window. The important inputs here are the path and site bindings (domain name).

4. Create & Configure Database

Open the MySql command line tool, and log in using the admin credentials. First create a new database for WordPress to use:

Next, add the admin user to the new database:

Note: this code does include the quote marks

5. Set up wp-config.php

Wp-config.php is the file that contains all the critical settings for WordPress including database connection information. Locate wp-config-sample.php and rename it to wp-config.php.

Open wp-config.php using your IDE of choice, and make the following changes:

6. Final Configuration

Browse to the new WordPress installation. If your domain is not already pointing to the site (bound in step 3), the easiest way to open your site is to add an entry to the windows hosts file. The hosts file is located at “Windows > system 32 > drivers > etc”, named “hosts.” Open this file using notepad (right click, run as administrator), and add the following entry

Once this is saved, browse to the new WordPress installation using your browser of choice, and follow the onscreen prompt to create a user, name your site, etc.

JavaScript Constructors

Due to the familiar syntax of JavaScript, it is easy for experienced developers to make blunders without knowing it. One common problem is crafting object constructors. With some simple knowledge and scope checks we can create well formed constructors that function as developers expect.

Because syntax and control structures look very similar in classic OOP languages (Java, C#) to JavaScript, it can be easy for experienced developers to jump-in, make progress, and then shoot themselves in the foot due to misunderstanding core differences in underlying language design.

One of those core differences is how functions can function as objects with constructors.

In a classic OOP language, a class,  constructor, and usage might look something like this:

Although the syntax is similar, doing something like this in JavaScript will land you in a bad place:

Scope

The first and most pressing issue is scope management.  Look back up the the JavaScript example — The function used in place of a class, is just that: a Function. Whereas a custom class is a datatype, a template for data, our function is a function in the same way as this is a function:

Primarily, the problem is with the scope of the this keyword with in functions.  Inside of a OOP language class, the this keyword refers to the parent object — the class that it is inside of. For example:

However, in side of a JavaScript function, the this keyword refers to the global scope, or the window object. Thus:

For the uninitiated, this can cause big problems. For example, consider:

A function/object Building, which contains the properties height, location, and occupancy, which are assigned like this: this.location = “123 N. 789 W.” Since the this keyword refers to the window object, your function has just overwritten window.location, the property used in changing the current location (url) of the page. Whoops!

But wait, there is a solution!

It is true, that a JavaScript object/function is really just a function — but you can create new instances of the function using the new keyword. Not only does the new keyword created a new instance (so you can have multiple objects of the same type on a page), but also assigns the scope of the this keyword to the function, NOT the window object. So, to use the previous example without clobbering the global scope:

However, if you have ever written a line of jQuery, you might be shaking your head in disagreement. Like you, I write something like this weekly:

So, how does that work?

To make sure that jQuery object is allways called with the new keyword, it does it for you, every time. See the jQuery source constructor:

So, each time $(“#asdf”) is used, jQuery returns a new jQuery.fn.init object. Now, keep in mind that this is one of several hundred lines within jQuery’s constructor source, but the key section for this subject. We can implement this method, with a few checks, in our code very easily.

Conclusion and template

So, to avoid clobbering the global scope, and to be convenient for implementers of your code, here is a well functioning JavaScript constructor template that can be implemented in your code:

See a demonstration of new keyword usage

JS Bin

Creating your own JavaScript Library

One of the phases I went through while learning about JavaScript was the intense desire to write my own library, similar to jQuery (but massively scaled down).

My library has gone through several major revisions — and more than one complete re-write, but now is exactly what I started out hoping it would be: functional, clean, small, and a solid learning experience.

I’d like to share what I learned from this project, and I hope you share back with me through the comments!

Finished project demo

Step 1: Identify the purpose of your library

This might just be one of the toughest parts of the whole process!  If you are to the point in your JavaScript knowledge that you would like to build your own library, than you’ve likely used jQuery, mooTools, Prototype, or any number of other popular libraries.  I use jQuery extensively in my projects, and know that it is very capable in many aspects, including: animation, user input validation, AJAX loading/submitting, event handling,  etc. Knowing this, it is tempting to have lofty goals for your own library. One piece of advice: Don’t. 

Pick one particular function, or aspect of web development/design that you would like your library to handle. Pick a niche need, and be happy with yourself when you fill it.

I decided my library would be a simple way to manipulate elements visually. At this point, I didn’t quite know how — but all you need is the kernel of the idea.

Step 2: Mock-up how would use the library

You always mock-up a webpage before you start building it right? Whether on paper, Photoshop, or even in code, it helps to pretend what the finished product will look like before you build it. It helps you to see obvious bugs, conflicts, and unwanted interactions you don’t catch when looking at the problem mentally.

Have you ever mocked-up your code?  Write some implementation, pretending that the class or object you are dealing with exists. Trust me, it will solve problems!

I want my library to do visual stuff with elements, and I like how jQuery looks. How about this?

Looking at my pretend implementation, I can see 1 problem and a hand-full of design implementation points.

The problem: $ as a function name is likely to conflict with lots of other libraries. Through some Googleing, I learn at StackOverflow that functions must start with a $ (dollar-sign) _ (underscore) or letters.

We can also tell some design patterns:

  • _ is the function name
  • _ must accept one or more parameters
  • _ should return itself so that a dot-operator will work
  • _ must control its scope so that we can have more than one _() on a page
  • dot-operator methods must also return the _ object for chaining

Step 3: Code up an outline

At this point, we know enough about the goal of our library, and how we will implement it, to begin outlining the structure of our library.

It may be useful for some (me) to review javascript function/object  prototyping.

Step 4: Fix-up the constructor

Now don’t try and run your code just yet: we have a pretty big scope issue (besides no functionality):

When our _() function returns this , it is actually returning the entire window, or the global scope.  Therefore, when we call _().toggle() , we are asking the browser to call the toggle() method which belongs to the window. Obviously this fails.

This problem can be solved by recursively creating another _ object using the new keyword.

What is the new keyword in JavaScript?

 

For an in-depth look at this problem, read more about JavaScript constructors

Next to implement in our constructor: making the _() represent an element with some bonus error prevention.

First, we create an about object that will be returned, if the implementation doesn’t specify an element id. Next, we check if the id parameter was sent, and then create a variable to contain that element.

Here is a final version of the _() constructor:

 

Step 5: Prototype method implementation

This step is pretty fun: being creative, and implementing what you want your library to actually do!

I mentioned earlier that I wanted my library to do some visual manipulation of elements. Make a list of what you want to do. I came up with the methods:

  • hide ()
  • show ()
  • bgcolor (color)
  • val (value)
  • toggle ()
  • size (height, width)

The depth of this step depends on the functionality of your library. Mine were rather trivial to implement:

 

Demo or download the finished library here

Part 2 – Event Handling

Final thoughts

Writing my own small library was a good way for me to learn about JavaScript. One of the great ways to learn more is to study the code of other libraries and see how they work.

Did you use this tutorial to create your own library? I would really like to hear about it. Please leave me a comment below.

Cheers!

Update
Stack Overflow user W3Geek asked a question about part of this tutorial. Visit his question: How do these pieces of code function exactly? His question is focused on Step 4 about the object constructor. User Leland Richardson does an excellent job explaining this further — I’d direct you to his thorough explanation rather than duplicating it here.

Convert < address > tags into Google Map link using jQuery

Relevant Stack Overflow Question

While designing a page template for a University today, I realized that there were many areas of the future pages that would include street addresses: buildings, conferences, offices, ect..  I thought, “Wouldn’t it be nice if these addresses were links to Google Maps?” Then people could easily find directions or set their phone GPS whilst driving (at a red light of course).

However, I quickly realized that in such a large institution as I am, that no faculty member would take the time to include a maps link.  As always, such wondering is the stuff of inspiration.  With a little bit of thought, I began writing a little jQuery function that could fulfill my dream.

code:

The function scans the entire webpage for instances of the <Address> tag:

And surrounds the address with a link to Google Maps:

Here is the jQuery Function:

Update: 11/27/2012 – Bug fix and code prettyfication.