CorvidReference

CustomElement

This feature is not yet available to all users.

An API for rendering a custom element.

A custom element is a reusable web component element that you define in a JavaScript file that is either hosted by Wix or hosted on a server that is external to Wix. The custom element is defined using the standard ECMAScript 2015 class syntax.

This reference focuses on how you can use Corvid to interact with custom elements. This reference provides only basic instructions for actually creating custom elements. For complete instructions and examples, see MDN documentation.

  • Learn more about using custom elements with Corvid.
  • This FAQ provides more information including some technical tips for getting started.

Custom Element Lifecycle with Corvid

The general flow for working with custom elements and Corvid is:

  1. Code the custom element and its behavior in a JavaScript file using any IDE.
  2. In the Wix Editor's Add panel, add a custom element to the site. In Settings, connect the custom element's code to the custom element added to your page on the site.
  3. Using Corvid, set up interactions between your site and the custom element. You can code event handling and additional functionality for the custom element.

You can also define seoMarkup for SEO support on custom elements.

Limitations

Table of Contents

PROPERTIES

?
Store values associated with an object.
collapsedIndicates if the element is collapsed or expanded.
globalIndicates if an element appears on all pages or only on the current page.
hiddenIndicates if the element is visible or hidden.
idGets the element's ID.
isVisibleIndicates if the element is actually visible.
parentGets the element's parent element.
renderedIndicates if an element is currently in the DOM structure.
seoMarkupSets or gets the SEO markup to be rendered for search engine bots.
typeGets the element's type.

FUNCTIONS

?
Perform actions on an object.
collapse( )Collapses the element and sets its collapsed property to true.
expand( )Expands the element and sets its collapsed property to false.
hide( )

Hides the element and sets its hidden property to true, using an effect if specified.

on( )Registers a callback function in Corvid for an event triggered from the custom element.
onMouseIn( )

Adds an event handler that runs when the mouse pointer is moved onto the element.

onMouseOut( )

Adds an event handler that runs when the mouse pointer is moved off of the element.

onViewportEnter( )

Adds an event handler that runs when an element is displayed in the viewable part of the current window.

onViewportLeave( )

Adds an event handler that runs when an element is no longer displayed in the viewable part of the current window.

scrollTo( )Scrolls the page to the element using an animation.
setAttribute( )Sets an HTML attribute on the custom element's DOM node.
show( )

Shows the element and sets its hidden property to false, using an effect if specified.

MIXES IN

?
Where some functionality is inherited from.
$w.Element, $w.HiddenCollapsedMixin

collapsed

Indicates if the element is collapsed or expanded.

Description

If collapsed is true, the element is not displayed on the page under any circumstances. A collapsed element, unlike a hidden element, does not take up any space on the page. When collapsed, elements positioned within 70 pixels below the collapsed element and each other move up to take the collapsed element's place where possible. The elements that move up maintain their positions relative to one another.

If collapsed is false, the element may be displayed on the page. Elements that moved up to take the collapsed element's place on the page are moved back down.

However, an expanded element (an element whose collapsed property is false) is still not displayed if:

Even if the element is not be displayed due to the conditions mentioned above, if its collapsed property is false, it's displayed when the conditions no longer apply.

To set the collapsed property on an element, use the element's collapse() and expand() functions.

If you select Collapsed on load in the element's Properties panel in the Editor, the collapsed property is set to true when the page loads.

See Also

collapse( ), expand( ), hide( ), show( ), hidden

Syntax

get collapsed(): boolean
TYPE
?
The kind of data the property stores.
boolean
DEFAULT VALUE
?
The value of a property before you explicitly set it.
false

MIXED IN FROM

?
Where this functionality is inherited from.
$w.HiddenCollapsedMixin

Examples

Get an element's collapsed status

let isCollapsed = $w("#myElement").collapsed; // false

Toggle an element's collapsed state

if( $w("#myElement").collapsed ) {
  $w("#myElement").expand();
}
else {
  $w("#myElement").collapse();
}

global

Indicates if an element appears on all pages or only on the current page.

Description

If global is true, the element appears on all pages.

If global is false, the element only appears on the current page.

Syntax

get global(): boolean
TYPE
?
The kind of data the property stores.
boolean
DEFAULT VALUE
?
The value of a property before you explicitly set it.
false

MIXED IN FROM

?
Where this functionality is inherited from.
$w.Element

Examples

Get whether an element is displayed on all pages

let isGlobal = $w("#myElement").global; // false

hidden

Indicates if the element is visible or hidden.

Description

If hidden is true, the element is not displayed on the page under any circumstances. A hidden element, unlike a collapsed element, continues to take up the same space on the page as it did when it was visible.

If hidden is false, the element may be displayed on the page.

However, an element whose hidden property is false is still not displayed if:

Even if the element is not displayed due to the conditions mentioned above, if its hidden property is set to false, it's displayed when the conditions no longer apply.

To determine if the element is actually visible, use the isVisible property.

To set the hidden property on an element, use the element's hide() or show() functions.

If you select Hidden on load in the element's Properties panel in the Editor, the hidden property is set to true when the page loads.

Note

An element's hidden property is not the same as its isVisible property. The hidden property indicates whether the element should be displayed, while isVisible indicates if it is actually displayed.

See Also

hide( ), show( ), collapse( ), expand( ), collapsed, rendered

Syntax

get hidden(): boolean
TYPE
?
The kind of data the property stores.
boolean
DEFAULT VALUE
?
The value of a property before you explicitly set it.
false

MIXED IN FROM

?
Where this functionality is inherited from.
$w.HiddenCollapsedMixin

Examples

Get an element's hidden status

let isHidden = $w("#myElement").hidden;  // false

Toggle an element's hidden state

if( $w("#myElement").hidden ) {
  $w("#myElement").show();
}
else {
  $w("#myElement").hide();
}

id

Gets the element's ID.

Description

The ID is the element's unique identifier. It is used when selecting elements using the $w() function.

An element's id is set in the Editor using the Properties panel.

Syntax

get id(): string
TYPE
?
The kind of data the property stores.
string

MIXED IN FROM

?
Where this functionality is inherited from.
$w.Element

Examples

Get the ID

let myId = $w("#myElement").id; // "myElement"

isVisible

Indicates if the element is actually visible.

Description

If isVisible is true, the element is displayed on the page.

If isVisible is false, the element is not displayed on the page.

The value of the isVisible property is calculated based on the hidden, collapsed, and rendered properties of the element and all of its ancestors. It is true only if the conditions exist in the element's property values and the property values of its ancestors such that the element is actually displayed on the page.

Note

An element's isVisible property is not the same as its hidden property. The isVisible property indicates whether the element is actually displayed, while hidden indicates if it should be displayed.

The isVisible property of an element remains true even if another element completely covers it so that a user cannot see it.

See Also

hidden, collapsed, rendered

Syntax

get isVisible(): boolean
TYPE
?
The kind of data the property stores.
boolean
DEFAULT VALUE
?
The value of a property before you explicitly set it.
true

MIXED IN FROM

?
Where this functionality is inherited from.
$w.HiddenCollapsedMixin

Examples

Get whether an element is visible

let isVisible = $w("#myElement").isVisible;  // true

parent

Gets the element's parent element.

Description

Some elements can contain other elements. This occurs when you drag an element onto a container element. The container is the parent of all the elements it contains.

Page, Header, and Footer are top-level elements and have no parent.

See Also

children

Syntax

get parent(): Node
TYPE
?
The kind of data the property stores.
DEFAULT VALUE
?
The value of a property before you explicitly set it.
null

MIXED IN FROM

?
Where this functionality is inherited from.
$w.Element

Examples

Get the parent element and the parent's ID

let parentElement = $w("#myElement").parent;

let parentId = parentElement.id; // "page1"

rendered

Indicates if an element is currently in the DOM structure.

Description

If rendered is true, the element is in the current DOM structure and can be used.

If rendered is false the element is not in the current DOM structure.

An element might not be in the DOM if it is in a slide or a state which is not currently showing.

See Also

collapsed, hidden, isVisible

Syntax

get rendered(): boolean
TYPE
?
The kind of data the property stores.
boolean
DEFAULT VALUE
?
The value of a property before you explicitly set it.
false

MIXED IN FROM

?
Where this functionality is inherited from.
$w.Element

Examples

Get an element's rendered status

let isRendered = $w("#myElement").rendered;  // true

seoMarkup

Sets or gets the SEO markup to be rendered for search engine bots.

Description

Use the seoMarkup property to write HTML content that will be served to Google and other search engines. This is necessary because some bots cannot process the JavaScript content of the custom element.

If you do not add the equivalent HTML of the custom element's implementation using this SEO markup property, only bots that index JavaScript, such as Google, will be able to index the custom element's content/markup for search engine results.

Note

It is the user's responsibility to handle all aspects of SEO for the element, including managing the validity of the SEO markup opposite search engines.

Syntax

get seoMarkup(): string
set seoMarkup(value: string): void
TYPE
?
The kind of data the property stores.
string

Examples

Set SEO markup for the custom element

// **********************************************
// Custom Element Code in Corvid 
// **********************************************

// Set the HTML content for SEO markup 
// to be used by search engines.
// Make sure the SEO markup matches the 
// contents of the custom
// element exactly so as not to mislead 
// web crawlers.

$w('#myCustomElement').seoMarkup = 'Hello World!';


// **********************************************
// Custom Element Implementation on an HTML Page
// **********************************************

class MyElement extends HTMLElement {
  connectedCallback() {
    this.innerHTML = 'Hello World!'
  }
}
customElements.define('my-custom-element', MyElement);
  

// ***************************************************************
// Custom Element's Result (both for SEO bots and non-SEO traffic)
// ***************************************************************
<my-custom-element>Hello World!</my-custom-element>

type

Gets the element's type.

Syntax

get type(): string
TYPE
?
The kind of data the property stores.
string

MIXED IN FROM

?
Where this functionality is inherited from.
$w.Element

Examples

Get the element's type

let myType = $w("#myElement").type; // "$w.Type"

collapse( )

Collapses the element and sets its collapsed property to true.

Description

The collapse() function returns a Promise that is resolved when the element's collapsed property has been set to true.

To learn about the behavior of a collapsed element, see the collapsed property.

You can also collapse an element when the page loads by using the Properties panel in the Editor.

See Also

expand( ), collapsed, hide( )

Syntax

function collapse(): Promise<void>
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>
Fulfilled - When the element's collapsed property has been set to true.

MIXED IN FROM

?
Where this functionality is inherited from.
$w.HiddenCollapsedMixin

Examples

Collapse an element

$w("#myElement").collapse();

Collapse an element and log a message when done

$w("#myElement").collapse()
  .then( () => {
    console.log("Done with collapse");
  } );

Toggle an element's collapsed state

if( $w("#myElement").collapsed ) {
  $w("#myElement").expand();
}
else {
  $w("#myElement").collapse();
}

expand( )

Expands the element and sets its collapsed property to false.

Description

The expand() function returns a Promise that is resolved when the element's collapsed property has been set to false.

To learn about the behavior of an expanded element, see the collapsed property.

See Also

expand( ), collapsed, show( )

Syntax

function expand(): Promise<void>
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>
Fulfilled - When the element's collapsed property has been set to false.

MIXED IN FROM

?
Where this functionality is inherited from.
$w.HiddenCollapsedMixin

Examples

Expand an element

$w("#myElement").expand();

Expand an element and log a message when done

$w("#myElement").expand()
  .then( () => {
    console.log("Done with expand");
  } );

Toggle an element's collapsed state

if( $w("#myElement").collapsed ) {
  $w("#myElement").expand();
}
else {
  $w("#myElement").collapse();
}

hide( )

Hides the element and sets its hidden property to true, using an effect if specified.

Description

The hide() function hides the element and returns a Promise that is resolved when the effect is complete and the element's hidden property has been set to true.

To learn about the behavior of a hidden element, see the hidden property.

You can optionally apply an effect when hiding the element by providing an effectName value. You can also customize the effect by providing the optional effectOptions object.

Effects:

You can also hide an element when the page loads by using the Properties panel in the Editor.

See Also

show( ), hidden, collapse( )

Syntax

function hide([effectName: string], [effectOptions: ArcEffectOptions | BounceEffectOptions | FadeEffectOptions | FlipEffectOptions | FloatEffectOptions | FlyEffectOptions | FoldEffectOptions | GlideEffectOptions | PuffEffectOptions | RollEffectOptions | SlideEffectOptions | SpinEffectOptions | TurnEffectOptions | ZoomEffectOptions]): Promise<void>
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>
Fulfilled - When the effect is complete and the element's hidden property has been set to true.

MIXED IN FROM

?
Where this functionality is inherited from.
$w.HiddenCollapsedMixin

Examples

Hide an element with no effect

$w("#myElement").hide();

Hide an element with the "fade" effect

$w("#myElement").hide("fade");

Hide an element with the "fade" effect and custom options

let fadeOptions = {
  "duration":   2000,
  "delay":      1000
};

$w("#myElement").hide("fade", fadeOptions);

Hide an element with an effect and log a message when the effect is done

$w("#myElement").hide("fade")
  .then( ( ) => {
    console.log("Done with fade");
} );

Toggle an element's hidden state

if( $w("#myElement").hidden ) {
  $w("#myElement").show();
}
else {
  $w("#myElement").hide();
}

on( )

Registers a callback function in Corvid for an event triggered from the custom element.

Description

The on() function registers a callback function in Corvid based on the this.dispatchEvent() in the custom element's script.

The on() function enables the custom element to affect the rendering of the site.

The code snippets below demonstrate how to define a my-event event in the custom element's implementation and how to refer to it from Corvid.

Syntax

function on(eventName: string, callBackFunction: Function): void
PARAMETERS
?
Values that you pass to a function.
eventName
string
The name of the event.
callBackFunction
Function
The callback function to run when the event is triggered.

Examples

Create an event in the custom element that Corivd can respond to

// **********************************************
// Custom Element Code in Corvid 
// **********************************************

// Handle an event on the custom element.  
$w('#myCE').on('my-event', 
  console.log('The event triggered successfully.') 
);


// **********************************************
// Custom Element Implementation on an HTML Page
// **********************************************

class MyElement extends HTMLElement {
  connectedCallback() {
    this.innerHTML = 'Hello World!'

    // Trigger an event that Corvid can watch for 
    // and handle using the [`on()`] function.

    this.dispatchEvent(new CustomEvent('my-event')
  }
}
customElements.define('my-custom-element', MyElement);
  

// ************************************************
// Custom Element's Result
// ************************************************

<my-custom-element>Hello World!</my-custom-element>

Check if events defined in the custom element occur

Learn more about this example.
// **********************************************
// Custom Element Implementation on an HTML Page
// **********************************************

// Code to set up variables and styles for the logo. 
const LOGO_TXT = 'https://static.wixstatic.com/media/logo-txt.png';
const LOGO_IMG = 'https://static.wixstatic.com/media/logo-img.png';
const LOGO_PHONE ='https://static.wixstatic.com/media/logo-phone.png';

const STYLE = `
#img.shake {
    animation: shake 0.5s;
    animation-iteration-count: infinite;
  }

  @keyframes shake {
    0% { transform: translate(1px, 1px) rotate(0deg); }
    10% { transform: translate(-1px, -2px) rotate(-1deg); }
    20% { transform: translate(-3px, 0px) rotate(1deg); }
    30% { transform: translate(3px, 2px) rotate(0deg); }
    40% { transform: translate(1px, -1px) rotate(1deg); }
    50% { transform: translate(-1px, 2px) rotate(-1deg); }
    60% { transform: translate(-3px, 1px) rotate(0deg); }
    70% { transform: translate(3px, 1px) rotate(-1deg); }
    80% { transform: translate(-1px, -1px) rotate(1deg); }
    90% { transform: translate(1px, 2px) rotate(0deg); }
    100% { transform: translate(1px, -2px) rotate(-1deg); }
  }
`;

// Code to check if the size of the custom element has 
// changed. 
const dispatchSizeChange = (root,scaleTxt) => {
  const gettingSmall = scaleTxt === 0 && root.prevScaleTxt !== 0;
  const gettingBig = scaleTxt !== 0 && root.prevScaleTxt === 0;
  root.prevScaleTxt = scaleTxt;

  // Use dispatchEvent() to create a new custom event that 
  // Corvid can handle. In our example, the event is 
  // triggered when the size of the custom element gets bigger or 
  // smaller.
  if (gettingSmall || gettingBig) {
    root.dispatchEvent(new CustomEvent('sizeChange', 
        { detail: { data: gettingSmall ? 'small' : 'big' } }));
  }
};

// Code to rotate and resize the custom element. 
const scrollHandler = root => (event) => {
  const txt = root.querySelector('#txt');
  const scaleTxt = (Math.max(0, 1000 - window.scrollY)) / 1000;
  txt.style.transform = `scale(${scaleTxt})`;
  dispatchSizeChange(root, scaleTxt);
  const opacityTxt = 1 / Math.log10(Math.max(10, window.scrollY));
  txt.style.opacity = opacityTxt;
  const img = root.querySelector('#img');
  img.style.transform = `rotate(${window.scrollY / 10}deg)`;
}

// Code to create each image that the logo comprises and 
// add the logo to the DOM using a `createImg()` function.
const createImg = (id, src) => {
  const img = document.createElement('img');
  img.src = src;
  img.id = id;
  img.width = '200';
  img.style.position = 'fixed';
  return img;
}

// Code to define the custom element based on the 
// definitions above.
class allEffects extends HTMLElement {

  constructor() {
    super();

    document.addEventListener('wheel', scrollHandler(this), {
        capture: false, passive: true })
        const style = document.createElement('style');
        style.innerHTML = STYLE;
        this.appendChild(style);
  }

  // Code for a special lifecycle function `connectedCallback()`
  // that runs when the custom element is connected initially to the DOM.
  // This function displays the various parts of the logo.
  connectedCallback() {
    this.appendChild(createImg('txt', LOGO_TXT));
    this.appendChild(createImg('img', LOGO_IMG));
    this.appendChild(createImg('img', LOGO_PHONE));
    const phone = createImg('phone', LOGO_PHONE);
    phone.style.display = 'none';
    this.appendChild(phone);
  }

  // Code for a special lifecycle function `attributeChangedCallback()`
  // that checks if the context of the page has changed. 
  attributeChangedCallback(name, oldValue, newValue) {   
    if (name === 'hoveringmenu') {
      this.querySelector('#img').className = newValue === 'true' ? 'shake' : '';
    }
    if (name === 'footershown') {
      this.querySelector('#phone').style.display = newValue === 'true' ? '' : 'none';
    }
  }

  // Code for a special lifecycle function `observedAttributes()`
  // that checks specific attributes on the page. 
  static get observedAttributes() {
    return ['hoveringmenu', 'footershown'];
  }
}

// Code to register the custom element. The name `my-logo-effects` is the 
// tag name to specify when adding the custom element in the Wix 
// Editor to the site. Make sure the tag name is in lowercase characters. 
customElements.define('my-logo-effects', allEffects);
  

// **********************************************
// Corvid Code for Custom Element on Page
// **********************************************

// Use `on()` to handle the `sizeChange` event defined in the 
// custom element. In this case, if the logo is very small, 
// the menu on the page is hidden. This is because one of the 
// defined behaviors of the element is that the logo gets 
// smaller as we scroll down the page.
$w.onReady(function () {
  $w('#myCustomElement').on('sizeChange', ({detail: {data}}) => {
    if (data === 'small') {
      $w('#menu').hide();
    } else {
      $w('#menu').show();
    }
  })
});

// **********************************************
// Corvid Code for Custom Element on the Site
// **********************************************

// The custom element's behavior will change for the entire
//  site in the following cases: 
// 
// + If the footer enters or leaves the viewport.
// + If the site visitor's mouse hovers or stops hovering over the menu.
// 
// Corvid "sends" the custom element attributes using `setAttribute()`
// so the element can process and and affect the element's behaviors
// according to the context on the page. 
export function footer1_viewportEnter(event) {
  $w('#myCustomElement').setAttribute('footershown', true);
 }
export function footer1_viewportLeave(event) {
 $w('#myCustomElement').setAttribute('footershown', false);
}
export function menu_mouseIn(event) {
 $w('#myCustomElement').setAttribute('hoveringmenu', true);
}
export function menu_mouseOut(event) {
 $w('myCustomElement').setAttribute('hoveringmenu', false);
}

onMouseIn( )

Adds an event handler that runs when the mouse pointer is moved onto the element.

Note

Deprecation note: The $w parameter of event handlers is being deprecated. To get a scoped selector for working with elements in repeater items, use the $w.at() function and pass it the context property of the event parameter: $item = $w.at(event.context). To learn more, see here.

Syntax

function onMouseIn(handler: MouseEventHandler): Element
callback MouseEventHandler(event: MouseEvent, $w: $w): void
PARAMETERS
?
Values that you pass to a function.
handler
function(event: MouseEvent, $w: $w)

The name of the function or the function expression to run when the mouse pointer is moved onto the element.

?
Values that you pass to a function.
event
The mouse event that occurred.
$w

Deprecated: A selector function. The $w function was used to enable event handlers to work with elements in repeaters. Now, to get a scoped selector for working with repeater items, use the $w.at() function and pass it the context property of the event parameter: $item = $w.at(event.context).

RETURN VALUE
?
Value that a function evaluates to when it is finished running.
The element to which the event handler was added.

MIXED IN FROM

?
Where this functionality is inherited from.
$w.Element

Examples

Get the mouse event info when the mouse enters an element

$w("#myElement").onMouseIn( (event) => {
  let clientX = event.clientX;  // 362
  let clientY = event.clientY;  // 244
  let offsetX = event.offsetX;  // 10
  let offsetY = event.offsetY;  // 12
  let pageX = event.pageX;      // 362
  let pageY = event.pageY;      // 376
  let screenX = event.screenX;  // 3897
  let screenY = event.screenY;  // 362
} );

onMouseOut( )

Adds an event handler that runs when the mouse pointer is moved off of the element.

Note

Deprecation note: The $w parameter of event handlers is being deprecated. To get a scoped selector for working with elements in repeater items, use the $w.at() function and pass it the context property of the event parameter: $item = $w.at(event.context). To learn more, see here.

Syntax

function onMouseOut(handler: MouseEventHandler): Element
callback MouseEventHandler(event: MouseEvent, $w: $w): void
PARAMETERS
?
Values that you pass to a function.
handler
function(event: MouseEvent, $w: $w)

The name of the function or the function expression to run when the mouse pointer is moved off of the element.

?
Values that you pass to a function.
event
The mouse event that occurred.
$w

Deprecated: A selector function. The $w function was used to enable event handlers to work with elements in repeaters. Now, to get a scoped selector for working with repeater items, use the $w.at() function and pass it the context property of the event parameter: $item = $w.at(event.context).

RETURN VALUE
?
Value that a function evaluates to when it is finished running.
The element to which the event handler was added.

MIXED IN FROM

?
Where this functionality is inherited from.
$w.Element

Examples

Get the mouse event info when the mouse exits an element

$w("#myElement").onMouseOut( (event) => {
  let clientX = event.clientX;  // 362
  let clientY = event.clientY;  // 244
  let offsetX = event.offsetX;  // 10
  let offsetY = event.offsetY;  // 12
  let pageX = event.pageX;      // 362
  let pageY = event.pageY;      // 376
  let screenX = event.screenX;  // 3897
  let screenY = event.screenY;  // 362
} );

onViewportEnter( )

Adds an event handler that runs when an element is displayed in the viewable part of the current window.

Description

An element enters the viewport when the page is scrolled to show any part of the element. An element also enters the viewport if it was hidden or collapsed and is then shown or expanded in the viewable part of the current window. onViewportEnter() is not fired for hidden or collapsed elements even if they are scrolled into view.

Note

Deprecation note: The $w parameter of event handlers is being deprecated. To get a scoped selector for working with elements in repeater items, use the $w.at() function and pass it the context property of the event parameter: $item = $w.at(event.context). To learn more, see here.

See Also

onViewportLeave( )

Syntax

function onViewportEnter(handler: EventHandler): Element
callback EventHandler(event: Event, $w: $w): void
PARAMETERS
?
Values that you pass to a function.
handler
function(event: Event, $w: $w)

The name of the function or the function expression to run when the element enters the viewport.

?
Values that you pass to a function.
event
The event that occurred.
$w

Deprecated: A selector function. The $w function was used to enable event handlers to work with elements in repeaters. Now, to get a scoped selector for working with repeater items, use the $w.at() function and pass it the context property of the event parameter: $item = $w.at(event.context).

RETURN VALUE
?
Value that a function evaluates to when it is finished running.
The element on which the event is now registered.

MIXED IN FROM

?
Where this functionality is inherited from.
$w.Element

Examples

Get the ID of the element that has entered the viewport

$w("#myElement").onViewportEnter( (event) => {
  let targetId = event.target.id; // "myElement"
});

onViewportLeave( )

Adds an event handler that runs when an element is no longer displayed in the viewable part of the current window.

Description

An element leaves the viewport when the page is scrolled so that the element is completely out of view. An element also leaves the viewport if it was shown or expanded and is then hidden or collapsed from the viewable part of the current window. onViewportLeave() is not fired for hidden or collapsed elements even if they are scrolled out of view.

Note

Deprecation note: The $w parameter of event handlers is being deprecated. To get a scoped selector for working with elements in repeater items, use the $w.at() function and pass it the context property of the event parameter: $item = $w.at(event.context). To learn more, see here.

See Also

onViewportEnter( )

Syntax

function onViewportLeave(handler: EventHandler): Element
callback EventHandler(event: Event, $w: $w): void
PARAMETERS
?
Values that you pass to a function.
handler
function(event: Event, $w: $w)

The name of the function or the function expression to run when the element leaves the viewport.

?
Values that you pass to a function.
event
The event that occurred.
$w

Deprecated: A selector function. The $w function was used to enable event handlers to work with elements in repeaters. Now, to get a scoped selector for working with repeater items, use the $w.at() function and pass it the context property of the event parameter: $item = $w.at(event.context).

RETURN VALUE
?
Value that a function evaluates to when it is finished running.
The element on which the event is now registered.

MIXED IN FROM

?
Where this functionality is inherited from.
$w.Element

Examples

Get the ID of the element that has left the viewport

$w("#myElement").onViewportLeave( (event) => {
  let targetId = event.target.id; // "myElement"
});

scrollTo( )

Scrolls the page to the element using an animation.

Description

The scrollTo() function returns a Promise that is resolved when the animated scroll is complete and the element is now in view.

To scroll to a specific location on the page, see the wix-window scrollTo() function.

Calling the scrollTo() function on an element in a repeated item that is selected from the global scope causes an error.

Syntax

function scrollTo(): Promise<void>
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>
Fulfilled - When the scroll is complete.

MIXED IN FROM

?
Where this functionality is inherited from.
$w.Element

Examples

Scroll the page to an element

$w("#myElement").scrollTo();

Scroll the page to an element and log message when done

$w("#myElement").scrollTo()
  .then( ( ) => {
    console.log("Done with scroll");
} );

setAttribute( )

Sets an HTML attribute on the custom element's DOM node.

Description

We can use setAttribute() to affect the custom element's definition and behavior. Consider setAttribute() a way for Corvid to pass information to the custom element based on the context of the site.

Each setAttribute() function sets one attribute at a time using a key-value pair. Use multiple setAttribute() functions to set more than one attribute.

If the custom element does not yet have the attribute, setAttribute() creates it.

Syntax

function setAttribute(key: string, value: string): void
PARAMETERS
?
Values that you pass to a function.
key
string
The name of the attribute. Use lowercase characters.
value
string
The value of the attribute.

Examples

Set the attribute of a custom element

// **********************************************
// Custom Element Code in Corvid 
// **********************************************

import wixUsers from 'wix-users';

// Set the `is-logged-in' attribute of the 
// custom element. Its value will be true/false, 
// depending on whether the
// user is currently logged-in.
// Remember to use lowercase characters for the 
// name of the attribute.

$w('#myCE').setAttribute('logged-in', wixUsers.currentUser.loggedIn);


// **********************************************
// Custom Element Implementation on an HTML Page
// **********************************************

class MyElement extends HTMLElement {

  connectedCallback() {
    this.innerHTML = 'Hello World!'
    this.dispatchEvent(new CustomEvent('my-event'))
  }
}
customElements.define('my-custom-element', MyElement);
  

// *****************************************************
// Custom Element's Result
// *****************************************************

// In the result, we can see the `is-logged-in` 
// attribute and its value
// as set in Corvid using `setAttribute()`.

<my-custom-element logged-in="true">Hello World!</my-custom-element>

Set a custom element attribute with info about the page from Corvid

Learn more about this example.
// **********************************************
// Custom Element Implementation on an HTML Page
// **********************************************

// Code to set up variables and styles for the logo. 
const LOGO_TXT = 'https://static.wixstatic.com/media/logo-txt.png';
const LOGO_IMG = 'https://static.wixstatic.com/media/logo-img.png';
const LOGO_PHONE ='https://static.wixstatic.com/media/logo-phone.png';

const STYLE = `
#img.shake {
    animation: shake 0.5s;
    animation-iteration-count: infinite;
  }

  @keyframes shake {
    0% { transform: translate(1px, 1px) rotate(0deg); }
    10% { transform: translate(-1px, -2px) rotate(-1deg); }
    20% { transform: translate(-3px, 0px) rotate(1deg); }
    30% { transform: translate(3px, 2px) rotate(0deg); }
    40% { transform: translate(1px, -1px) rotate(1deg); }
    50% { transform: translate(-1px, 2px) rotate(-1deg); }
    60% { transform: translate(-3px, 1px) rotate(0deg); }
    70% { transform: translate(3px, 1px) rotate(-1deg); }
    80% { transform: translate(-1px, -1px) rotate(1deg); }
    90% { transform: translate(1px, 2px) rotate(0deg); }
    100% { transform: translate(1px, -2px) rotate(-1deg); }
  }
`;

// Code to check if the size of the custom element has 
// changed. 
const dispatchSizeChange = (root,scaleTxt) => {
  const gettingSmall = scaleTxt === 0 && root.prevScaleTxt !== 0;
  const gettingBig = scaleTxt !== 0 && root.prevScaleTxt === 0;
  root.prevScaleTxt = scaleTxt;

  // Use dispatchEvent() to create a new custom event that 
  // Corvid can handle. In our example, the event is 
  // triggered when the size of the custom element gets bigger or 
  // smaller.
  if (gettingSmall || gettingBig) {
    root.dispatchEvent(new CustomEvent('sizeChange', 
        { detail: { data: gettingSmall ? 'small' : 'big' } }));
  }
};

// Code to rotate and resize the custom element. 
const scrollHandler = root => (event) => {
  const txt = root.querySelector('#txt');
  const scaleTxt = (Math.max(0, 1000 - window.scrollY)) / 1000;
  txt.style.transform = `scale(${scaleTxt})`;
  dispatchSizeChange(root, scaleTxt);
  const opacityTxt = 1 / Math.log10(Math.max(10, window.scrollY));
  txt.style.opacity = opacityTxt;
  const img = root.querySelector('#img');
  img.style.transform = `rotate(${window.scrollY / 10}deg)`;
}

// Code to create each image that the logo comprises and 
// add the logo to the DOM using a `createImg()` function.
const createImg = (id, src) => {
  const img = document.createElement('img');
  img.src = src;
  img.id = id;
  img.width = '200';
  img.style.position = 'fixed';
  return img;
}

// Code to define the custom element based on the 
// definitions above.
class allEffects extends HTMLElement {

  constructor() {
    super();

    document.addEventListener('wheel', scrollHandler(this), {
        capture: false, passive: true })
        const style = document.createElement('style');
        style.innerHTML = STYLE;
        this.appendChild(style);
  }

  // Code for a special lifecycle function `connectedCallback()`
  // that runs when the custom element is connected initially to the DOM.
  // This function displays the various parts of the logo.
  connectedCallback() {
    this.appendChild(createImg('txt', LOGO_TXT));
    this.appendChild(createImg('img', LOGO_IMG));
    this.appendChild(createImg('img', LOGO_PHONE));
    const phone = createImg('phone', LOGO_PHONE);
    phone.style.display = 'none';
    this.appendChild(phone);
  }

  // Code for a special lifecycle function `attributeChangedCallback()`
  // that checks if the context of the page has changed. 
  attributeChangedCallback(name, oldValue, newValue) {   
    if (name === 'hoveringmenu') {
      this.querySelector('#img').className = newValue === 'true' ? 'shake' : '';
    }
    if (name === 'footershown') {
      this.querySelector('#phone').style.display = newValue === 'true' ? '' : 'none';
    }
  }

  // Code for a special lifecycle function `observedAttributes()`
  // that checks specific attributes on the page. 
  static get observedAttributes() {
    return ['hoveringmenu', 'footershown'];
  }
}

// Code to register the custom element. The name `my-logo-effects` is the 
// tag name to specify when adding the custom element in the Wix 
// Editor to the site. Make sure the tag name is in lowercase characters. 
customElements.define('my-logo-effects', allEffects);
  

// **********************************************
// Corvid Code for Custom Element on Page
// **********************************************

// Use `on()` to handle the `sizeChange` event defined in the 
// custom element. In this case, if the logo is very small, 
// the menu on the page is hidden. This is because one of the 
// defined behaviors of the element is that the logo gets 
// smaller as we scroll down the page.
$w.onReady(function () {
  $w('#myCustomElement').on('sizeChange', ({detail: {data}}) => {
    if (data === 'small') {
      $w('#menu').hide();
    } else {
      $w('#menu').show();
    }
  })
});

// **********************************************
// Corvid Code for Custom Element on the Site
// **********************************************

// The custom element's behavior will change for the entire
//  site in the following cases: 
// 
// + If the footer enters or leaves the viewport.
// + If the site visitor's mouse hovers or stops hovering over the menu.
// 
// Corvid "sends" the custom element attributes using `setAttribute()`
// so the element can process and and affect the element's behaviors
// according to the context on the page. 
export function footer1_viewportEnter(event) {
  $w('#myCustomElement').setAttribute('footershown', true);
 }
export function footer1_viewportLeave(event) {
 $w('#myCustomElement').setAttribute('footershown', false);
}
export function menu_mouseIn(event) {
 $w('#myCustomElement').setAttribute('hoveringmenu', true);
}
export function menu_mouseOut(event) {
 $w('myCustomElement').setAttribute('hoveringmenu', false);
}

show( )

Shows the element and sets its hidden property to false, using an effect if specified.

Description

The show() function shows the element and returns a Promise that is resolved when the effect is complete and the element's hidden property has been set to false.

You can optionally apply an effect when showing the element by providing an effectName value. You can also customize the effect by providing the optional effectOptions object.

Effects:

See Also

hide( ), hidden, expand( )

Syntax

function show([effectName: string], [effectOptions: ArcEffectOptions | BounceEffectOptions | FadeEffectOptions | FlipEffectOptions | FloatEffectOptions | FlyEffectOptions | FoldEffectOptions | GlideEffectOptions | PuffEffectOptions | RollEffectOptions | SlideEffectOptions | SpinEffectOptions | TurnEffectOptions | ZoomEffectOptions]): Promise<void>
RETURN VALUE
?
Value that a function evaluates to when it is finished running.
Promise<void>
Fulfilled - When the effect is complete and the element's hidden property has been set to false.

MIXED IN FROM

?
Where this functionality is inherited from.
$w.HiddenCollapsedMixin

Examples

Show an element with no effect

$w("#myElement").show();

Show an element with the "fade" effect

$w("#myElement").show("fade");

Show an element with the "fade" effect and custom options

let fadeOptions = {
  "duration":   2000,
  "delay":      1000
};

$w("#myElement").show("fade", fadeOptions);

Show an element with an effect and log a message when the effect is done

$w("#myElement").show("fade")
  .then( ( ) => {
    console.log("Done with fade");
  } );

Toggle an element's hidden state

if( $w("#myElement").hidden ) {
  $w("#myElement").show();
}
else {
  $w("#myElement").hide();
}