[ /tiny/ki ]

Using Ki.js

ki.js and ki.extend.js provide a lot of jQuery's core functionality without all the bulk.

The layout for this site is used to be based on PureCSS, which implements some fairly impressive UI features without relying on too much Javascript. In particular, the Sidebar layout only uses a little bit of vanilla js to provide a responsive interface.

I love vanilla js, since in most situations you don't need a full UI library to pull off the few effects that you're actually going to use. Given that I've built this blog as a single page app, though, it made sense to get rid of the vanilla js in favour of the ki.js functions I'd already included.

What it was before

(function (window, document) {
  var layout=document.getElementById('layout'),
    menu=document.getElementById('menu'),
    menuLink=document.getElementById('menuLink');
  function toggleClass(element, className) {
    var classes=element.className.split(/\s+/),
      length=classes.length,
      i=0;
    for(; i < length; i++) {
      if (classes[i] === className) {
        classes.splice(i, 1);
        break;
      }
    }
    // The className is not found
      if (length === classes.length) {
        classes.push(className);
      }
      element.className = classes.join(' ');
  }
  menuLink.onclick = function (e) {
    var active = 'active';
    e.preventDefault();
    toggleClass(layout, active);
    toggleClass(menu, active);
    toggleClass(menuLink, active);
  };
}(this, this.document));

What it is now

(function(){
  var $layout=$('#layout'),
    $menu=$('#menu'),
    $menuLink=$('#menuLink');
  $menuLink.on('click',function(e){
    $.stop(e);
    $layout.toggleClass('active');
    $menu.toggleClass('active');
    $menuLink.toggleClass('active');
  });
})();

Functions I'm using

In that particular function, I'm only using ki's selector syntax, the on method, the stop method, and the toggleClass method. Elsewhere I use the html and attr methods.

Basic Ki functionality

In its most basic form, ki comes with a jQuery-like selector syntax. It can be used, like jQuery, to run some code once the document has loaded. Otherwise, it can be used to select elements by type, by class, or by id.

It would be trivial to implement a regex selector if you wanted something like that. Regular expressions are generally treated as though they are magic, though, so if you're not already using them, you likely won't find use cases for doing so.

var $div = $('div');

The base ki library comes with on, off, and each methods. If you need or want more than that, you can include parts of ki.extend.js.

Extended functions

  • $.addClass
  • $.removeClass
  • $.toggleClass
  • $.hasClass
  • $.append
  • $.prepend
  • $.hide
  • $.show
  • $.attr
  • $.removeAttr
  • $.hasAttr
  • $.before
  • $.after
  • $.css
  • $.first
  • $.last
  • $.get
  • $.text
  • $.html
  • $.parent
  • $.remove
  • $.trim
  • $.trigger
  • $.is
  • $.map
  • $.stop
  • $.param
  • $.ajax