on( )
Registers a callback function in Velo for an event triggered from the custom element.
Description
The on()
function registers a callback function in Velo 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 Velo.
In Custom Element Implementation:
Javascript | Copy CodeconnectedCallback() {this.addEventListener('click', () => {this.dispatchEvent(new CustomEvent('my-event',{ detail: 'my-event-data' }));})}
In Velo Implementation:
Javascript | Copy Code$w('#myCustomElement').on('my-event', (event) => {console.log('The event triggered successfully.');console.log('Received the following info from my-event: ', event.detail);});
Syntax
function on(eventName: string, callBackFunction: Function): void
on Parameters
NAME
TYPE
DESCRIPTION
The name of the event.
The callback function to run when the event is triggered.
Returns
This function does not return anything.
Return Type:
Was this helpful?
1// **********************************************2// Custom Element Code in Velo3// **********************************************45// Handle an event on the custom element.6$w('#myCE').on('my-event', (event) => {7 console.log('The event triggered successfully.');8 console.log('Info received from my-event: ', event.detail);9});101112// **********************************************13// Custom Element Implementation on an HTML Page14// **********************************************1516class MyElement extends HTMLElement {17 connectedCallback() {18 this.innerHTML = 'Hello World!';1920 // Trigger a click event that Velo can watch for21 // and handle using the on() function.22 this.addEventListener('click', () => {23 this.dispatchEvent(new CustomEvent('my-event',24 {detail: 'my-event-data'}));25 });26 }27}28customElements.define('my-custom-element', MyElement);293031// ************************************************32// Custom Element's Result33// ************************************************3435<my-custom-element>Hello World!</my-custom-element>363738// ************************************************39// Logged When Custom Element is Clicked40// ************************************************41//42// The event triggered successfully.43// Info received from my-event: my-event-data
1// **********************************************2// Custom Element Implementation on an HTML Page3// **********************************************45// Code to set up variables and styles for the logo.6const LOGO_TXT = 'https://static.wixstatic.com/media/logo-txt.png';7const LOGO_IMG = 'https://static.wixstatic.com/media/logo-img.png';8const LOGO_PHONE ='https://static.wixstatic.com/media/logo-phone.png';910const STYLE = `11#img.shake {12 animation: shake 0.5s;13 animation-iteration-count: infinite;14 }1516 @keyframes shake {17 0% { transform: translate(1px, 1px) rotate(0deg); }18 10% { transform: translate(-1px, -2px) rotate(-1deg); }19 20% { transform: translate(-3px, 0px) rotate(1deg); }20 30% { transform: translate(3px, 2px) rotate(0deg); }21 40% { transform: translate(1px, -1px) rotate(1deg); }22 50% { transform: translate(-1px, 2px) rotate(-1deg); }23 60% { transform: translate(-3px, 1px) rotate(0deg); }24 70% { transform: translate(3px, 1px) rotate(-1deg); }25 80% { transform: translate(-1px, -1px) rotate(1deg); }26 90% { transform: translate(1px, 2px) rotate(0deg); }27 100% { transform: translate(1px, -2px) rotate(-1deg); }28 }29`;3031// Code to check if the size of the custom element has32// changed.33const dispatchSizeChange = (root,scaleTxt) => {34 const gettingSmall = scaleTxt === 0 && root.prevScaleTxt !== 0;35 const gettingBig = scaleTxt !== 0 && root.prevScaleTxt === 0;36 root.prevScaleTxt = scaleTxt;3738 // Use dispatchEvent() to create a new custom event that39 // Velo can handle. In our example, the event is40 // triggered when the size of the custom element gets bigger or41 // smaller.42 if (gettingSmall || gettingBig) {43 root.dispatchEvent(new CustomEvent('sizeChange',44 { detail: { data: gettingSmall ? 'small' : 'big' } }));45 }46};4748// Code to rotate and resize the custom element.49const scrollHandler = root => (event) => {50 const txt = root.querySelector('#txt');51 const scaleTxt = (Math.max(0, 1000 - window.scrollY)) / 1000;52 txt.style.transform = `scale(${scaleTxt})`;53 dispatchSizeChange(root, scaleTxt);54 const opacityTxt = 1 / Math.log10(Math.max(10, window.scrollY));55 txt.style.opacity = opacityTxt;56 const img = root.querySelector('#img');57 img.style.transform = `rotate(${window.scrollY / 10}deg)`;58}5960// Code to create each image that the logo comprises and61// add the logo to the DOM using a createImg() function.62const createImg = (id, src) => {63 const img = document.createElement('img');64 img.src = src;65 img.id = id;66 img.width = '200';67 img.style.position = 'fixed';68 return img;69}7071// Code to define the custom element based on the72// definitions above.73class allEffects extends HTMLElement {7475 constructor() {76 super();7778 document.addEventListener('wheel', scrollHandler(this), {79 capture: false, passive: true })80 }8182 // Code for a special lifecycle function connectedCallback()83 // that runs when the custom element is connected initially to the DOM.84 // This function displays the various parts of the logo.85 connectedCallback() {86 this.appendChild(createImg('txt', LOGO_TXT));87 this.appendChild(createImg('img', LOGO_IMG));88 const phone = createImg('phone', LOGO_PHONE);89 phone.style.display = 'none';90 this.appendChild(phone);9192 const style = document.createElement('style');93 style.innerHTML = STYLE;94 this.appendChild(style);9596 }9798 // Code for a special lifecycle function attributeChangedCallback()99 // that checks if the context of the page has changed.100 attributeChangedCallback(name, oldValue, newValue) {101 if (name === 'hoveringmenu') {102 this.querySelector('#img').className = newValue === 'true' ? 'shake' : '';103 }104 if (name === 'footershown') {105 this.querySelector('#phone').style.display = newValue === 'true' ? '' : 'none';106 }107 }108109 // Code for a special lifecycle function observedAttributes()110 // that checks specific attributes on the page.111 static get observedAttributes() {112 return ['hoveringmenu', 'footershown'];113 }114}115116// Code to register the custom element. The name my-logo-effects is the117// tag name to specify when adding the custom element in the Wix118// Editor to the site. Make sure the tag name is in lowercase characters.119customElements.define('my-logo-effects', allEffects);120121122// **********************************************123// Velo Code for Custom Element on Page124// **********************************************125126// Use on() to handle the sizeChange event defined in the127// custom element. In this case, if the logo is very small,128// the menu on the page is hidden. This is because one of the129// defined behaviors of the element is that the logo gets130// smaller as we scroll down the page.131$w.onReady(function () {132 $w('#myCustomElement').on('sizeChange', ({detail: {data}}) => {133 if (data === 'small') {134 $w('#menu').hide();135 } else {136 $w('#menu').show();137 }138 })139});140141// **********************************************142// Velo Code for Custom Element in masterPage.js143// **********************************************144145// The custom element's behavior will change for the entire146// site in the following cases:147//148// + If the footer enters or leaves the viewport.149// + If the site visitor's mouse hovers or stops hovering over the menu.150//151// Velo "sends" the custom element attributes using setAttribute()152// so the element can process and and affect the element's behaviors153// according to the context on the page.154$w('#footer1').onViewportEnter((event) => {155 $w('#myCustomElement').setAttribute('footershown', true);156});157$w('#footer1').onViewportLeave((event) => {158 $w('#myCustomElement').setAttribute('footershown', false);159});160$w('#menu').onMouseIn((event) => {161 $w('#myCustomElement').setAttribute('hoveringmenu', true);162});163$w('#menu').onMouseOut((event) => {164 $w('myCustomElement').setAttribute('hoveringmenu', false);165});
This example shows how to to embed a Web Component in a page. In this example, we demonstrate sending information from the page to the Custom Element and from the Custom Element to the page. You can test out the code in our example template.
1/******************2 * Home Page Code *3 ******************/45$w.onReady(function () {6 $w('#customElement').on('sayHello', ({ detail: { data } }) => {7 $w('#message').text = data;8 })910 $w('#sendButton').onClick(() => {11 $w('#customElement').setAttribute('msg', "HELLO FROM THE PAGE");12 });13});1415/*********************************************16 * Custom Element Implementation in .js File *17 *********************************************/1819const createH2 = () => {20 const h2Element = document.createElement('h2');21 h2Element.textContent = 'THIS IS THE CUSTOM ELEMENT';22 h2Element.id = 'hello-h2';23 return h2Element;24};2526const createP = () => {27 const pElement = document.createElement('p');28 pElement.textContent = 'MESSAGE FROM PAGE WILL SHOW HERE';29 pElement.id = 'hello-p';30 return pElement;31};3233const createButton = () => {34 const buttonElement = document.createElement('button');35 buttonElement.textContent = 'Button';36 buttonElement.id = 'hello-button';37 return buttonElement;38};3940const createContainer = () => {41 const container = document.createElement('div');42 container.id = 'hello-container';43 return container;44};4546const createStyle = () => {47 const styleElement = document.createElement('style');48 styleElement.innerHTML = `49 hello-world {50 background-color: black;51 display: flex;52 height: 100%;53 height: -moz-available;54 height: -webkit-fill-available;55 width: 100%;56 justify-content: center;57 }5859 #hello-container {60 border: 2px inset blue;61 display: flex;62 flex-direction: column;63 width: 100%;64 justify-content: center;65 text-align:center;66 }6768 #hello-h2 {69 font-size: 24px;70 color: white;71 }7273 #hello-p {74 font-size: 20px;75 color: white;76 }7778 #hello-button {79 border: none;80 color: white;81 padding: 15px 32px;82 text-align: center;83 text-decoration: none;84 display: inline-block;85 font-size: 16px;86 margin: 4px 200px;87 cursor: pointer;88 background-color: blue89 }90 `;91 return styleElement;92};9394class HelloWorld extends HTMLElement {95 constructor() {96 super();97 }9899 connectedCallback() {100 this.appendChild(createStyle());101 let container = createContainer();102 let button = createButton();103 button.addEventListener('click', () => {104 this.dispatchEvent(new CustomEvent('sayHello', { detail: { data: 'HELLO FROM THE CUSTOM ELEMENT' } }));105 });106 container.appendChild(createH2());107 container.appendChild(document.createElement('br'));108 container.appendChild(createP());109 container.appendChild(document.createElement('br'));110 container.appendChild(button);111 this.appendChild(container);112 }113114 get msg() {115 return this.getAttribute('msg');116 }117118 set msg(value) {119 this.setAttribute('msg', value);120 }121122 static get observedAttributes() {123 return ['msg'];124 }125126 attributeChangedCallback(name, oldVal, newVal) {127 this.render();128 }129130 render() {131 document.getElementById('hello-p').textContent = this.msg;132 }133}134customElements.define('hello-world', HelloWorld);