Add View Counter to Dynamic Page

:triangular_flag_on_post:MORE TUTORIALS https://www.wixideas.com/tutorials

:tv:Please Subscribe, Like, & Share :point_right:t4::point_right:t4: YouTube

This tutorial will show you how to add view counter to your WIX dynamic page. This will enable anyone to view and their view will be recorded.

Code

//VIEW EVENT FUNCTION 🚀
const viewsEvent = function () {

    $w("#dynamicDataset").onReady(() => {
        const itemObj = $w("#dynamicDataset").getCurrentItem();
        let totalViews = itemObj.views + 1;
        $w("#dynamicDataset").setFieldValue("views", totalViews)
        $w('#dynamicDataset').save();

        $w("#viewCounter").text = formatView(String($w("#dynamicDataset").getCurrentItem().views))
    });

}

//RUN THE VIEW WHEN PAGE LOADS⌛
$w.onReady(function () {
    setTimeout(viewsEvent, 100);
});

//FORMAT THE VIEWS PER ZERO🚀
function formatView(view) {
    if (view > 999 && view < 1000000) {
        return `${(view/1000).toFixed(0)}K`;
    } else if (view > 1000000) {
        return (view / 1000000).toFixed(0) + 'M';
    } else if (view < 900) {
        return view;
    }
}

Thanks🙂

:triangular_flag_on_post:MORE TUTORIALS https://www.wixideas.com/tutorials
:tv:Check out http://bit.ly/3a07EEF

Facebook Page: WIX Ideas
Facebook Community Group: Wix Ideas Community | Facebook
Instagram: Wix Ideas (@wixideas) • Instagram photos and videos
Website: https://www.wixideas.com/
YouTube Channel: https://www.youtube.com/@wixideas

@walterodibi Could you explain what’s the point of having a setTimeout on this feature?

setTimeout(viewsEvent,100);

Also, I believe there might be a problem because your code will execute 2 times on each rendering, therefore increasing the number of views twice.

It will insert once In backend rendering and once in frontend rendering: read the following articles for more details:

Hi @plomteuxquentin , thanks for the article. The setTimeout delays the execution of the viewEvent function. In a way, it makes it execute once when the page loads.

Removing the setTimeout makes the insert execute twice and adds 2 views instead of one.

@walterodibi is possible to count not every view, so that unique visitor counts?

Thank you @walterodibi71715 this helped a ton!!!