javascript posts page 2

Responsive: Turn Image Maps Into Selects

I’ve been doing quite a few responsive sites since I first started into them. I like doing them. They are fun to build, requiring new techniques and a different way of thinking to handle different situations. I like the concept and I like looking at the sites. One recent fun thing was dealing with an image map. Scaling the image and coordinates would be a pain and very expensive. An alternative option is to replace the image with a select drop down when the screen is too small for the image.

Breakpoint detection

I don’t remember where I found this method of dealing with breakpoints in JavaScript, but I’ve been setting the line height on the html tag with media queries and reading it with JavaScript to determine which breakpoint I’m in. This works with the ’em’ based breakpoints I use. I convert the numbers to more descriptive names, such as ‘small’, ‘medium’, and ‘large’. It looks something like this:

Continue reading post "Responsive: Turn Image Maps Into Selects"

TMLib meets Require JS

I’ve recently been working on reorganizing, cleaning up, and improving my javascript library, TMLib. This has included folder reorganization, source cleanup and normalization, a (so far crappy) build system, adding unit testing, a (mostly still unused) class system, etc.

My most recent effort has been to bring in the use of Require JS. Require is an AMD implementation, which is an interesting extension of the module pattern. It takes the dependency injection part of the module pattern (ie passing variables the module will use as arguments into the function expression) a step further by handling auto loading of those modules with a script loader that will asynchronously load and run all dependencies for a module before running the dependent module, injecting the dependencies as either parameters or assigned variables. Require does this with names based on file path, sort of like a JS equivalent of PSR-0. Require also provides a build process that will combine all required module files into one and minify. I have not played with this yet, but am hoping it will take over my currently crappy build process.

So far, I’ve only converted over a small core part of my library, but I really like the direction it is going. The scoping/dependency wrappers around each module may add some bulk, but will also allow minification of all module dependencies and what not, so it may end up being insignificant in the build, especially since my current build process doesn’t involve much minification. Even if it ends up a bit larger than it could be, the development benefits outweigh that concern for me. It has also required a change in the way I construct my library pieces. The early pieces require being constructed in a certain order, and things don’t work as well when modules to depend on each other. But I think it will be really nice when I get the full library converted over and the build process figured out.


JavaScript: Callable namespaces and other namespacing options

It is a good practice to not pollute the global “namespace” (ie window in browsers) when creating JavaScript code, especially if it is to be reusable, to avoid collisions with other bits of code that may be used on a page. It is common to use objects as namespaces. You can say window.myLibrary = {} and then add whatever you want to that object with confidence of no collisions with other libraries as long as myLibrary isn’t taken. Larger libraries will often have a namespacing function that will manage the creation of these namespaces, allowing them to be accessed if they already exist or created and then accesed if not, and easily handling multiple levels of depth. A simple example may look like the following:

namespace = function(_namespace, _scope){
    if(!_scope){
        _scope = window;
    }
    var _currentScope = _scope;
    var _identifiers = _namespace.split('.');
    for(var _i = 0; _i < _identifiers.length; ++_i){
        var _identifier = _identifiers[_i];
        if(!_currentScope[_identifier]){
            _currentScope[_identifier] = {};
        }
        _currentScope = _currentScope[_identifier];
    }
    return _currentScope;
}

Then you can do something like:

ns = namespace('myLibrary.mySubNameSpace');
jQuery.extend(ns, {
    'component1': function(){}
    ,'component2': function(){}
});

I’ve been doing the more manual approach for my library, but have been desiring for a while to get more organized and streamline repetition by adding my own namespace function. I got to thinking about doing more with the namespace objects, so that they can perform operations on themselves once created. For example, they might be able to create and return sub-namespaces as well as easily extend themselves.

Continue reading post "JavaScript: Callable namespaces and other namespacing options"

JQuery UI Droppable and Handling Multiple Draggable Types per Droppable

JQuery UI Draggable and Droppable make it fairly easy to implement dragondrop on a web page. There are some things that are not easy to do with it though. One example is having a droppable accept multiple types of draggables with different responses depending on type, especially when added at different times (for instance, being attached by separate objects/scripts). The way JQuery UI is set up, only one droppable behavior set can be attached to an element, so doing

element.droppable({accept: ".type1",...});
element.droppable({accept: ".type2",...});

simply replaces the “.type1” options with the “.type2” options.

In a recent project, I needed multiple draggable types per droppable, so I created an object class to handle adding a new “accept” type and associated events to an element that is already a droppable. I do this using duck punching to overwrite the original event callbacks. The wrapper callback checks the draggable element to see if it matches the new “accept” value. If so, it runs the new callback, otherwise it runs the original callback. Every time a new set of droppable options is applied, a new wrapper callback is created that calls the previous, so that no functionality is lost. Perhaps not as efficient as a single function with an if/switch tree, but that would not be feasible for this use case.

Continue reading post "JQuery UI Droppable and Handling Multiple Draggable Types per Droppable"

Animation queue management for jQuery

jQuery makes it fairly easy to animate DOM elements. Animating a single-step animation on one or more elements is simple with the call of the animate method. Multi-step animations can be more complex because animations are run asynchronously, meaning that they will start running when called but the script will continue onto the next step before the animation is done. For these, jQuery has the ability to queue steps. jQuery automatically queues multiple steps on a single object and dequeues as each completes, so you don’t have to worry about managing things and setting up callbacks. But for more complex animations where multiple elements are animated at different times or other functionality must be performed after an animation step, there is no automatic queuing.

A common practice for simple queuing is to use the “complete” parameter of the animate method or of other similar asynchronous methods that is a callback to be run when the animation is finished. This works nicely when there are a few steps. It becomes more unwieldy though the more steps you add. That is where queue comes in, allowing for adding of as many steps as you want without having to nest in callback after callback.

Continue reading post "Animation queue management for jQuery"

My Javascript Practices

It has been quite some time since I’ve posted anything, but I certainly haven’t stopped building websites. One thing I like to find out from other developers is how they do things so I can compare them with what I do and take anything that I like of theirs better, so I’m going to share some of my current practices. I’ll start with javascript, since I just built a javascript heavy site and want to share some more specific javascript stuff in later posts.

Base Library

To begin with, I use a namespace to store all of my javascript variables/objects in. This doesn’t pollute the “global” window object with many variables and drastically reduces the possibility of collisions with other libraries. Since javascript has no actual namespaces, but it does allow for generic objects and the ability to add arbitrary attributes and functions to them, I just create an object and add everything to it. I use “__” because it is small and quick to type, can’t really be given any meaning based on the name, and probably won’t be used by someone else.

The only other thing I put in the global namespace is the base object type I instantiate that variable with. I did this as an object so I could conceivably create multiple instances and so that I could declare it later in the file and have all of the site specific code at the top. I call it tmlib since it is my library. So a bare instantiation might look like this:

if(typeof __ === 'undefined') var __ = new tmlib;
__.cfg.whatever = "whatever";
__.scrOnload = function(){
    doSiteSpecificSomething();
}
/*----------
©tmlib
---------*/
function tmlib(){
        this.classes = {};
        this.lib = {};
        this.cfg = {};
    }
    tmlib.prototype.addListeners = function(argElements, argEvent, argFunction, argBubble){
        var fncBubble = (argBubble)?argBubble : false;
        if(!__.lib.isArray(argElements)) argElements = new Array(argElements);
        for(var i = 0; i < argElements.length; ++i){
            var forElement = argElements[i];
            if(forElement.attachEvent)
                forElement.attachEvent("on"+argEvent, argFunction);
            else
                forElement.addEventListener(argEvent, argFunction, fncBubble);
        }
    }
/*--init */
__.addListeners(window, "load", __.scrOnload, false);
Continue reading post "My Javascript Practices"

Javascript: Anchors in Dropdown Menus for Keyboard Access

My boss at work doesn’t like the top-level items that have submenus in our two-level menus to be links. In most of the sites we build, there is really no page for the top-level items to link to. Having a duplicated link to the first item or just a worthless value could be confusing, especially for both bots and screenreaders. But with no anchors, the submenus are inaccessible via the keyboard, as browsers generally only provide keyboard navigation to anchors, inputs, and buttons. As I prefer to keep my hands on the keyboard most of the time, I was disappointed with this characteristic of the menu system I built.

While building a vertical menu where the submenu drops down directly below the top-level items, I realized a solution to this issue. Anchors with no “href” attribute are fully valid, but they are interpreted much like spans and don’t receive keyboard focus or perform any actions on activation (barring event handlers of course). To a non-javascript agent, they are basically the same as the spans I would normally wrap around my top-level items. But for javascript users, I can simply add an href attribute to turn them into keyboard accessible items that can then activate the submenus. I use a worthless but descriptive value to tell users what the items do if they read their status bar. I prevent the default action anyway, but I still use a javascript qualifier to be sure and to describe the action, so the href looks like: “javascript://openMenu();”. This would do nothing if somehow the onclick event handler were not run. Like a good little javascripter, I attach event listeners programatically, of course. With jQuery, this would look something like:

elmsMenus.find("."+classTopitem).attr("href","javascript://openmenu();");

When I have time, I will have to update the horizontal menu that we use on many sites. In my vertical menu, I shall not that non-javascript users can still access the menus, because the default CSS displays them as opened. This is not the case for my horizontal menu script. I have yet to find a solution for this that will fit my bosses desires.


Javascript: Objects and Callbacks

I’ve been doing my JavaScript coding directly in objects. Before I had been doing them without objects, then modifying them if I had time, but now that I have experience with JS objects, it is much nicer to do the OO straight off. When making objects that are versatile, allowing multiple instances, it is often necessary to be able to perform different operations for different instances. As an example, you might create a single class to handle auto-suggest type functionality, and want it to do different things when you choose one of its suggestions or cancel for different instances of its use. In JS, you could either create forks in the parent class for each possible behavior and use a test to determine which behavior is appropriate, or you could create a callback on instance instantiation or in a function call. The callback method can be very versatile and clean, allowing you to leave alone the core class and modify the calling class or global call.

Continue reading post "Javascript: Objects and Callbacks"

Piwik and XHTML 5: Document.write and Noscript

I’ve been using Piwik recently for my site analytic purposes. I added it to my “professional” site, which is served as XHTML 5 for anything but IE. On that site, no visits were registering, though awstats showed that there were visitors. As it happens, this is because the javascript “document.write” is not allowed in XHTML. I believe older versions of XHTML still allowed it to be run, but it certainly wasn’t being run on my XHTML 5 site. Firefox showed an error in the console. This is mentioned on the WHATWG’s page about the differences between HTML5 and XHTML5.

The Piwik community doesn’t seem to have much mention of this, other than one mailing list thread. I modified the script to something similar to the one in that thread, like this:

Continue reading post "Piwik and XHTML 5: Document.write and Noscript"

David Hawkins: JQuery Image Reflections

The design of the gallery portion of the David Hawkins site I’m working on at Cogneato called for a reflection of the current image below that image. This could have been done by making reflections for each image in an image editor and then adding them to a separate field in the CMS. That would have been a pain and would require (most likely) us to be involved for each image added.

Luckily, since this site was already going to be using jQuery, I was able to find a jQuery plugin that handles the reflections automatically on page load. People without javascript just won’t get reflections. It works in modern browsers and IE 6-8. It is less than 2kB, which would be much smaller than even a single separate reflection image, though the now-more-bloated 72kB jQuery might ruin size benefits if we weren’t using it already. And as far as adding images to the site, the reflection is added automatically, well worth it.

Because of the design of the site, I had to modify the script somewhat to make it work properly. One issue was that I had a border around my images.

Continue reading post "David Hawkins: JQuery Image Reflections"