0
(0)

Learning jQuery nowadays is like learning an old language that is loosing ground as the moment we speak. Bootstrap 5 removed it’s Jquery dependency, only WordPress themes are still fuelled with this library.

Type checks

The jQuery library was a big hit back in the days, since there were so many browser compatibility issues and this library had an out-of-box solution for each of them. Also each method has all kind’s of type checkings, that is one reason why this library pushes above 80kb.

append: function() {
   return domManip( this, arguments, function( elem ) {
      if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
      var target = manipulationTarget( this, elem );
      target.appendChild( elem );
      }
   } );
}

For example the append method checks if the node type provided by the coder is an ELEMENT, DOCUMENT OR DOCUMENT_FRAGMENT_NODE and only after this check, continues using a native javascript method called appendChild. If you would use vanilla javascript, you could simply use the appendChild() method directly(without the additional type checks).

The upside of jQuery methods are that they heavily reuse other already defined methods. In this case the manipulationTarget and domManip methods are reused to respect DRY(Don’t repeat yourself) principle.

The manipulationTarget method has another set of type checks:

function manipulationTarget( elem, content ) {
   if ( nodeName( elem, "table" ) &&
      nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {
      return jQuery( elem ).children( "tbody" )[ 0 ] || elem;
   }
   return elem;
}

All in all, Jquery does a lot of node type checks and if you are really curious how the source code looks like, you can always take a look in the source code viewer

Sizzle the selector library

Another major feature in jQuery is the Sizzle selector engine that does a fantastic job of selecting also classes, elements, ids. Sizzle was created in the days of document.getElementsByTagname and document.getElementById, so there were no getElementsByClassName and querySelectorAll methods available in that period of time. Sizzle works like the querySelector method or queryselectorAll method, but it supports also pseudo selectors from CSS and some additional methods:

$('*')   - universal selector
$('#header .nav-item li') - id, class and type selectors
$('nav li > a') - descendant and child selectors
$('[class*="box"]') - attribute selectors
$('div:first-child') - pseudo-classes
$(':lang(de)') - lang pseudo-class

The additional methods are these:

Ex: $('div:has(a)')
Ex: $('$("p:has(span | mark | a)")')
Ex: $('input:checkbox:checked')
Ex: $('.box, .box2')

:first and :last  (this is not first-child or last-child, but more like first-of-type, first-of-class)

:lt(), :gt() (these refer to their index/order, so if it's index is lower/greater then n)

 :eq(), :nth()  (these is the :nth-of-type or the not existing :nth-of-class)
:not() (exclusion of selectors)

:has() (parent selector checking html elements)
:contains() (parent selector checking text)
:radio, :checkbox, :file, :password, :submit, :text, :image, :reset, :button, :input, :checked, :enabled, :disabled, :selected

Their implementation is pretty straightforward:

file: function(elem) {
    return "file" === elem.type;
},
button: function(elem) {
   return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
},
input: function(elem) {
   return /input|select|textarea|button/i.test(elem.nodeName);
}

Even creating custom expressions is simple:

$.expr[':'].mailToLink = (obj) => {
    return obj.href.match(/^mailto\:/)
};

Now you can use the new expression this way:

$('a:mailToLink').addClass('mailTo');

There is a second argument in the $() method and that is the parent element:

$('p','#target')   //selects p tag if it's parent is a #target

If you want to take a look at Sizzle, you can do it here.

Extending jQuery methods a.k.a. creating plugins

jQuery gives the possibility to extend it’s own method list by your own defined function and in it’s core it is using the prototype method:

$.fn.visuallyHide = () => {
   return this.css({
      'clip': 'rect(0 0 0 0)';
      'clip-path': 'inset(50%)';
      'height': '1px';
      'overflow': 'hidden';
      'position': 'absolute';
      'white-space': 'nowrap';
      'width': '1px';
   })
}
$('#target').visuallyHide();

All this CSS style will be applied to the #target element. Also because we added the return key, you can chain the methods one after the other:

$('#target').visuallyHide().attr('aria-hidden',false).addClass('visibleForSR');

Already existing jQuery methods can be also extended. Below the attr() method gets an extra action(we add a class attributeApplied on the element):

const oldAttr = $.fn.attr;
$.fn.attr= function()
 {

   const ext= oldAttr.apply(this, arguments);
   ext.addClass('attributeApplied');
   return ext;
}
$('img').attr('title','hello'); 

Creating a plugin is not hard, we just need to add options for customizations and use the extend method:

$.fn.smartTooltip= function(options) {
   let settings = $.extend({
      title: 'Hello World',
      description: 'Lorem ipsum dolor',
      fullscreen: false,
      centered: true,
      darkTheme: false,
   }, options);  
   const dialog = $('<div class="tooltip" />');
  
   dialog.html(
     `
       <h2>${settings.title}</h2>
       <p>settings.description</p>
     `
   );
   return this.append(dialog);
}
$('div').smartTooltip();

jQuery has a great ecosystem, with a large amount of plugins both open-source and premium.

Ajax

$.ajax({
  url: "file.html",
}).done(function() {
    alert( "success" );
})
  .fail(function() {
    alert( "error" );
})
  .always(function() {
    alert( "complete" );
});

The new implementation of ajax method in jQuery is based on promises.

Effects and animations

$('div').fadeIn();
$('p').fadeOut();
$('.box').animate({
   opacity: 0.5,
   height: '500px'
}, 'slow')

Events

$('button').click(function() {
   alert('I am clicked');
});

$('.header-item').hover(function() {
   $(this).css('opacity', 1);
},
{
   $(this).css('opacity', .5);
}

Conclusions: In this article we discussed about main features of the good old jQuery, a Javascript library that was at it’s highest when we had to deal with browser issues in Internet explorer, Safari etc. The only reason it is still widely used is, that WordPress themes still use it. But it is already beginning to fall into oblivion slowly, because it does not serve our modern day’s web design criteria. Nowadays the SPA(single page application) is more likely to be preferred(kind of a mobile application type of desktop websites – no more waiting when switching pages). In the next article we will discuss about jQuery’s methods.

Image credits – Sizzle Vectors by Vecteezy

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Tagged in:

, , ,