Spinners and sliders with just native javascript

April 5th, 2012

In an earlier post we waved goodbye to jQuery UI for animations. CSS transform and transitions are more powerful, easier to maintain, hardware accelerated, and last but not least less code.

And you could save bandwidth by not loading jQuery UI.

And now I have rewritten the former example to drop jQuery, and believe it or not, it’s even less inline Javascript code. Sure the former example wasn’t really clever programmed – now we use event delegations – but it’s quiet astonishing that using native JS requires less code then the former jQuery example. And of course one library less to load.

Why can we drop jQuery in a lot of cases?

Because CSS animations aren’t working in old browsers anyway, so it doesn’t matter that don’t understand the latest HTML5/ECMA Script 5 / Javascript additions. That’s what graceful degradation means. No eye-candy for older browsers.

Important HTML5/ECMA Script 5 / Javascript additions:

  • classList api: easy toggling, adding and removing of classes.
  • document.querySelectorAll, the native selector API,  get you’re DOM elements like the way you do with CSS
  • new powerful array functions, like forEach etc.
  • even Microsoft products (Explorer 9) now support Javascript specs: like addEventListener, XMLHttpRequest,  javascript objects instead of ActiveX objects etc.
  • innerHTML, outerHTML
  • DOM traversal

Above list is not complete, but in most cases jQuery was used for things like, binding events, toggling classes, selecting elements, add elements, and ajaxify sites.

Here is the new example

And the used Javascript code:


(function(){
var spinner = document.getElementById("spinner"),i=null
spinner.addEventListener('click', function(event){
// event.preventDefault()
// event.stopPropagation()
// which element is the target
i = Array.prototype.indexOf.call(spinner.children, event.target);
// if(window.console) console.log(i,event)
switch(i){
case 1:
// clicked left, pop -> unshift
spinner.insertBefore(spinner.lastElementChild, spinner.firstElementChild)
break;
case 3:
// clicked right shift -> push
spinner.appendChild(spinner.firstElementChild)
break;
default:
}
// Opera bug workaround
spinner.classList.toggle('operabug')
}, false);
})()

Caveats

The Opera bug with DOM mutations and CSS transform/transitions isn’t resolved yet unfortunately. Somehow the DOM mutations don’t seem to trigger a reflow.

UPDATE: there is an easy fix for the Opera Bug, trigger a reflow by setting a bogus class on any element:

// Opera bug workaround
spinner.classList.toggle('operabug')

Comments are closed.