Star Ratings - Done
Overview
The Star Rating element is a dynamic, customizable JavaScript component that renders star-based ratings on your webpage. It processes elements with the class .star-rating-container and a data-rating attribute to display a visual representation of the rating using SVG stars. Each star accurately reflects full, partial, or empty states based on the specified rating value.
Features
- Dynamic Rendering: Automatically generates star elements based on the rating value.
- Partial Star Support: Accurately displays fractional ratings by partially filling stars.
- Accessible: Incorporates ARIA attributes for improved accessibility.
- Customizable: Easily adjust star sizes and colors using CSS variables.
How It Works
The JavaScript module follows a systematic approach to generate and style the star ratings:
- Initialization on DOM Load: Ensures the script runs after the DOM is fully loaded.
- Selecting Rating Containers: Targets all elements with the class .star-rating-container.
- Parsing Ratings: Extracts the rating value from the data-rating attribute.
- Generating Stars: Creates individual stars based on the rating, handling full, partial, and empty stars.
- Creating SVG Elements: Constructs SVGs for each star with appropriate fill and stroke.
- Handling Partial Fills: Utilizes SVG <clipPath> to display partially filled stars.
- Accessibility Enhancements: Adds ARIA attributes to improve screen reader compatibility.
Example Usage