jQuery: Easy JavaScript for Designers

Share this article

If the rebirth of JavaScript has been the biggest theme of the past two years, you could probably divide most of the talk surrounding this topic into two main areas.

At the geekier end of town, we’ve seen smarties harnessing JavaScript to do all sorts of amazing — and occasionally ridiculous — things with Ajax.

However for front-end guys like myself, much of the scripting fizz and bubble has been focussed around refitting your markup — that is, using JavaScript to make your markup work better after it gets to the browser. Long-time readers of the Design View newsletter will probably remember a few of my own experiments along these lines over the past few years:

  • In Styling Images with the DOM, we used JavaScript to add rounded corners to images.
  • In DOM Text Shadows, we used JavaScript to build up a shadow on heading text.
  • In Horizontal Rulez! OK!, we used JavaScript to fix the dodgy hr element.

Although each of these scripts has quite a different purpose, they all involve sending neat, semantic markup to browsers, and using JavaScript either to fix or extend the abilities of those browsers that are smart enough to understand. In most cases, this involves “wrapping” some part of your markup in some more markup. Today we’re going to look at an easy, all-purpose method that will allow us to do this anytime, anywhere: jQuery.

So, What Is jQuery?

jQuery is yet another JavaScript library to join the already crowded space that includes Prototype, Scriptaculous, Rico, Moo.Fx and more than a dozen others. To use it, simply attach the .js file in the head of your page: magically, you have access to lots of pre-built functions and gizmos.

Q: Why would you possibly want another arcane JavaScript library to deal with?
A: The key attraction of jQuery is what it can offer you within the first 10 minutes of your using it.

A while back, we spent some time improving the way in which SitePoint’s Marketplace operates. While looking for an elegant way to allow sellers to display large screenshots, statistics, graphs and other images without leaving the main auction page, I came across Cody Lindley’s Thickbox, which is powered by John Resig’s jQuery JavaScript library. The image below shows the Thickbox in action.

Cody's Thickbox in action

After only five minutes of toying with Thickbox, you’ll begin to see its potential. In the Marketplace, I was able to pull both linked images and full HTML documents through to the Thickbox window, while simultaneously dimming (but not losing) the launch page. Users with browsers in which JavaScript is disabled or unavailable are simply taken directly to the item (that is, the image or page). It’s a very clever, usable, and accessible solution to the “enlarge this thumbnail” problem.

However, since we’d already decided to include the jQuery library in the page (it’s tiny — about 10kB), I thought it would be a good idea to find out what else it could do for us.

An hour later, I was a jQuery convert.

The true beauty of jQuery is its simplicity. Single lines of jQuery code can replace a dozen lines of normal JavaScript, yet it remains very elemental and flexible. Let me illustrate this point with an example. In my “horizontal rules fixer” from two years ago, we used the following script:

function fancyRules() {  
 if (!document.getElementsByTagName) return;  
   var hr = document.getElementsByTagName("hr");
 for (var i=0; i<hr.length; i++) {  
   var newhr = hr[i];  
   var wrapdiv = document.createElement('div');
   wrapdiv.className = 'line';  
   newhr.parentNode.replaceChild(wrapdiv, newhr);  
   wrapdiv.appendChild(newhr);  
 }  
}  

window.onload = fancyRules;

As a quick summary of this code, the browser waits for the page to finish loading before rifling through the DOM to locate each occurrence of hr. Each time it finds one, it creates a new div, gives it the class name “line”, inserts it where the hr was, and pops the old hr inside the new div, to achieve the markup required to implement this particular effect. Semantic pedantry aside, the end result of this script was that we were able to achieve the desired result without having to change hundreds of pages.

At the time, I thought it wasn’t a bad result for 12 lines of code. But let’s look at how we’d achieve the same result using jQuery.

$(document).ready(function(){ 
 $("hr").wrap("<div class='line'></div>");
});

I kid you not.

To break it down (not that there’s much to break):

$(document).ready(function(){ 
 ...
});

The first and third lines are jQuery’s load event, and they replace the old window.onload from above. Any task that we wish to complete during the loading of the page can be dropped inside these curly braces.

This is a great improvement on the old onload method, because rather than waiting until everything has finished loading, jQuery’s function watches everything that comes in, and starts working as soon as it has all the parts it needs. It’s really very neat.

Remarkably, the second line is even simpler:

  $("hr").wrap("<div class='line'></div>");

The “dollar object” — $("hr") — is all we need to tell jQuery to grab every horizontal rule on this page, and wrap is what we will be doing to those hr elements.

jQuery’s built-in wrap function takes in whatever HTML we give it (in this case "<div class='line'></div>") and wraps it around each hr in our page — no loops or tests required.

We’ve used a div here, but we could just as easily been modifying or wrapping a b, span, or a element.

And although we’ve used a very simple selection rule here (all hrs), we could have easily been much more specific with what we targeted. Using familiar old CSS syntax, we could have used any of the following:

  • $("hr.separate") — Get the hr elements with the class name "separate ".
  • $("li:only-child") — Get list items that are by themselves.
  • $("ul > li") — Get only list items with unordered parent lists.

While I’ve personally found wrap to be of the most instantly useful jQuery functions, it’s just one of many, including hide, show, fadeOut("slow") and slideUp("fast"), just to name a few. You can probably guess what each one of these functions does. The jQuery starter’s tutorial on the jQuery site is quite a gentle beginner’s guide, and takes you through some of the most common functions.

But perhaps jQuery’s single neatest feature is its ability to “chain” functions together. In other words, if I wanted to add a second div to our hr elements for some crazy reason, I could simply add another call to the wrap function to the end of my code, like this:

$("hr").wrap("<div></div>").wrap("<div></div>");

It’s so easy, it’s crazy. Crazy like a fox!

The Sell Your Site section of the Marketplace gives you another example of where this might come in handy, as demonstrated below.

Thumbnail images popping ou

When we were developing this page, I wanted to add a small icon to the bottom corner of each thumbnail. This required each img element to be wrapped in a container div, and another div showing the icon to be positioned in the container div.

Again, the jQuery code is just one line (I’ve split it here because we have limited column width to work with).

  $("#thumbnails li img") 
.wrap("<div class='wrap'></div>")
.before("<div class='thumb'></div>");

In plain English, this code simply asks jQuery to:

  • Find all the images in li elements that are inside #thumbnails.
  • Wrap these images in a div called "wrap".
  • Squeeze another div (the one with the icon graphic) in my "wrap" div just before my image.

Now that we have the structure, CSS does the rest.

Of course, if JavaScript is turned off, the thumbnails link directly to the raw image files, and there’s no need for the icons. Now that’s what I call elegant degradation.

Like most other JavaScript libraries, jQuery is capable of some very high-end tricks (we’ve covered its Ajax features in a previous article), but the biggest attraction for me was its ability to solve the little problems quickly and with a minimum of fuss.

As you can probably tell, I’m a big jQuery fan already. I hope you’ll find it useful too.

And of course, if you’re expanding your JavaScript horizons, don’t forget to upgrade to the latest version of Joe Hewitt’s Firebug extension, which is now the undisputed king of JavaScript debuggers.

This article was originally published in Design View #23.

Frequently Asked Questions about jQuery and JavaScript for Designers

What is the difference between jQuery and JavaScript?

JavaScript is a programming language that allows you to implement complex features on web pages. jQuery, on the other hand, is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, and animation much simpler with an easy-to-use API that works across a multitude of browsers. Essentially, jQuery is a set of JavaScript libraries designed to simplify HTML document traversing, event handling, and animating.

How can I start using jQuery in my projects?

To start using jQuery, you need to include the jQuery library in your project. You can download it from the official jQuery website or include it directly from a Content Delivery Network (CDN). Once the library is included in your project, you can start using jQuery functions by using the $ sign followed by a selector (to select HTML elements) and a jQuery action (to perform on the selected elements).

What are some common uses of jQuery for web designers?

jQuery is commonly used for a variety of tasks in web design, including manipulating HTML elements, handling events (like clicks or mouse movements), creating animations, and making AJAX calls to retrieve or send data to a server. It’s also used to create interactive features like image sliders, form validations, and dynamic content loading.

How does jQuery simplify working with JavaScript?

jQuery simplifies JavaScript by providing easy-to-use APIs for common web tasks, abstracting away complex JavaScript functionality. It also handles a lot of cross-browser compatibility issues that can arise when writing raw JavaScript, making your code easier to write and maintain.

Can I use jQuery with other JavaScript libraries?

Yes, jQuery can be used alongside other JavaScript libraries. It provides a feature called noConflict mode, which allows you to use jQuery with other libraries that also use the $ symbol.

What are some resources for learning jQuery?

There are many resources available for learning jQuery. The official jQuery website provides comprehensive documentation and tutorials. Other online platforms like Codecademy, Udemy, and Khan Academy also offer courses on jQuery.

How can I debug jQuery code?

Debugging jQuery code is similar to debugging JavaScript. You can use the browser’s developer tools to inspect elements, view console logs, and step through your code. Additionally, jQuery provides a few methods like .error(), .fail(), and .done() to handle errors and exceptions.

What are some best practices when using jQuery?

Some best practices when using jQuery include: using the latest version of jQuery, leveraging its chaining capabilities, using the document ready function to ensure all elements are loaded before your code runs, and using the jQuery CDN for faster loading times.

How can I optimize my jQuery code for better performance?

There are several ways to optimize your jQuery code for better performance. These include: minimizing DOM manipulation, using ID selectors instead of class selectors, caching jQuery objects, and using the .on() method for event binding.

Can I use jQuery for mobile web development?

Yes, jQuery has a specific library for mobile web development called jQuery Mobile. It provides a unified, HTML5-based user interface system for all popular mobile device platforms.

Alex WalkerAlex Walker
View Author

Alex has been doing cruel and unusual things to CSS since 2001. He is the lead front-end design and dev for SitePoint and one-time SitePoint's Design and UX editor with over 150+ newsletter written. Co-author of The Principles of Beautiful Web Design. Now Alex is involved in the planning, development, production, and marketing of a huge range of printed and online products and references. He has designed over 60+ of SitePoint's book covers.

Share this article
Read Next
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
5 jQuery.each() Function Examples
5 jQuery.each() Function Examples
Florian RapplJames Hibbard
Implementing User Authentication in React Apps with Appwrite
Implementing User Authentication in React Apps with Appwrite
Yemi Ojedapo
AI-Powered Search Engine With Milvus Vector Database on Vultr
AI-Powered Search Engine With Milvus Vector Database on Vultr
Vultr
Understanding Signals in Django
Understanding Signals in Django
Kabaki Antony
Why React Icons May Be the Only Icon Library You Need
Why React Icons May Be the Only Icon Library You Need
Zain Zaidi
View Transitions in Astro
View Transitions in Astro
Tamas Piros
Getting Started with Content Collections in Astro
Getting Started with Content Collections in Astro
Tamas Piros
What Does the Java Virtual Machine Do All Day?
What Does the Java Virtual Machine Do All Day?
Peter Kessler
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Mayank Singh
Layouts in Astro
Layouts in Astro
Tamas Piros
.NET 8: Blazor Render Modes Explained
.NET 8: Blazor Render Modes Explained
Peter De Tender
Mastering Node CSV
Mastering Node CSV
Dianne Pena
A Beginner’s Guide to SvelteKit
A Beginner’s Guide to SvelteKit
Erik KückelheimSimon Holthausen
Brighten Up Your Astro Site with KwesForms and Rive
Brighten Up Your Astro Site with KwesForms and Rive
Paul Scanlon
Which Programming Language Should I Learn First in 2024?
Which Programming Language Should I Learn First in 2024?
Joel Falconer
Managing PHP Versions with Laravel Herd
Managing PHP Versions with Laravel Herd
Dianne Pena
Accelerating the Cloud: The Final Steps
Accelerating the Cloud: The Final Steps
Dave Neary
An Alphebetized List of MIME Types
An Alphebetized List of MIME Types
Dianne Pena
The Best PHP Frameworks for 2024
The Best PHP Frameworks for 2024
Claudio Ribeiro
11 Best WordPress Themes for Developers & Designers in 2024
11 Best WordPress Themes for Developers & Designers in 2024
SitePoint Sponsors
Top 9 Best WordPress AI Plugins of 2024
Top 9 Best WordPress AI Plugins of 2024
Dianne Pena
20+ Tools for Node.js Development in 2024
20+ Tools for Node.js Development in 2024
Dianne Pena
The Best Figma Plugins to Enhance Your Design Workflow in 2024
The Best Figma Plugins to Enhance Your Design Workflow in 2024
Dianne Pena
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Christopher Collins
Build Your Own AI Tools in Python Using the OpenAI API
Build Your Own AI Tools in Python Using the OpenAI API
Zain Zaidi
The Best React Chart Libraries for Data Visualization in 2024
The Best React Chart Libraries for Data Visualization in 2024
Dianne Pena
7 Free AI Logo Generators to Get Started
7 Free AI Logo Generators to Get Started
Zain Zaidi
Turn Your Vue App into an Offline-ready Progressive Web App
Turn Your Vue App into an Offline-ready Progressive Web App
Imran Alam
Clean Architecture: Theming with Tailwind and CSS Variables
Clean Architecture: Theming with Tailwind and CSS Variables
Emmanuel Onyeyaforo
How to Analyze Large Text Datasets with LangChain and Python
How to Analyze Large Text Datasets with LangChain and Python
Matt Nikonorov
6 Techniques for Conditional Rendering in React, with Examples
6 Techniques for Conditional Rendering in React, with Examples
Yemi Ojedapo
Introducing STRICH: Barcode Scanning for Web Apps
Introducing STRICH: Barcode Scanning for Web Apps
Alex Suzuki
Using Nodemon and Watch in Node.js for Live Restarts
Using Nodemon and Watch in Node.js for Live Restarts
Craig Buckler
Task Automation and Debugging with AI-Powered Tools
Task Automation and Debugging with AI-Powered Tools
Timi Omoyeni
Quick Tip: Understanding React Tooltip
Quick Tip: Understanding React Tooltip
Dianne Pena
12 Outstanding AI Tools that Enhance Efficiency & Productivity
12 Outstanding AI Tools that Enhance Efficiency & Productivity
Ilija Sekulov
React Performance Optimization
React Performance Optimization
Blessing Ene Anyebe
Introducing Chatbots and Large Language Models (LLMs)
Introducing Chatbots and Large Language Models (LLMs)
Timi Omoyeni
Migrate to Ampere on OCI with Heterogeneous Kubernetes Clusters
Migrate to Ampere on OCI with Heterogeneous Kubernetes Clusters
Ampere Computing
Scale Your React App with Storybook and Chromatic
Scale Your React App with Storybook and Chromatic
Daine Mawer
10 Tips for Implementing Webflow On-page SEO
10 Tips for Implementing Webflow On-page SEO
Milan Vracar
Create Dynamic Web Experiences with Interactive SVG Animations
Create Dynamic Web Experiences with Interactive SVG Animations
Patricia Egyed
5 React Architecture Best Practices for 2024
5 React Architecture Best Practices for 2024
Sebastian Deutsch
How to Create Animated GIFs from GSAP Animations
How to Create Animated GIFs from GSAP Animations
Paul Scanlon
Aligning Teams for Effective User Onboarding Success
Aligning Teams for Effective User Onboarding Success
Himanshu Sharma
How to use the File System in Node.js
How to use the File System in Node.js
Craig Buckler
Laravel vs CodeIgniter: A Comprehensive Comparison
Laravel vs CodeIgniter: A Comprehensive Comparison
Dianne Pena
Essential Tips and Tricks for Coding HTML Emails
Essential Tips and Tricks for Coding HTML Emails
Rémi Parmentier
How to Create a Sortable and Filterable Table in React
How to Create a Sortable and Filterable Table in React
Ferenc Almasi
WooCommerce vs Wix: Which Is Best for Your Next Online Store
WooCommerce vs Wix: Which Is Best for Your Next Online Store
Priyanka Prajapati
GCC Guide for Ampere Processors
GCC Guide for Ampere Processors
John O’Neill
Navigating Data Management: Warehouses, Lakes and Lakehouses
Navigating Data Management: Warehouses, Lakes and Lakehouses
Leonid Chashnikov
Integrating MongoDB with Node.js
Integrating MongoDB with Node.js
Dianne Pena
How to Use Node.js with Docker
How to Use Node.js with Docker
Craig Buckler
4 Reasons Why You Should Join A Freelancing Community
4 Reasons Why You Should Join A Freelancing Community
Kyle Prinsloo
ChatGPT vs AutoGPT: Comparing Top Language Models
ChatGPT vs AutoGPT: Comparing Top Language Models
Dianne Pena
How to Perform User Authentication with Flask-Login
How to Perform User Authentication with Flask-Login
Yemi Ojedapo
BERT vs LLM: A Comparison
BERT vs LLM: A Comparison
Dianne Pena
Monitoring Your Python App with AppSignal
Monitoring Your Python App with AppSignal
Connor James
BabyAGI vs AutoGPT: A Comprehensive Comparison
BabyAGI vs AutoGPT: A Comprehensive Comparison
Dianne Pena
Top Redux Alternatives: Exploring State Management Solutions
Top Redux Alternatives: Exploring State Management Solutions
Dianne Pena
Code Migration: Ampere Porting Advisor for x86 to AAarch64
Code Migration: Ampere Porting Advisor for x86 to AAarch64
Pete Baker
React Router v6: A Beginner’s Guide
React Router v6: A Beginner’s Guide
James Hibbard
Get the freshest news and resources for developers, designers and digital creators in your inbox each week