It was designed to simplify the client-side scripting of HTML and is widely used, with installation on 65% of the top 10 million highest-trafficked sites on the web.
Before we begin, let’s make sure we’re all starting from the same place. The one prerequisite for this tutorial is access to a WordPress website with the ability to edit files. I don’t recommend experimenting on a live site, so please use a test installation or a local copy.
We have a couple of articles to help you set up a WordPress installation locally, this will make testing a lot faster since you won’t be reliant on your internet connection. If you’re a Windows user take a look at How to Install XAMPP and WordPress Locally on PC/Windows. If you’re on Linux or OSX head over to our articles How to Develop WordPress Locally with MAMP article. I personally prefer Vagrant, which can be used on either system but any of them will be fine for our purposes here.
Creating a Child Theme
Let’s use the default WordPress theme, Twenty Sixteen, for testing. Modifying the code of an existing theme is bad practice so we’ll create a child theme. Child themes inherit all their functionality from parent themes, except where specified.
Create a new directory in your themes folder named
jquery-test-theme. Create three files within:
functions.php. Add the following to the stylesheet and save it:
Add the following to the
functions.php and save it:
jQuery Without WordPress
WordPress loads jQuery for you but if you’re not working in WordPress you’ll need to include it yourself before any jQuery code you write. Head over to the jQuery website to grab a copy.
In this tutorial, we’ll be focusing on the first two. Let’s start with DOM traversal and manipulation.
Note: Usually jQuery allows you to use the
$ function. To make sure conflicts don’t happen WordPress uses safe mode which means you need to use
jQuery instead of the dollar sign. There are ways around this which we’ll discuss later
Finding Elements With jQuery Selectors
Adding a selector within a
jQuery() function will grab all instances of that element. We can use it to grab the theme’s header and recolor it. Write the following code in your
This should result in something similar to the rather ugly display below.
If you use a selector which matches multiple elements they will all be grabbed by jQuery so you can modify them all in one go.
A number of selectors can be used to fine-tune the elements you want to select. For example, you can use
:eq() to select an element with the given index from a section. Let’s only make the first widget’s title red.
:gt() selector selects elements with an index greater than the one given. Let’s recolor all widget titles after the third:
Indexes always start at 0 so 2 is actually the third element. Since we’re recoloring everything after the third element the first element to be recolored will actually be the fourth.
:not() selector removes an item from a selection. We can utilize it to recolor all titles except ones in category widgets.
Take a look at the full list of selectors on the jQuery documentation page.
WP Academy – WordPress Wisdom, Bitesized.
Structured e-learning to expand your WordPress and general business horizons. Learn from people like our very own CEO James Farmer with more than a decade’s experience running a WordPress Business!.
1.6 million WordPress Superheroes read and trust our blog. Join them and get daily posts delivered to your inbox - free!
Traversing the DOM
jQuery offers a bunch of functions that allow you to traverse the DOM. You start out from a selected DOM node and then use traversal functions to arrive at your final destination.
Let’s use some of these functions to recolor the widget titles using a different method.
Initially, we select
aside, which is the sidebar’s container. We then use the
children() function to grab all direct children of the node. In our case, these are section elements that contain the widgets. Finally, we use
find() to find elements with the given selector – h2 – and we recolor those.
Beware of how you select! Since we’re selecting all
h2 elements within the widget we might recolor titles that are contained within, not the widget title.
has() function can check for the existence of a selector within an element. We could use it to recolor the background of widgets that have a widget title. This would exclude the search widget, which has no title.
There are a number of useful traversal functions you can use to pinpoint elements exactly.
You can also remove, add or modify content on the page by using a few jQuery functions. The most basic way to add content is to select and element and use
text() to inject content into it.
html() treats the string you enter as HTML, Tags will be converted to the proper elements.
text treats the string as text, tags will not be converted but output as-is.
prepend() function can add content before and after the content contained within the selected element.
Modifying Properties and Styling Elements
You’ve already seen a bit of styling – I’ve used the
css() function in most of the code samples above. The function takes an object you can use to apply multiple CSS properties and values. Here’s an example that modifies post titles:
Note that CSS properties with dashes get converted to camel case so you should use
Awesome as that might look, it’s not really jQuery’s job to make things look nice – that falls under CSS’s purvey. If you really must add styles with jQuery, I recommend modifying class names instead and using your stylesheet to implement styles.
addClass() function adds the given class so we can then add the styles to our stylesheet instead. You can use
removeClass() to remove a class or
toggleClass() to toggle it.
To modify HTML attributes you’ll need the
attr() function. If used with one parameter it gets the attribute, if you used with two it sets the given attribute to the given value.
The first line returns the id of the given element. The second line modifies the ID to the one given.
Currently, this is possible, but I would need to look at the
id, remove the string “post-” and use the remainder as a numeric ID.
Information like this is often stored in a data attribute, it looks something like this:
<div class='post' id='post-8' data-id='8'></post>.
You can use
attr( 'data-id' ) to retrieve this value but jQuery has a shortcut: the
data() function. It works the same way as
attr(). If you give it a parameter like
id it will get the value from
Events in jQuery
Events allow you to respond to certain user actions. You could create a drop-down menu that opens on hover, implement a popup when the user reaches the bottom of the screen, and so on.
W3Schools has a list of commonly used jQuery events. We’ll take a look at how to implement one here.
The result of this function is an easter egg on your site. If the user double-clicks the masthead the text of the site description will change.
There are a few ways to attach events to elements. I favor this method because it will work even if the element is added after page load – this will be an issue when we look at AJAX in the next article.
on() function takes three arguments. The first one is the event to listen for, the second is the element to attach it to, the third is an anonymous function that performs a given action.
Toggling Widgets With jQuery
Let’s use what we’ve learned to create a simple widget toggle functionality without touching any code in theme files. We’ll prepend an element to the widget, which will toggle the widget contents on-click. We only need four lines of code!
The first line prepends a
span element with the class
toggle-widget to each widget. A click event is attached to this element. Within the anonymous function we use
jQuery(this) which refers to the actual element clicked.
This is different for each widget since each toggle span is a separate element. We find the element’s parent by traversing the DOM and then find all elements within the widget that are not the title or the toggle button and use the
toggle() function to toggle them. That’s it!
Practice, Practice, Practice!
At this point you know a lot of things about jQuery. You could create functionality, which would take the user to the article when any part of the excerpt is clicked, you could create selectable skins for your website and a lot more. I recommend practicing as much as possible .
In the next tutorial, we’ll take a look at how we can use jQuery and jQuery plugins in WordPress themes and plugins.