Convert jquery code to JavaScript

$('input').blur(function() {
  var $this = $(this);
  if ($this.val())
    $this.addClass('used'); 
  else
    $this.removeClass('used');
});

I won’t give you the whole answer because it is a bit lengthy but I will give you a few clues and I will tell you that by undertaking this exercise yourself you will learn invaluable things and possibly completely emancipate yourself from frameworks, which is a very valuable thing to do. I actually achieved that by porting all my code from jQuery to vanilla JavaScript and I’ll never ever be looking back. The code immediately looked much cleaner and easy to understand and I ended up having an epiphany about JavaScript :stuck_out_tongue:

Two of the main things jQuery became popular for is for its event standarisation and for its handy dom node selectors. The latter is no longer really relevant because nowadays all modern browsers support querySelector and querySelectorAll functions which do the same. The former will still need some srandarisation to make things consistent for all browsers.

The way to do what you want is to first create your own event functions which you will use throughout your applications such as addEventListener, removeEventListener, triggerEvent…
The mission of those functions is to standarise all the inconsistencies between browsers.

Secondly you will need to create the utility functions addClass and removeClass which likewise you will use throughout your web app. Those functions should take in a dom node element and the class string that you want to set like so:

function addClass (node, _class) {
	if (!(node instanceof HTMLElement)) {
		console.error("expecting a dom node");
		return;
	} 
	_class = sanitizeClass(_class);
	var attr = node.getAttribute('class')
	var classes = [];
	if (attr) {
		classes = sanitizeClass(attr).split(' ');
	}
	if (classes.indexOf(_class) === -1) {
		classes.push(_class);
		node.setAttribute('class', classes.join(' '));
	}
}

function sanitizeClass(str) {
    // this function removes any unnecessary extra spaces in the string
    return str.replace(/\s{2,}/g,' ');
}

So yeah, to sum things up the best way is to create your own small library that deals with these things and that you can then port to every project you work on.

4 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.