Will the real DOM manipulator 

please stand up




@benhowdle
http://benhowdle.im




jQuery

the best thing since JavaScript

the DOM API and XHR requests in IE






From this

function getElementsByClass(searchClass,node,tag) {

	var classElements = new Array();

	if ( node == null )

		node = document;

	if ( tag == null )

		tag = '*';

	var els = node.getElementsByTagName(tag);

	var elsLen = els.length;

	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");

	for (i = 0, j = 0; i < elsLen; i++) {

		if ( pattern.test(els[i].className) ) {

			classElements[j] = els[i];

			j++;

		}

	}

	return classElements;

}



to this

 $('.myClass').doStuff(); 


Using jQuery for like...everything



Standing on our own



Let's talk browser support



  • know your audience/stats

  • communicate like a human

  • users vs developers -> people

Selecting stuff


querySelector and querySelectorAll

var el = document.querySelector('#mySingleElement');console.log(el); // <div id=​"mySingleElement">​</div>​
var els = document.querySelectorAll('.els');console.log(els); // [div.els, div.els]

Looping stuff


decrementing while loop

var elsL = els.length;while(elsL--){    console.log(els[elsL]); // cool, but lets use array functions});

forEach?

els.forEach(function(el){    console.log(el); // ace?});

Looping stuff


Not quite...

Uncaught TypeError: Object #<NodeList> has no method 'forEach'



Looping stuff


"Arrays. Lots of arrays" - Neo





var _each = Array.prototype.forEach;
_each.call(els, function(el){
    console.log(el); // <div class="els"></div>
});

Event listeners


jQuery
$('.els').on('click', function(){
    $(this).hide();
});

JavaScript
_each.call(els, function(el){
el.addEventListener('click', function(){ this.style.display = 'none'; });});

Managing classes


jQuery
$('.els').on('click', function(){
    $(this).addClass('danger');});

JavaScript
_each.call(els, function(el){
el.addEventListener('click', function(){ this.classList.add('danger', 'foo'); this.classList.remove('alert'); this.classList.toggle('show');
});});

AJAX


Old, horrendous JavaScript way

var xhr;
if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
} else {
    try {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            xhr = false;
        }
    }
}


AJAX


jQuery

$.ajax({    url: '/api/users/',    type: 'POST',    data: {        name: 'eduardo saverin',        job: 'CFO'    },    success: function(user){        console.log(user);    }});

AJAX


Nice, concise way

var xhr = new XMLHttpRequest();xhr.open('POST', '/api/users/', true);xhr.send({    name: 'eduardo saverin',    job: 'CFO'});xhr.onreadystatechange = function(){    if(xhr.readyState == 4){        console.log(xhr.responseText);    }}

AJAX


Another-JavaScript-AJAX-thingy-that's-not-so-horrible:

File Uploading

document.querySelector('#file-input').addEventListener('change', function(){    var file = this.files[0];    var formData = new FormData();    formData.append('file', file);        var xhr = new XMLHttpRequest;    xhr.open('POST', '/fileProcessor', true);    xhr.send(formData);});

Like, real use case stuff


Animating some tiles with jQuery

function setAnimationDelay() {    $( ".square" ).each(function( index ) {        var intValue = $(this).attr('data-anim-int')*1000;        $(this).text(intValue);        var el = this;
setInterval(function() { $(el).toggleClass('active'); },intValue); });}
setAnimationDelay();

Like, real use case stuff


Animating some tiles with JavaScript (OMG SAME LINE COUNT BRO)

var _each = Array.prototype.forEach;
function setAnimationDelay(){ _.each.call(document.querySelectorAll('.square'), function(el){ var intValue = el.getAttribute('data-anim-int') * 1000; el.innerHTML = intValue; setInterval(function(){ el.classList.toggle('active'); }, intValue); });}
setAnimationDelay();

This is all great, but like...why?


Constraints
It's easy to write unoptimised jQuery (* I have this in production)
$('.myEls').each(function(){    $(this).click(function(){        $('#myEl').addClass('danger').not(':first-child').slideDown();        $('#myEl').removeClass('success').not(':first-child').slideUp();
$('#myEl').fadeIn('slow').not(':last-child').fadeOut();
});});




Imagine trying to write all that in JavaScript?





This is all great, but like...why...again?


Reinventing the wheel?

Moment.js = Abstracts a specific part of JavaScript
jQuery = Covers a large part of JS, ie. loops -> control flow



With jQuery, I feel like I'm always "prototyping".


With JavaScript, it feels more like writing software.

In it's defence: jQuery is the balls

  • Performant
  • Tested to the hilt
  • Excellent community
  • PLUGINS
  • Low barrier to entry

When is it appropriate?



  • When you're shimming too much

  • When you *have* to support older browsers

  • Prototyping

Most excellent resources




That's all folks!


Will the real DOM manipulator please stand up

By benhowdle89

Will the real DOM manipulator please stand up

  • 3,789