Topics Covered in This JavaScript & jQuery Tutorial:
Building an Interactive Product Color Picker, Leveraging jQuery's Attr() Method for Dynamic Content, Implementing Visual State Changes with AddClass() and RemoveClass() Methods, Creating Responsive User Interactions with jQuery's Hover() Method
Required Skills and Setup
Visual Studio Code recommended for folder navigation and multi-file projects
Essential for debugging and testing jQuery functionality in real-time
Ability to identify elements by ID and class attributes for jQuery targeting
Understanding relative paths for image assets and script linking
Exercise Preview

Exercise Overview
Modern e-commerce demands intuitive product customization interfaces. When products are available in multiple variants, users expect seamless color selection with immediate visual feedback. In this hands-on exercise, you'll build a sophisticated product color picker using jQuery that responds to user interactions in real-time, switching product images dynamically based on color selection. This type of interactive component is essential for professional web applications and forms the foundation of more complex product configurators used by major retailers.
This exercise uses a chair product with 4 color variants: beige, blue, red, and yellow. Each color has corresponding image files and swatch elements with matching IDs for seamless integration.
Getting Started
- Launch your preferred code editor if it isn't already running.
- Close any open files to maintain a clean workspace.
- Navigate to the Product-Color-Chooser folder located in Desktop > Class Files > yourname-JavaScript jQuery Class. If you're using a modern editor like Visual Studio Code, WebStorm, or Sublime Text, open the entire folder as a project for better file management and IntelliSense support.
- Open product.html from the Product-Color-Chooser folder.
Preview product.html in Chrome (we'll leverage its Developer Tools for debugging later).
Examine the current interface: you'll see a large product photograph displaying a chair in its default color, accompanied by color swatches representing available variants. Currently, these swatches are non-functional—clicking them produces no response. Your objective is to transform these static elements into an interactive color selection system that updates the main product image in real-time.
- Keep the browser tab open for testing as we implement functionality.
- Return to your code editor to begin development.
- Starting on line 21, examine how each color swatch contains a unique ID corresponding to its color value. This semantic naming convention will be crucial for our dynamic image switching logic.
- On line 29, locate the img element with ID of product-photo—this is our target for dynamic updates.
Notice the product-photo's source file follows the naming convention chair-beige@2x.jpg. Our complete image library includes four high-resolution variants:
- chair-beige@2x.jpg
- chair-blue@2x.jpg
- chair-red@2x.jpg
- chair-yellow@2x.jpg
- Observe the strategic naming pattern: the color identifiers in the filenames (beige, blue, red, and yellow) precisely match the IDs assigned to their corresponding swatch elements. This consistency enables clean, maintainable code.
- We're now ready to implement the interactive functionality. jQuery remains a powerful choice for DOM manipulation in 2026, particularly for rapid prototyping and projects requiring broad browser compatibility. On line 32, note that we've already included the jQuery library and provided an empty script block for your implementation.
To ensure robust execution timing, we'll wrap our jQuery code in a document ready handler. This pattern guarantees that our scripts execute only after the DOM is fully constructed. Add the following structure:
<script) $(document).ready(function() { }); </script)
Initial Setup Process
File Organization
Navigate to Desktop > Class Files > yourname-JavaScript jQuery Class > Product-Color-Chooser folder and open in your code editor
Preview Setup
Open product.html in Chrome browser and test the current non-functional color swatches to understand the expected behavior
Code Structure Review
Examine the HTML structure, noting the swatch IDs (line 21) and product-photo element (line 29) that will be manipulated
jQuery Integration
Verify jQuery script linking on line 32 and add document ready function to ensure proper initialization
Image Asset Structure
Getting the Swatch Buttons to Work
Now we'll implement the core interaction logic that responds to user clicks and updates the product display accordingly.
Event handling forms the backbone of interactive web applications. Since each swatch shares the swatch class, we can attach a single event handler to all elements efficiently. Add the following event binding:
$(document).ready(function(){ $('.swatch').click(function(){ }); });The heart of our color picker lies in dynamically updating the product image's src attribute. jQuery's attr() method provides clean, readable syntax for attribute manipulation, accepting the target attribute name and new value as parameters.
Let's start with a simple test to verify our image-switching mechanism works. Add the following code:
$('.swatch').click(function(){ $('#product-photo').attr('src', 'img/chair-blue@2x.jpg'); });- Save the file and refresh your browser to test the initial implementation.
With the page currently displaying the beige chair, click any color swatch. The image should immediately switch to the blue variant, confirming our attribute manipulation works correctly.
This basic functionality proves our concept, but we need to make the system responsive to the specific color selected rather than always defaulting to blue.
The attr() method requires two parameters: the attribute name to modify and the new value to assign. This is fundamental for dynamic content updates.
Figuring Out Which Color the User Clicked on
Professional web applications require context-aware responses to user interactions. We'll implement dynamic color detection using jQuery's context handling capabilities.
- Return to your code editor for the next development phase.
- Examine line 22, where the yellow swatch receives an ID of yellow. JavaScript's this keyword, when wrapped in jQuery as
$(this), provides a reference to the specific element that triggered the current event—a fundamental pattern in event-driven programming. Let's investigate what information we can extract from the clicked element. Add this debugging code:
$('.swatch').click(function(){}); $('#product-photo').attr('src', 'img/chair-blue@2x.jpg'); console.log( $(this) ); });- Save and reload the page in Chrome.
- Open Chrome's Developer Console using Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows)—an essential tool for JavaScript debugging and development.
Click the yellow swatch and observe the complete element object logged to the console.
While seeing the full element confirms our event handling works, we need only the ID attribute to construct our dynamic image path.
- Switch back to your code editor.
Extract the specific attribute we need by chaining jQuery's
attr()method:$('.swatch').click(function(){ $('#product-photo').attr('src', 'img/chair-blue@2x.jpg'); console.log( $(this).attr('id') ); });- Save and refresh the page.
Test each color swatch and verify that only the ID value (beige, blue, red, or yellow) appears in the console—exactly the data we need for dynamic path construction.
Close the DevTools window.
Return to your code editor.
Now we'll implement the core dynamic functionality. Instead of hard-coding a specific image path, we'll construct it programmatically using string concatenation. In the file path img/chair-blue@2x.jpg, only the color segment needs to vary based on user selection.
Replace the static color reference with dynamic ID extraction:
$('.swatch').click(function(){ $('#product-photo').attr('src', 'img/chair-' + $(this).attr('id') + '@2x.jpg'); console.log( $(this).attr('id') ); });- Save and reload the page to test the complete functionality.
Click each color swatch systematically and verify that the product image updates to match your selection. This demonstrates the power of semantic naming conventions combined with dynamic content generation.
Element Identification Process
Using 'this' Keyword
Implement $(this) to reference the specific element that triggered the click event, enabling dynamic element targeting
Console Testing
Use Chrome DevTools Console (Cmd-Opt-J on Mac, Ctrl-Shift-J on Windows) to verify element selection and attribute extraction
ID Attribute Extraction
Apply .attr('id') method to retrieve the color identifier from the clicked swatch element
Dynamic Path Assembly
Construct image file paths using string concatenation with the extracted ID value for dynamic image switching
Always test your jQuery selectors in the browser console before implementing them in your code. This prevents runtime errors and ensures proper element targeting.
Change the Border Color of the Selected Element
Professional user interfaces provide clear visual feedback about the current state. We'll implement a selection indicator that moves dynamically as users make different color choices.
- Switch back to your code editor.
- Remove the console.log statement—debugging code should be cleaned up in production implementations.
jQuery's addClass() method provides elegant class manipulation for visual state changes. Add the selection indicator:
$('.swatch').click(function(){ $('#product-photo').attr('src', 'img/chair-' + $(this).attr('id') + '@2x.jpg'); $(this).addClass('selected'); });- Save and refresh your browser.
- Click the red swatch and observe that it receives the distinctive black border indicating selection.
- Click the blue swatch and notice a usability problem: while blue correctly receives the selection border, the previous selections (red and beige) retain their selection styling. This creates confusion about the current state.
We need to implement proper state management by clearing previous selections before applying new ones. Add the state reset logic:
$('.swatch').click(function(){ $('#product-photo').attr('src', 'img/chair-' + $(this).attr('id') + '@2x.jpg'); $('.swatch').removeClass('selected'); $(this).addClass('selected'); });Save and reload the page.
Test the complete interaction flow by clicking through all color options. You should see clean state transitions where only the currently selected swatch displays the selection border, while all others return to their default styling—the hallmark of professional interface design.
addClass vs removeClass Methods
| Feature | addClass() | removeClass() |
|---|---|---|
| Purpose | Add CSS class to element | Remove CSS class from element |
| Target Scope | Single element $(this) | All matching elements $('.swatch') |
| Use Case | Highlight selected state | Clear previous selections |
| Execution Order | Apply after removeClass | Execute before addClass |
Using Hover Instead of Click
Different interaction patterns serve different use cases. While click events work well for mobile-first designs, hover interactions can provide more immediate feedback in desktop environments—particularly useful for preview functionality.
- Switch back to your code editor.
jQuery's event system makes it trivial to experiment with different interaction models. Change the event trigger from click to hover:
$('.swatch').hover(function(){- Save and reload the page to test the alternative interaction model.
Move your cursor over different color swatches and observe the immediate image updates without requiring clicks.
The choice between click and hover depends on your specific use case and user experience goals. Hover provides immediate feedback and works well for preview functionality, while click events offer more deliberate selection behavior and better mobile compatibility. Many modern implementations use hover for previews and click for final selection.
For reference, you can examine our complete implementation in Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > Product-Color-Chooser.
Click vs Hover Event Handling
| Feature | Click Event | Hover Event |
|---|---|---|
| User Action | Deliberate click required | Mouse movement triggers |
| User Intent | Confirms selection | Previews option |
| Mobile Experience | Touch-friendly | Not available on touch devices |
| Implementation | .click(function(){}) | .hover(function(){}) |
Changing from click to hover requires only one word modification, demonstrating the power of well-structured jQuery event handling. This flexibility allows for rapid prototyping and A/B testing of user interactions.