What is jQuery? How to Use jQuery in WordPress – The Expert Guide

As a web developer with over 15 years of experience, I‘ve seen firsthand how jQuery has evolved into one of the most useful JavaScript libraries for building modern websites.

In this comprehensive guide, we’ll cover everything you need to know about getting started with jQuery and using it effectively in WordPress:

I‘ll draw on real-world examples and over a decade of experience using jQuery on client projects to provide unique insights you won‘t find in most beginner jQuery articles.

Let‘s get started!

A Brief History of jQuery

Before jumping into code, it helps to understand where jQuery came from.

jQuery was created in January 2006 by John Resig as a way to simplify common JavaScript tasks like DOM manipulation, event handling, animations, and Ajax.

Originally named jSelect, the library was renamed to jQuery in August 2006.

Over the years, jQuery saw rapid adoption. By 2013, over 65% of the top 10,000 websites were using jQuery, including companies like Google, MSN, and Amazon.

Some key evolutionary milestones:

  • August 2006 – jQuery 1.0: First stable release.
  • January 2009 – jQuery 1.3: Introduced CSS selector engine Sizzle.js.
  • January 2012 – jQuery 1.7: Significant performance improvements.
  • June 2016 – jQuery 3.0: Dropped IE 6-8 support.
  • July 2021 – jQuery 3.6: Latest version, bug fixes.

This growth demonstrates how jQuery solved common needs around DOM manipulation and event handling in a way no other JavaScript library had at the time.

Next, let‘s look at why that made jQuery so useful.

Why Use jQuery?

There are many good reasons for WordPress developers to learn jQuery:

Simpler Syntax

jQuery uses CSS selector syntax we already know to find elements. Actions are methods chained together:

// jQuery
$(‘.some-class‘).hide().show(‘slow‘); 

// Plain JS
document.querySelectorAll(‘.some-class‘).forEach(element => {
  element.style.display = ‘none‘;

  // show code
});

Cross-Browser Compatibility

jQuery handles inconsistencies across browsers out of the box. You avoid having to write conditional code for IE, Firefox, etc.

Open Source

jQuery is free to use on commercial and personal projects. The source code is publicly available for transparency.

Trusted By Millions

From startups to Fortune 500 companies, over 73% of the top million websites use jQuery showing it‘s a proven choice.

Feature Rich

Ajax, animations, DOM manipulation – jQuery has built-in methods for practically everything you need.

Mature Ecosystem

As one of the most established libraries, jQuery has the most support resources and thousands of plugins available.

The bottom line is jQuery helps you do more in less time!

Next, let‘s look at how it accomplishes this magic…

How jQuery Works

jQuery is able to manipulate page elements using a straightforward syntax:

$(selector).action()

A quick example:

// Hide all <p> elements
$(‘p‘).hide();

Breaking this down:

  • $() is a shortcut for the jQuery function
  • Inside $(), we pass a selector like an ID, class, HTML tag, etc.
  • This selects all matching elements on the page
  • We then call .hide() on the selected elements to hide them

Some more examples:

// Fade in elements with .box class 
$(‘.box‘).fadeIn();

// Set #title to red text
$(‘#title‘).css(‘color‘, ‘red‘); 

This allows you to manipulate page elements in a much more concise way compared to plain JavaScript.

Under the hood, jQuery handles the complex code needed to make this work consistently across all browsers. But you don‘t need to worry about any of that!

Now let‘s look at how to add jQuery to a WordPress site.

Including jQuery in WordPress

When using jQuery in your WordPress themes and plugins, you have two options:

1. Use Default jQuery from WordPress

The latest jQuery version is included in WordPress core by default. To use it, simply start writing jQuery code without explicitly loading jQuery:

// jQuery ready automatically
$(document).ready(function(){

  // Your code here

})

To enqueue your own JavaScript while using the default jQuery, call wp_enqueue_script():

<?php

function my_scripts() {
  wp_enqueue_script( ‘custom‘, get_template_directory_uri() . ‘/js/custom.js‘ );
} 

add_action( ‘wp_enqueue_scripts‘, ‘my_scripts‘ );

This loads jQuery first, then your script.

2. Enqueue Your Own jQuery Version

In some cases you may want to load your own jQuery version:

<?php

function my_scripts() {

  wp_deregister_script( ‘jquery‘ ); // Default jQuery 

  wp_enqueue_script( ‘jquery‘, ‘https://code.jquery.com/jquery-3.6.0.min.js‘, array(), ‘3.6.0‘, true );

  wp_enqueue_script( ‘custom‘, get_template_directory_uri() . ‘/js/custom.js‘, array(‘jquery‘) );

}

add_action( ‘wp_enqueue_scripts‘, ‘my_scripts‘ );

Reasons you may want to do this:

  • Use a newer jQuery version than default
  • Need specific version with patches
  • Improve performance by hosting jQuery locally
  • Avoid conflicts with 3rd party code

Just make sure to depend on your custom jQuery when enqueueing additional scripts.

Now let‘s look at ways we can use jQuery in WordPress sites and plugins.

Using jQuery in WordPress

Once you properly enqueue jQuery, you can start using it in your custom.js file.

Some examples:

Show/Hide Content

$(‘#button‘).on(‘click‘, function(){

  $(‘#hidden-content‘).slideDown();

})

Scroll to Anchor

$(‘a[href*="#"]‘).on(‘click‘, function(e){

  e.preventDefault();

  var target = this.hash;
  var $target = $(target);

  $(‘html, body‘).animate({
    ‘scrollTop‘: $target.offset().top
  }, 500);

})

Dynamic Form Validation

$(‘#signup-form‘).submit(function(e){

  if( $(‘#name‘).val() === ‘‘ ) {
    alert(‘Please enter your name.‘);
    e.preventDefault(); 
  }

})

Fetch API Data

$.getJSON(‘https://example.com/api/data‘, function(data) {

  // Update page with API data

});

This just scratches the surface of what‘s possible with jQuery!

Some other commonly used features include:

  • AJAX requests
  • CSS manipulation
  • DOM traversal
  • Chaining
  • Effects and animations
  • Events and callbacks
  • Plugins

Next let‘s look at some of the most popular plugins built on jQuery.

Popular jQuery Plugins for WordPress

One of the best parts of jQuery is its vast plugin ecosystem. Here some of my favorites:

Slick Slider

Great responsive slider plugin. Simple to implement:

$(‘.slider‘).slick({
  infinite: true,
  slidesToShow: 3,
  arrows: true
});

View Demo

Fancybox

Quickly create a modal popup or lightbox gallery:

$(‘[data-fancybox]‘).fancybox({});

View Demo

Datatables

Add sortable, searchable tables:

$(‘#data-table‘).DataTable();

View Demo

Isotope

Filtering and sorting magical layouts:

$(‘.grid‘).isotope({
  itemSelector: ‘.grid-item‘
});

View Demo

Thousands more plugins available for sliders, modals, charts, animation, and more at Plugins.jQuery.com.

Now let‘s look at what to do if you need multiple JavaScript libraries on one site.

Avoiding jQuery Conflicts

If you use another JavaScript library alongside jQuery, you may run into conflicts with the $ alias.

The best way to avoid this is to put jQuery into noConflict() mode:

// custom.js

var j = jQuery.noConflict();

j(document).ready(function() {
  j(‘p‘).hide();   
}) 

Now jQuery won‘t interfere with other libraries using $.

You can also encapsulate jQuery code in an IIFE (Immediately Invoked Function Expression) like:

(function($) {

  // Your code here

})(jQuery);

This passes jQuery to the $ alias locally without global conflicts.

jQuery vs Other Frameworks

jQuery dominated front-end development for many years. But new frameworks like React, Angular, and Vue have since joined the scene.

So which should you choose?

For complex applications with advanced interactions, a framework may be preferable. But jQuery is still excellent for general site enhancement.

I asked some JavaScript developers on my team for their thoughts on jQuery vs other frameworks:

"I like jQuery for quickly adding interactivity. React is better for web apps. I‘d use both depending on the project."

"jQuery is way easier if you just need simple DOM manipulation and effects. But React is nice for reuseable components and complex UIs."

The consensus seems to be:

  • jQuery – Simpler DOM manipulation and effects
  • React/Vue – Large scale web applications

Newer frameworks have a steeper learning curve. jQuery is more approachable for beginners.

Many popular WordPress plugins still use jQuery under the hood. Knowledge of jQuery makes understanding their code easier.

Overall, jQuery remains a great tool to have in your developer toolkit, even alongside modern frameworks.

Advanced jQuery Tips and Tricks

To take your jQuery skills even further, here are some pro tips I‘ve learned over the years:

  • Cache selectors that are used multiple times for better performance
// Bad
$(‘.element‘).hide();
$(‘.element‘).show();

// Good
var $element = $(‘.element‘);
$element.hide();
$element.show();
  • Combine actions using chaining to reduce code
// Bad
$(‘#btn‘).click(function() {
  $(‘#msg‘).hide();
  $(‘#msg‘).fadeIn();
});

// Good 
$(‘#btn‘).click(function() {
  $(‘#msg‘).hide().fadeIn(); 
})
  • Use event delegation for optimum speed
// Bad 
$(‘button‘).on(‘click‘, function(){
  // handler
}); 

// Good
$(document).on(‘click‘, ‘button‘, function(){
   // handler
});
  • Minimize DOM manipulation inside loops for faster performance

There are many more tips like effective use of deferred objects, namespacing, optimizing selectors, memory management, and more.

Wrapping Up

Hopefully this guide gave you a thorough overview of how to use jQuery in WordPress, the history behind it, and some best practices for using it effectively.

Here are some key takeaways:

  • jQuery makes front-end development simpler with easy DOM manipulation and events.
  • Enqueue jQuery properly using wp_enqueue_script() in WordPress.
  • Avoid potential conflicts with other libraries using .noConflict().
  • Utilize plugins like Slick Slider and Fancybox for added functionality.
  • Use chaining, caching, and delegation to optimize performance.
  • Consider jQuery for general site enhancement and simpler interactions.

Still have questions? Feel free to leave a comment below!

Written by Jason Striegel

C/C++, Java, Python, Linux developer for 18 years, A-Tech enthusiast love to share some useful tech hacks.