Introduction
CurrClick is a lightweight, client‑side JavaScript library designed to handle currency selection and conversion on web pages. The core idea behind CurrClick is to provide a consistent user experience when displaying prices in multiple currencies, while keeping the implementation straightforward for developers. The library supports dynamic formatting, conversion via real‑time exchange rates, and integration with popular e‑commerce platforms.
Purpose and Scope
The primary goal of CurrClick is to abstract the complexity of currency selection away from application code. It offers developers a set of declarative attributes that can be applied to HTML elements, allowing the library to detect the user's locale or a chosen preference and adjust monetary values accordingly. CurrClick does not replace server‑side pricing logic; rather, it complements it by handling the front‑end representation.
Key Features
- Automatic detection of user locale using the browser’s language settings.
- Declarative API via data attributes.
- Real‑time exchange rates fetched from a configurable API provider.
- Formatting according to locale conventions, including currency symbols and decimal separators.
- Fallback to a default currency when conversion data is unavailable.
- Extensible architecture for custom formatters or rate providers.
History and Development
CurrClick was conceived in 2017 by a small team of e‑commerce developers who were dissatisfied with the existing solutions for front‑end currency handling. Early prototypes were built as part of an internal library for an online marketplace that required frequent currency updates. The codebase was initially released under a permissive license in early 2018, allowing other developers to incorporate it into their projects.
Version Timeline
- 1.0.0 – Initial release with basic currency formatting and static exchange rates.
- 1.2.0 – Introduction of dynamic rate fetching and locale detection.
- 2.0.0 – Major refactor for modularity, support for custom formatter plugins.
- 2.5.0 – Addition of a built‑in fallback mechanism and improved error handling.
- 3.0.0 – Integration with popular e‑commerce frameworks and performance optimizations.
Open Source Community
Since its release, CurrClick has attracted contributions from developers worldwide. The repository hosts a discussion forum where users can report bugs, request features, and share custom plugins. Regular releases are scheduled every quarter, ensuring compatibility with evolving web standards and third‑party services.
Technical Overview
CurrClick is implemented as a vanilla JavaScript module, with optional support for module bundlers such as Webpack, Rollup, and Browserify. The library attaches itself to the global window object, exposing a single entry point: window.currclick. Developers can also import the library as an ES module.
Data Attribute Convention
To apply CurrClick to a page element, developers use a specific set of data attributes:
data-currclick-value– The numeric value to be displayed.data-currclick-original-currency– The currency code of the provided value (e.g., USD, EUR).data-currclick-target-currency– The desired currency code for display. If omitted, the library uses the user’s locale currency.data-currclick-format– Optional custom formatting string.
When the library initializes, it scans the DOM for elements containing the data-currclick-value attribute and processes them accordingly.
Exchange Rate Retrieval
CurrClick fetches exchange rates from a configurable provider. By default, it uses a free public API that returns rates in JSON format. The library accepts a custom function to supply rates, enabling integration with enterprise-grade services or cached data. Rate requests are debounced to avoid excessive network traffic.
Formatting Engine
The formatting engine relies on the ECMAScript Internationalization API (Intl) to produce locale‑appropriate currency strings. It supports both symbol and code representations, as well as custom formatting patterns specified by the data-currclick-format attribute. The engine respects rounding rules, decimal precision, and grouping separators.
Error Handling and Fallbacks
When the library fails to fetch exchange rates, it falls back to the data-currclick-original-currency value. It also logs a warning to the console, allowing developers to identify issues during debugging. If the original currency code is missing, the element remains unchanged.
Key Concepts
Understanding the main abstractions in CurrClick is essential for effective use. The following concepts describe the library’s core components.
Locale and Currency Mapping
CurrClick uses the browser’s navigator.language property to determine the user's locale. It then maps that locale to a default currency via an internal lookup table. For instance, en-US maps to USD, de-DE to EUR. This mapping can be overridden by passing a custom map during initialization.
Currency Conversion Workflow
The conversion workflow comprises three steps:
- Detection – Identify the target currency based on locale or explicit attribute.
- Rate Retrieval – Fetch the conversion rate from the provider or use a cached value.
- Formatting – Apply the rate and format the final string for display.
These steps are performed asynchronously, ensuring the page remains responsive.
Declarative vs Imperative Use
CurrClick can be used declaratively by adding data attributes to HTML elements, allowing the library to manage conversion automatically. Alternatively, developers can invoke the library imperatively via JavaScript, passing an object containing value, source currency, target currency, and formatting options. The imperative API is useful when dynamic data is rendered after page load.
Custom Formatters and Plugins
To accommodate unique formatting requirements, CurrClick exposes a plugin interface. Developers can register custom formatter functions that receive the numeric value, currency code, and locale. These functions return a string to be displayed. Plugins can also hook into the rate retrieval process, enabling integration with specialized services.
API and Usage
CurrClick offers a concise API. The following sections detail the available methods and options.
Initialization
To set up the library, call currclick.init(options). The options object may include:
rateProvider– A function that returns a Promise resolving to a rate map.localeMap– An object mapping locale strings to currency codes.defaultCurrency– The fallback currency when no locale mapping is found.debug– Boolean flag to enable verbose console output.
Example:
currclick.init({
rateProvider: fetchRates,
localeMap: { 'en-US': 'USD', 'fr-FR': 'EUR' },
defaultCurrency: 'USD',
debug: false
});
Processing Elements
After initialization, the library automatically processes all elements with data-currclick-value. To manually trigger processing, use currclick.processElement(element) or currclick.processAll(). The processElement function returns a Promise that resolves once the element’s content is updated.
Imperative Conversion
Developers may perform conversions directly via:
currclick.convert({
value: 99.99,
from: 'USD',
to: 'EUR',
locale: 'de-DE'
}).then(formatted => {
console.log(formatted); // €85,00
});
Plugin Registration
To register a custom formatter:
currclick.registerFormatter('myCustom', (value, currency, locale) => {
// Custom logic
return `¤${value.toFixed(2)}`;
});
When an element includes data-currclick-format="myCustom", the custom formatter will be applied.
Integration with E‑Commerce Platforms
CurrClick can be integrated with popular e‑commerce solutions, providing a consistent front‑end experience across product listings, shopping carts, and checkout pages.
Shopify
Shopify themes can include CurrClick by adding the library to the theme’s assets and referencing the data-currclick attributes within product templates. The platform’s built‑in currency selector can be leveraged to trigger dynamic updates.
Magento
Magento modules may expose CurrClick as a dependency, enabling store owners to enable multi‑currency support on product pages without server‑side changes. The module registers event listeners to handle cart updates and price recalculations.
WooCommerce
Within WooCommerce, developers can enqueue CurrClick in the child theme’s functions file. The library can be paired with the WooCommerce REST API to fetch product prices and update the DOM on the fly.
Custom Applications
For bespoke web applications, CurrClick integrates seamlessly with any front‑end framework (React, Vue, Angular) through component wrappers or directive usage. These wrappers typically expose a <CurrClick> component that accepts props such as value, currency, and locale.
Security Considerations
While CurrClick is primarily a presentation layer tool, certain security aspects should be considered.
Rate Source Trustworthiness
Exchange rates are fetched from external APIs. Developers must ensure that the chosen provider is reliable and that data is transmitted over HTTPS to prevent tampering. Rate caches should be validated periodically to guard against stale data.
Input Validation
Values provided via data attributes or imperative calls should be validated to prevent injection attacks. The library sanitizes all input internally, but developers should still perform server‑side validation for critical data.
CORS and Same-Origin Policies
When fetching rates from a third‑party service, the provider must support Cross‑Origin Resource Sharing (CORS). Failure to do so will result in blocked requests. Developers may use JSONP or server‑side proxies as alternatives.
Content Security Policy (CSP)
CurrClick’s scripts should be included via trusted sources or inline with appropriate CSP directives. The library does not introduce external scripts beyond the rate provider, simplifying CSP management.
Community and Ecosystem
The CurrClick ecosystem extends beyond the core library. Numerous community-contributed plugins and wrappers exist, covering formatting, rate providers, and integration with various frameworks.
Plugin Repository
A curated list of plugins includes:
currclick-formatter-iso– Formats currency according to ISO 4217 standards.currclick-rate-fixer– Connects to the fixer.io API for real‑time rates.currclick-vue– Vue directive for declarative usage.currclick-react– React component wrapper.
Discussion Forums
The official discussion board hosts threads on best practices, bug reports, and feature requests. Contributors often provide sample code and troubleshoot integration issues.
Contributing Guidelines
Developers wishing to contribute are guided by a set of guidelines outlining code standards, testing procedures, and pull request workflows. The project emphasizes unit testing for core functions and compatibility tests across major browsers.
Future Directions
CurrClick’s roadmap focuses on enhancing usability, performance, and integration capabilities.
Performance Optimization
Future releases aim to reduce the library’s footprint by implementing tree shaking and lazy loading for unused features. Debounce logic for rate fetching will be refined to minimize latency.
Locale‑Aware Tax and Shipping Calculations
Integrating tax and shipping calculations based on locale is planned. This feature will allow developers to display complete price estimates, including local taxes and shipping fees.
Expanded Rate Provider Support
Additional providers, including those offering historical rates and forecast data, will be supported. The plugin interface will become more flexible to accommodate proprietary rate systems.
Accessibility Enhancements
Future iterations will ensure compliance with WCAG 2.1 guidelines, including support for screen readers and high‑contrast modes. Developers can specify accessibility attributes in data tags.
External Links
Official documentation and source code repository are maintained under the project’s umbrella. Community forums and plugin directories provide additional resources for developers.
No comments yet. Be the first to comment!