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 Velo to pass information to the custom element based on the context of the site.
Attributes can either be set:
- Using this API with
setAttribute()
. - In the Editor, by clicking the custom element's Set Attribute button, without any coding. Tip: Set attributes using the Editor if you would like to share the element with other designers that don't code.
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 | boolean | number): void
setAttribute Parameters
NAME
TYPE
DESCRIPTION
The name of the attribute. Use lowercase characters.
The value of the attribute.
Returns
This function does not return anything.
Return Type:
Was this helpful?
1// **********************************************2// Custom Element Code in Velo3// **********************************************45import { authentication } from 'wix-members-frontend';67// Set the is-logged-in attribute of the8// custom element. Its value will be true/false,9// depending on whether the10// user is currently logged-in.11// Remember to use lowercase characters for the12// name of the attribute.1314const isLoggedIn = authentication.loggedIn();15$w('#myCE').setAttribute('logged-in', isLoggedIn);161718// **********************************************19// Custom Element Implementation on an HTML Page20// **********************************************2122class MyElement extends HTMLElement {23 connectedCallback() {24 this.innerHTML = 'Hello World!'25 this.dispatchEvent(new CustomEvent('my-event'));26 };2728// Function that is called whenever an attribute of the29// custom element is added, removed, or changed.30 attributeChangedCallback(name, oldValue, newValue) {31 console.log("Attribute changed.");32 console.log(name, oldValue, newValue);33 };3435// Static function that checks if attributes changed.36// Works together with attributeChangedCallback().37 static get observedAttributes() {38 return ['logged-in'];39 }40}41customElements.define('my-custom-element', MyElement);424344// *****************************************************45// Custom Element's Result46// *****************************************************4748// In the result, we can see the is-logged-in49// attribute and its value as set in Velo50// using the setAttribute() function.5152<my-custom-element logged-in="true">Hello World!</my-custom-element>535455// ************************************************56// Logged When Member Logs In57// ************************************************58//59// Attribute changed.60// logged-in null true
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);