This guide will help you add a “xx people are looking at this item right now” message to your product pages in the Shopify Dawn theme. The number will remain static and won’t change while the user is on the page.
Step 1: Create a Custom JavaScript File
- Go to your Shopify Admin:
- Navigate to Online Store > Themes.
- Find the Dawn theme and click Actions > Edit code.
- Create a New JavaScript File:
- In the Assets folder, click Add a new asset.
- Select Create a blank file and name it
people-watching.js
. - Click Add asset.
- Add JavaScript Code:
- Open the newly created
people-watching.js
file. - Copy and paste the following code into this file:
- Open the newly created
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
document.addEventListener('DOMContentLoaded', function () {
const visitorCount = getRandomInt(5, 50); // Adjust the min and max values as needed
document.getElementById('people-watching').innerText = visitorCount;
});
This code generates a random number only once when the page is loaded and displays it.
- Save the JavaScript file.
Step 2: Modify the main-product.liquid
File
- Open the
main-product.liquid
file:- Go to the Sections folder.
- Click on
main-product.liquid
to open it.
- Add the HTML Element:
- Decide where you want the “people watching” message to appear (e.g., under the product title or price).
- Insert the following HTML code in the desired location:
<div id="people-watching-container" style="margin-top: 10px; font-weight: bold;">
<span id="people-watching"></span> people are looking at this item right now.
</div>
- Link the JavaScript File:
- Scroll to the bottom of the
main-product.liquid
file. - Add the following line to include your JavaScript file:
<script src="{{ 'people-watching.js' | asset_url }}" defer="defer"></script>
- Save the changes.
Step 3: Preview Your Product Page
- Go to your store’s product page.
- Verify that the “xx people are looking at this item right now” message is displayed correctly.