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
From Idea to Prototype in Minutes: Claude Sonnet 3.5
From Idea to Prototype in Minutes: Claude Sonnet 3.5
Zain Zaidi
Essential Plugins for WordPress Developers: Top Picks for 2024
Essential Plugins for WordPress Developers: Top Picks for 2024
SitePoint Sponsors
WebAssembly vs JavaScript: A Comparison
WebAssembly vs JavaScript: A Comparison
Kaan Güner
The Functional Depth of Docker and Docker Compose
The Functional Depth of Docker and Docker Compose
Vultr
How Top HR Agencies Build Trust Through Logo Designs
How Top HR Agencies Build Trust Through Logo Designs
Evan Brown
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
SitePoint Sponsors
10 Artificial Intelligence APIs for Developers
10 Artificial Intelligence APIs for Developers
SitePoint Sponsors
The Ultimate Guide to Navigating SQL Server With SQLCMD
The Ultimate Guide to Navigating SQL Server With SQLCMD
Nisarg Upadhyay
Retrieval-augmented Generation: Revolution or Overpromise?
Retrieval-augmented Generation: Revolution or Overpromise?
Kateryna ReshetiloOlexandr Moklyak
How to Deploy Apache Airflow on Vultr Using Anaconda
How to Deploy Apache Airflow on Vultr Using Anaconda
Vultr
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Dave NearyAaron Williams
How to Create Content in WordPress with AI
How to Create Content in WordPress with AI
Çağdaş Dağ
A Beginner’s Guide to Setting Up a Project in Laravel
A Beginner’s Guide to Setting Up a Project in Laravel
Claudio Ribeiro
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Gitlab
Creating Fluid Typography with the CSS clamp() Function
Creating Fluid Typography with the CSS clamp() Function
Daine Mawer
Comparing Full Stack and Headless CMS Platforms
Comparing Full Stack and Headless CMS Platforms
Vultr
7 Easy Ways to Make a Magento 2 Website Faster
7 Easy Ways to Make a Magento 2 Website Faster
Konstantin Gerasimov
Powerful React Form Builders to Consider in 2024
Powerful React Form Builders to Consider in 2024
Femi Akinyemi
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Ralph Mason
Sending Email Using Node.js
Sending Email Using Node.js
Craig Buckler
Creating a Navbar in React
Creating a Navbar in React
Vidura Senevirathne
A Complete Guide to CSS Logical Properties, with Cheat Sheet
A Complete Guide to CSS Logical Properties, with Cheat Sheet
Ralph Mason
Using JSON Web Tokens with Node.js
Using JSON Web Tokens with Node.js
Lakindu Hewawasam
How to Build a Simple Web Server with Node.js
How to Build a Simple Web Server with Node.js
Chameera Dulanga
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Beloslava Petrova
Crafting Interactive Scatter Plots with Plotly
Crafting Interactive Scatter Plots with Plotly
Binara Prabhanga
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
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 10 Best WordPress AI Plugins of 2024
Top 10 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
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form