Overview
The SmartSize JavaScript API allows you to control the size chart modal using your own custom buttons, links, or other interactive elements. This gives you complete control over the placement, styling, and behavior of size chart triggers in your theme.
This method is specially useful if you want to re-use the existing size chart button in your theme and display SmartSize size charts via that button.
Getting Started
The SmartSize API is automatically available on any page where the SmartSize app is loaded. The API is exposed through the global window.smartsize object.
Checking API Availability
Always ensure the API is loaded before using it:
// Simple check
if (window.smartsize) {
// API is ready
window.smartsize.openModal();
}
// Wait for API to load (recommended)
function waitForSmartSize(callback) {
if (window.smartsize) {
callback();
} else {
setTimeout(() => waitForSmartSize(callback), 100);
}
}
waitForSmartSize(() => {
console.log('SmartSize API is ready!');
});
API Methods
window.smartsize.openModal()
Opens the size chart modal for the current product.
Returns: void
Example:
// Open modal when clicking a custom button
document.getElementById('my-size-button').addEventListener('click', function() {
window.smartsize.openModal();
});
Use Cases:
- Custom "Size Guide" buttons
- Text links in product descriptions
- Icon buttons in navigation
- Mobile menu items
window.smartsize.closeModal()
Closes the size chart modal if it's currently open.
Returns: void
Example:
// Close modal programmatically
document.getElementById('close-size-guide').addEventListener('click', function() {
window.smartsize.closeModal();
});
// Auto-close after adding to cart
document.getElementById('add-to-cart').addEventListener('click', function() {
if (window.smartsize.isModalOpen()) {
window.smartsize.closeModal();
}
});
window.smartsize.isModalOpen()
Checks whether the size chart modal is currently open.
Returns: boolean - true if modal is open, false otherwise
Example:
// Toggle modal open/closed
function toggleSizeGuide() {
if (window.smartsize.isModalOpen()) {
window.smartsize.closeModal();
} else {
window.smartsize.openModal();
}
}
// Check state before performing actions
if (window.smartsize.isModalOpen()) {
console.log('Size guide is currently visible');
}
window.smartsize.hasChart()
Checks if a size chart exists for the current product.
Returns: boolean - true if chart exists, false otherwise
Example:
// Only show button if chart exists
const button = document.getElementById('size-guide-button');
if (window.smartsize.hasChart()) {
button.style.display = 'block'; // Show button
} else {
button.style.display = 'none'; // Hide button
}
Use Cases:
- Conditionally show/hide size guide buttons
- Display different UI based on chart availability
- Prevent clicks when no chart exists
window.smartsize.openModalByProductId(productId)
Opens the size chart modal for a specific product by its Shopify product ID. Useful for collection pages, quick view modals, or anywhere you want to show a size chart for a product other than the current page.
Parameters:
productId(string|number, required) - The Shopify product ID
Returns: Promise<boolean> - Resolves to true if chart was opened successfully, false if no chart exists for the product
Example:
// Open size chart for a specific product
async function showSizeGuideForProduct(productId) {
const opened = await window.smartsize.openModalByProductId(productId);
if (opened) {
console.log('Size chart opened for product:', productId);
} else {
console.log('No size chart available for product:', productId);
alert('Sorry, no size guide available for this product');
}
}
// Usage on collection page
document.querySelectorAll('.product-card').forEach(card => {
const productId = card.dataset.productId;
const sizeButton = card.querySelector('.size-guide-link');
sizeButton.addEventListener('click', function(e) {
e.preventDefault();
window.smartsize.openModalByProductId(productId);
});
});
Use Cases:
- Collection page size guide links
- Quick view modals
- Product comparison pages
- Related products sections
window.smartsize.getProductData()
Returns the current product data that SmartSize has loaded.
Returns: object|null - Product data object or null if no data is available
Example:
const productData = window.smartsize.getProductData();
if (productData) {
console.log('Current product:', productData.title);
console.log('Product ID:', productData.id);
console.log('Variants:', productData.variants);
}
Use Cases:
- Debugging and troubleshooting
- Custom integrations
- Conditional logic based on product data
window.smartsize.getShopData()
Returns information about the current shop.
Returns: object - Shop data object with shop and domain properties
Example:
const shopData = window.smartsize.getShopData();
console.log('Shop domain:', shopData.shop);
console.log('Shop domain (alias):', shopData.domain);
Data Attributes (No JavaScript Required)
SmartSize automatically detects certain data attributes, allowing you to create triggers without writing any JavaScript.
data-smartsize-trigger="open"
Automatically opens the modal when the element is clicked.
Example:
<!-- Simple button --> <button data-smartsize-trigger="open">View Size Guide</button> <!-- Styled link --> <a href="#" data-smartsize-trigger="open" class="size-guide-link"> Size Chart </a> <!-- Icon button --> <button data-smartsize-trigger="open" class="icon-btn"> <svg><!-- ruler icon --></svg> </button>
data-smartsize-trigger="close"
Automatically closes the modal when the element is clicked.
Example:
<button data-smartsize-trigger="close">Close Size Guide</button>
data-smartsize-product="[productId]"
Opens the modal for a specific product when clicked.
Example:
<!-- Collection page -->
<div class="product-card" data-product-id="7234567890">
<h3>Blue T-Shirt</h3>
<button data-smartsize-product="7234567890">Size Guide</button>
</div>
<!-- Quick view modal -->
<a href="#" data-smartsize-product="{{ product.id }}">
View Size Chart
</a>
CSS Class: smartsize-trigger
Any element with the class smartsize-trigger will automatically open the modal when clicked.
Example:
<button class="smartsize-trigger">Size Guide</button> <a href="#" class="smartsize-trigger">View Sizing</a>
Complete Examples
Example 1: Custom Button with Conditional Display
Show a custom styled button only when a chart exists:
<button id="my-size-guide-btn" style="display: none;">
📏 Find Your Size
</button>
<script>
(function() {
function initSizeGuideButton() {
// Wait for SmartSize API
if (!window.smartsize) {
setTimeout(initSizeGuideButton, 100);
return;
}
const button = document.getElementById('my-size-guide-btn');
// Only show if chart exists
if (window.smartsize.hasChart()) {
button.style.display = 'inline-block';
// Add click handler
button.addEventListener('click', function() {
window.smartsize.openModal();
});
}
}
// Initialize
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initSizeGuideButton);
} else {
initSizeGuideButton();
}
})();
</script>
Example 2: Collection Page Size Guides
Add size guide buttons to each product in a collection:
<div class="product-grid">
{% for product in collection.products %}
<div class="product-card" data-product-id="{{ product.id }}">
<img src="{{ product.featured_image | img_url: 'medium' }}" alt="{{ product.title }}">
<h3>{{ product.title }}</h3>
<p>{{ product.price | money }}</p>
<!-- Size guide button with data attribute -->
<button
class="size-guide-btn"
data-smartsize-product="{{ product.id }}">
Size Guide
</button>
</div>
{% endfor %}
</div>
Example 3: Toggle Button (Open/Close)
Create a button that toggles the modal open and closed:
<button id="toggle-size-guide">Size Guide</button>
<script>
(function() {
function initToggleButton() {
if (!window.smartsize) {
setTimeout(initToggleButton, 100);
return;
}
const button = document.getElementById('toggle-size-guide');
// Only show if chart exists
if (!window.smartsize.hasChart()) {
button.style.display = 'none';
return;
}
// Toggle on click
button.addEventListener('click', function() {
if (window.smartsize.isModalOpen()) {
window.smartsize.closeModal();
button.textContent = 'Size Guide';
button.classList.remove('active');
} else {
window.smartsize.openModal();
button.textContent = 'Close Size Guide';
button.classList.add('active');
}
});
}
initToggleButton();
})();
</script>
Example 4: Mobile Drawer Integration
Integrate size guide into a mobile drawer menu:
<div class="mobile-drawer">
<ul class="drawer-menu">
<li><a href="/collections/all">Shop All</a></li>
<li><a href="/pages/about">About Us</a></li>
<li>
<a href="#" id="mobile-size-guide" style="display: none;">
📏 Size Guide
</a>
</li>
</ul>
</div>
<script>
(function() {
function initMobileSizeGuide() {
if (!window.smartsize) {
setTimeout(initMobileSizeGuide, 100);
return;
}
const link = document.getElementById('mobile-size-guide');
// Show only if on product page and chart exists
const isProductPage = document.body.classList.contains('template-product');
if (isProductPage && window.smartsize.hasChart()) {
link.style.display = 'block';
link.addEventListener('click', function(e) {
e.preventDefault();
window.smartsize.openModal();
// Close mobile drawer after opening size guide
document.querySelector('.mobile-drawer').classList.remove('open');
});
}
}
initMobileSizeGuide();
})();
</script>
Example 5: Text Link in Product Description
Add a clickable text link anywhere in your product description:
<div class="product-description">
<p>
Our premium cotton t-shirts are made for comfort.
Not sure about sizing?
<a href="#" class="smartsize-trigger" style="text-decoration: underline; color: blue;">
Check our size guide
</a>
for detailed measurements.
</p>
</div>
<!-- No JavaScript needed! The smartsize-trigger class handles everything -->
Example 6: Variant Change Detection
Update button visibility when product variants change:
<button id="dynamic-size-btn" style="display: none;">Size Guide</button>
<script>
(function() {
function updateSizeButton() {
if (!window.smartsize) {
setTimeout(updateSizeButton, 100);
return;
}
const button = document.getElementById('dynamic-size-btn');
if (window.smartsize.hasChart()) {
button.style.display = 'block';
} else {
button.style.display = 'none';
}
}
// Initial check
updateSizeButton();
// Listen for variant changes (adjust selector to your theme)
document.addEventListener('variant:change', updateSizeButton);
// Some themes use different events
document.addEventListener('variantChange', updateSizeButton);
// Button click handler
document.getElementById('dynamic-size-btn').addEventListener('click', function() {
window.smartsize.openModal();
});
})();
</script>
Best Practices
1. Always Check for API Availability
// ✅ Good
if (window.smartsize) {
window.smartsize.openModal();
}
// ❌ Bad - will error if API not loaded
window.smartsize.openModal();
2. Use Retry Pattern for Initialization
// ✅ Good - handles race conditions
function init() {
if (!window.smartsize) {
setTimeout(init, 100);
return;
}
// Your code here
}
init();
// ❌ Bad - might run before API loads
if (window.smartsize) {
// Your code here
}
3. Hide Buttons When No Chart Exists
// ✅ Good - better UX
if (window.smartsize.hasChart()) {
button.style.display = 'block';
} else {
button.style.display = 'none';
}
// ❌ Bad - confusing for customers
button.style.display = 'block'; // Always show
4. Prefer Data Attributes for Simple Cases
<!-- ✅ Good - simple and declarative -->
<button data-smartsize-trigger="open">Size Guide</button>
<!-- ❌ Unnecessary - too much code for simple task -->
<button id="btn">Size Guide</button>
<script>
document.getElementById('btn').addEventListener('click', () => {
window.smartsize.openModal();
});
</script>
5. Use Async/Await with Product-Specific API
// ✅ Good - handles promise properly
async function showChart(productId) {
const success = await window.smartsize.openModalByProductId(productId);
if (!success) {
alert('No size chart available');
}
}
// ⚠️ Works but doesn't handle failure
window.smartsize.openModalByProductId(productId);
Troubleshooting
Button Not Working
Check if API is loaded:
console.log('SmartSize available?', !!window.smartsize);Check if chart exists:
console.log('Has chart?', window.smartsize?.hasChart());- Check console for errors:
- Open browser DevTools (F12)
- Look for SmartSize-related messages
- Green message = API loaded successfully
Button Shows But Modal Doesn't Open
Verify click handler is attached:
button.addEventListener('click', function() { console.log('Button clicked!'); window.smartsize.openModal(); });- Check for JavaScript errors:
- Open browser console
- Look for red error messages
Ensure event isn't prevented:
button.addEventListener('click', function(e) { e.preventDefault(); // Add this if using <a> tag window.smartsize.openModal(); });
Chart Exists But hasChart() Returns False
The API checks asynchronously - ensure you're checking after page load. Use the retry pattern to wait for data to load:
function checkChart() {
if (!window.smartsize) {
setTimeout(checkChart, 100);
return;
}
if (window.smartsize.hasChart()) {
// Chart exists, show button
} else {
// Still loading, check again
setTimeout(checkChart, 100);
}
}
checkChart();
Browser Compatibility
The SmartSize API works in all modern browsers:
- Chrome/Edge (latest)
- Firefox (latest)
- Safari (latest)
- Mobile browsers (iOS Safari, Chrome Mobile)
For older browser support, ensure your code uses ES5 syntax or transpile with Babel.
Getting Help
If you encounter issues:
- Check the browser console for error messages
- Verify SmartSize is installed and active in your Shopify admin
- Test with the default SmartSize button first
- Contact SmartSize support with specific error messages
Summary
The SmartSize API gives you complete control over size chart triggers in your theme:
- Quick Start: Use
data-smartsize-trigger="open"for no-code implementation - Advanced: Use
window.smartsize.openModal()for custom logic - Product-Specific: Use
window.smartsize.openModalByProductId(productId)for collection pages - Conditional Display: Use
window.smartsize.hasChart()to show buttons only when needed
Choose the approach that best fits your needs and technical comfort level.