top of page
This website was created by Code Enhancement Studio

Quick Tip: How to work with elements not part of mobile design on Wix

Most of the time, your mobile design renders fewer elements (button, images, ...) than your desktop design.


Because those elements are not rendered, when your Velo code tries to access them, you get an error, and your app stops working on mobile.


The error might look like this:

TypeError: $w(...).onClick is not a function

There are several tricks to prevent that error but we use the following for pages with many elements.


1. Create a mock element

//Mock object that emulate $w.Element
//It will simulate any method call the hidden elements
const mockedElement = {
   hide: () => {},
   show: () => {},
   onClick: () => {},
};

Properties are not mocked because they render as undefined. If you need a default value for mobile, you can add them to your mock.


2. Check if the website is rendered on Desktop

const isDesktopView = wixWindow.formFactor === "Desktop"


3. Replace the removed element with the mockElement

const $myHiddenElementOnMobile = isDesktopView ? $w("#elementId") : mockedElement;
const $myHiddenElementOnMobile2 = isDesktopView ? $w("#elementId2") : mockedElement;
const $alwaysVisibleElement = $w("#elementId3");

//rest of the code will behave the same whatever the formFactor
$myHiddenElementOnMobile.hide();//will do nothing
$myHiddenElementOnMobile2.value;//undefined

The advantage of this technique is that your code remains the same whatever the version (desktop or mobile) is being executed.


We like this approach because it keeps your logic independent of the device it's executed on.


Complete code

import wixWindow from 'wix-window';

//Mock object that emulate $w.Element
const mockedElement = {
   hide: () => {},
   show: () => {},
   onClick: () => {},
};

const isDesktopView = wixWindow.formFactor === "Desktop";

$w.onReady(() => {
   const $myHiddenElementOnMobile = isDesktopView ? $w("#elementId") : mockedElement;
   const $myHiddenElementOnMobile2 = isDesktopView ? $w("#elementId2") : mockedElement;
   const $alwaysVisibleElement = $w("#elementId3");

   //rest of the code will behave the same whatever the device
   $myHiddenElementOnMobile.hide();//will do nothing
   $myHiddenElementOnMobile2.value;//undefined
});


31 views0 comments

Recent Posts

See All
Anchor 1

Need help with Velo ?

We provide tutoring and debugging session to all skills levels.

From amateurs to professional developers, help writing high-quality code for performance and security

Maybe later
bottom of page