CodeAPI

$w

The $w namespace contains everything you need in order to work with your site's components. It contains all of the UI elements, nodes, and events that make up your site. It also includes the $w(), onReady(), and at() functions.

The APIs in $w can only be used in front-end code.

You do not need to import $w.

Table of Contents

FUNCTIONS

?
Perform actions on an object.
$w( )Selects and returns elements from a page.
at( )Gets a selector function for a specific context.
onReady( )Sets the function that runs when all the page elements have finished loading.

$w( )

Selects and returns elements from a page.

Description

The $w() function selects single or multiple elements by ID or type.

To select by ID, pass a selector string with the hash symbol (#) followed by the ID of the item you want to select (e.g. "#myElement"). The function returns the selected element object.

To select by type, pass a selector string with the name of the type without the preceding # (e.g. "Button"). The function returns an array of the selected element objects. An array is returned even if one or no elements are selected.

To select using multiple selectors, pass a selector string with multiple selectors separated by commas. The selectors in the comma-separated string can be ID selectors, type selectors, or a mixture of the two. The function returns an array of the selected element objects. An array is returned even if one or no elements are selected. If two or more selectors select the same element, it's still returned only once in the array.

Syntax

function $w(selector: string): Element | Array<Element>
PARAMETERS
?
The kind of data the property stores.
selector
string
A selector or multiple comma-separated selectors.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Element | Array<>
A single selected element or an array of selected elements.

Examples

Select an element using its ID

let myElement = $w("#myElement");

let elementType = myElement.type; // "$w.Type"

Select elements by type

let typeElements = $w("Type");

let firstOfType = typeElements[0];

Select all the images on the page

let imageElements = $w("Image");

let firstImage = imageElements[0];

Select elements using multiple selectors

let selected = $w("#myElement1, #myElement3, Type");

Hide all the page's images

$w("Image").hide();

at( )

Gets a selector function for a specific context.

Description

The at() function returns a scoped selector where the scope is based on the context property. Usually, you will use at() in a event handler that handles events fired on an element contained in a repeater to get a selector with repeated item scope. The returned function selects the elements from the same repeater item where the event was fired.

For example, suppose we have a repeater where each item contains an image and a text element. Here, when an image is clicked, the value of the text element in the same repeated item is changed to "Selected". All the other text elements in the other repeated items are not affected.

 $w.onReady( function () {
   $w("#myRepeatedImage").onClick( (event, $w) => {
     let $item = $w.at(event.context)
     $item("#myRepeatedText").text = "Selected";
   } );
 } );

Syntax

function at(context: EventContext): $w
PARAMETERS
?
The kind of data the property stores.
context
An event context.
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
A selector function for the given context.

onReady( )

Sets the function that runs when all the page elements have finished loading.

Description

Use the onReady() function for code you want to run before the user starts interacting with your page.

The following code should be placed inside the onReady() event handler:

  • Initialization of element properties: Example: setting a text element's initial text value.
  • Function calls on elements to set their initial state: Example: disabling a button.
  • Dynamic event handlers that you want bound when the page loads: Example: setting an event handler to be called when the mouse pointer enters an element.

Static event handlers, those that are wired using the Properties panel in the Editor, are not placed inside the onReady() event handler.

The onReady() function in the Site tab is called before the onReady() function in the Page tab.

The onReady() event handler may be called twice during the page rendering process, once server-side and once client-side. You can use this behavior to improve your page's load time. To learn more, see About The Page Rendering Process.

When onReady() is run server-side, you can pass data to the client-side by returning it from the onReady() handler function. Then, you can retrieve the passed data client-side by using the warmupData property of wix-window.rendering.

When onReady() is run client-side, you can return a Promise from the onReady handler function to force the page to wait for your Promise to resolve before displaying the page to users.

For example, suppose you are using a query to retrieve data that you want to display in a table. If you don't return the query promise the table might show without your data until the query's Promise resolves. Instead return the query Promise so that the page doesn't load for users until the query returns results and the table is populated.

Note

Because onReady() code may be run twice, you need to be aware that if your onReady() code causes a side effect, such as inserting an item into a collection, that side effect might happen twice. To learn how to avoid side effects from occurring twice, see About The Page Rendering Process.

See Also

$w( )

Syntax

function onReady(initFunction: ReadyHandler): void
callback ReadyHandler(): Promise<void>
PARAMETERS
?
The kind of data the property stores.
initFunction
function()
The name of the function or the function expression to run when the page has finished loading.

Examples

Run code in an anonymous function when the page loads

$w.onReady( function() {
  let pageTitle = $w("#page1").title;
} );

Wait for a Promise to resolve

This example demonstrates the technique of returning a Promise so that the page doesn't load until the Promise resolves. Here, we wait for the query to finish and populate a table before displaying the page to users.

import wixData from 'wix-data';

$w.onReady(function () {
  return wixData.query("myCollection")
    .find()
    .then( (results) => {
      $w("#myTable").rows = results.items;
    } );
} );

Where to place code

This example demonstrates which code should be placed inside the onReady() event handler.

// Import statement go at the top of your code, outside of onReady()
import wixWindow from 'wix-window';

// Initialization statements without $w() don't need to be in onReady()
let hideCount = 0;

// Code you want to run when the page loads
$w.onReady(function () {
  console.log(`Device viewing site is: ${wixWindow.formFactor}`);

  // Initialize an element property
  $w("#myTextElement").text = "Hover over to hide";

  // Call a function on an element to set its initial state
  $w("#buttonReset").disable();

  // Dynamic event handler to be bound when the page loads
  $w("#myTextElement").onMouseIn( (event) => {
    event.target.hide();
    console.log(`Hidden ${++hideCount} times`);
    $w("#buttonReset").enable();
  } );
} );

// Static event handler
export function buttonReset_onClick(event) {
  $w("#myTextElement").show();
  $w("#buttonReset").disable();
}

Use warmupData to run a query server-side and pass the results to client-side code

This example demonstrates how to work with passing warmup data from the server-side render to cycle to be used in the client-side cycle. It takes into account the two possible render paths: 1) Two cycles - First cycle happens on the server and then a second cycle in the browser. 2) One cycle - Only one cycle that happens in the browser.

import wixData from 'wix-data';
import wixWindow from 'wix-window';
import {local} from 'wix-storage';

let promise;
let dataResults;

// start performing a query as soon as possible during
// the first render cycle and store the returned promise
if(wixWindow.rendering.renderCycle === 1) {
  promise = wixData.query("myCollection").find();
}

// this will run twice, once on the
// backend and once in the browser
$w.onReady( function () {
  // if it's the first render cycle, set up what
  // to do when the query promise resolves
  if(wixWindow.rendering.renderCycle === 1) {
    promise.then( (results) => {
      // use the query results for page setup
      $w("#text").text = results.items[0].title;

      // if the first cycle is happening on the backend
      if(wixWindow.rendering.env === "backend") {
        // return the items from the query results
        // to be used later in the browser
        return results.items;
      }
      // if the first cycle is happening in the browser, just
      // store the items from the query results in a variable
      dataResults = results.items;
    } );
  }
  // if it's the second render cycle, get the items from the query
  // results returned in the first cycle and store them in a variable
  else {
    dataResults = wixWindow.rendering.warmupData;
  }

  // regardles of cycle, if in the browser, do some stuff that can
  // only be done in the browser, like using local storage
  if(wixWindow.rendering.env === "browser") {
    $w('#storedText').text = local.getItem("someKey");
  }

  // if it's the first cycle, return the promise
  // that rendering rendering should wait for
  // if there will be a second cycle, the value the promise
  // resolves to will be retrieved using warmupData
  if(wixWindow.rendering.renderCycle === 1) {
    return promise;
  }
} );