Skip to main content
April 1, 2026Dan Rodney/7 min read

Product Color Chooser

Master Interactive Product Selection with jQuery

Tutorial Learning Objectives

jQuery Methods Mastery

Learn to use attr(), addClass(), removeClass(), and hover() methods for dynamic element manipulation. These core methods form the foundation of interactive web interfaces.

Product Color Selection

Build a fully functional color picker that updates product images based on user selection. Perfect for e-commerce and product showcase applications.

Event Handling

Master click and hover event handling to create responsive user interfaces. Understand when to use each interaction type for optimal user experience.

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

0/4

Exercise Preview

ex prev color picker

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.

Project Structure Overview

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

  1. Launch your preferred code editor if it isn't already running.
  2. Close any open files to maintain a clean workspace.
  3. 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.
  4. Open product.html from the Product-Color-Chooser folder.
  5. 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.

  6. Keep the browser tab open for testing as we implement functionality.
  7. Return to your code editor to begin development.
  8. 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.
  9. On line 29, locate the img element with ID of product-photo—this is our target for dynamic updates.
  10. 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
  11. 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.
  12. 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.
  13. 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

1

File Organization

Navigate to Desktop > Class Files > yourname-JavaScript jQuery Class > Product-Color-Chooser folder and open in your code editor

2

Preview Setup

Open product.html in Chrome browser and test the current non-functional color swatches to understand the expected behavior

3

Code Structure Review

Examine the HTML structure, noting the swatch IDs (line 21) and product-photo element (line 29) that will be manipulated

4

jQuery Integration

Verify jQuery script linking on line 32 and add document ready function to ensure proper initialization

Image Asset Structure

chair-beige@2x.jpg25%
chair-blue@2x.jpg25%
chair-red@2x.jpg25%
chair-yellow@2x.jpg25%

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.

  1. 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(){
    
       });
    });
  2. 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');
    });
  3. Save the file and refresh your browser to test the initial implementation.
  4. 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.

jQuery attr() Method Usage

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.

  1. Return to your code editor for the next development phase.
  2. 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.
  3. 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) );
    });
  4. Save and reload the page in Chrome.
  5. Open Chrome's Developer Console using Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows)—an essential tool for JavaScript debugging and development.
  6. 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.

  7. Switch back to your code editor.
  8. 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') );
    });
  9. Save and refresh the page.
  10. 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.

  11. Close the DevTools window.

  12. Return to your code editor.

  13. 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') );
    });
  14. Save and reload the page to test the complete functionality.
  15. 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

1

Using 'this' Keyword

Implement $(this) to reference the specific element that triggered the click event, enabling dynamic element targeting

2

Console Testing

Use Chrome DevTools Console (Cmd-Opt-J on Mac, Ctrl-Shift-J on Windows) to verify element selection and attribute extraction

3

ID Attribute Extraction

Apply .attr('id') method to retrieve the color identifier from the clicked swatch element

4

Dynamic Path Assembly

Construct image file paths using string concatenation with the extracted ID value for dynamic image switching

DevTools Debugging

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.

  1. Switch back to your code editor.
  2. Remove the console.log statement—debugging code should be cleaned up in production implementations.
  3. 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');
    });
  4. Save and refresh your browser.
  5. Click the red swatch and observe that it receives the distinctive black border indicating selection.
  6. 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.
  7. 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');
       });
  8. 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

FeatureaddClass()removeClass()
PurposeAdd CSS class to elementRemove CSS class from element
Target ScopeSingle element $(this)All matching elements $('.swatch')
Use CaseHighlight selected stateClear previous selections
Execution OrderApply after removeClassExecute before addClass
Recommended: Always remove existing classes before adding new ones to prevent multiple selections

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.

  1. Switch back to your code editor.
  2. jQuery's event system makes it trivial to experiment with different interaction models. Change the event trigger from click to hover:

    $('.swatch').hover(function(){
  3. Save and reload the page to test the alternative interaction model.
  4. 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

FeatureClick EventHover Event
User ActionDeliberate click requiredMouse movement triggers
User IntentConfirms selectionPreviews option
Mobile ExperienceTouch-friendlyNot available on touch devices
Implementation.click(function(){}).hover(function(){})
Recommended: Use click for final selections, hover for preview functionality on desktop interfaces
Code Flexibility Achievement

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.

Key Takeaways

1jQuery's attr() method enables dynamic modification of HTML attributes, essential for changing image sources and other element properties based on user interactions
2The 'this' keyword in jQuery event handlers refers to the specific element that triggered the event, allowing for targeted manipulation of individual elements within a collection
3Combining addClass() and removeClass() methods creates smooth state transitions, with removeClass() clearing previous selections before addClass() applies new styling
4String concatenation with jQuery attribute values enables dynamic file path construction, making code reusable across multiple similar elements with consistent naming conventions
5Event type selection significantly impacts user experience - click events require deliberate action while hover events provide immediate visual feedback for exploration
6Chrome DevTools console serves as an essential debugging tool for testing jQuery selectors and verifying element targeting before implementation
7Document ready function ensures jQuery code executes only after the DOM is fully loaded, preventing errors from attempting to manipulate non-existent elements
8Well-structured HTML with consistent ID and class naming conventions directly correlates to cleaner, more maintainable jQuery code and easier debugging processes

RELATED ARTICLES