A Simple Image Slider without jQuery

I’ve used jQuery since I began my web development career, but I sometimes feel like it makes life too easy. In the spirit of rejecting complacency, I wrote a simple JavaScript image slider without jQuery or other libraries.

You can find a demonstration of the image slider here, and the Github repo is here.

It was illuminating to see how much I take jQuery for granted. For example, I wanted to add a button to the page. jQuery makes this very easy:

container.append('<button>text</button>');

Without jQuery, however, you have to be a little more verbose:

var button = document.createElement('button');
button.innerHTML = 'text';
container.appendChild(button);

I wanted to add a wrapper element to my group of <img> tags. This is a breeze with jQuery:

outer.find('img').wrapAll('<div />')

Without jQuery, you have to flex your JavaScript muscles:

var wrapper = document.createElement('div');
var outer = document.getElementById('whatever');

var nodes = outer.childNodes;
var elementsWidth = 0;
for (var i = 0; i < nodes.length; i++) {
  if (nodes[i].nodeType === Node.ELEMENT_NODE
    && nodes[i].tagName === 'IMG'
  ) {
    elementsWidth += nodes[i].width;
    wrapper.appendChild(nodes[i]);
  }
}
outer.appendChild(wrapper);

I looked at jQuery’s source code after I finished the exercise to see how $.wrapAll was implemented, and unsurprisingly their implementation is very elegant. I think the average web developer can learn a lot from reading the jQuery source; for an excellent introduction, check out this screencast by Paul Irish.

This proved to be a fun and educational task, and it renewed my appreciation for jQuery’s simplicity and effectiveness. If you want to better understand the gifts jQuery gives you, I strongly recommend you try a little project without it.