Search.../

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:

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
key
string

The name of the attribute. Use lowercase characters.

value
string | boolean | number

The value of the attribute.

Returns

This function does not return anything.

Return Type:

void

Was this helpful?

Set the attribute of a custom element

Copy Code
1// **********************************************
2// Custom Element Code in Velo
3// **********************************************
4
5import { authentication } from 'wix-members-frontend';
6
7// Set the is-logged-in attribute of the
8// custom element. Its value will be true/false,
9// depending on whether the
10// user is currently logged-in.
11// Remember to use lowercase characters for the
12// name of the attribute.
13
14const isLoggedIn = authentication.loggedIn();
15$w('#myCE').setAttribute('logged-in', isLoggedIn);
16
17
18// **********************************************
19// Custom Element Implementation on an HTML Page
20// **********************************************
21
22class MyElement extends HTMLElement {
23 connectedCallback() {
24 this.innerHTML = 'Hello World!'
25 this.dispatchEvent(new CustomEvent('my-event'));
26 };
27
28// Function that is called whenever an attribute of the
29// custom element is added, removed, or changed.
30 attributeChangedCallback(name, oldValue, newValue) {
31 console.log("Attribute changed.");
32 console.log(name, oldValue, newValue);
33 };
34
35// 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);
42
43
44// *****************************************************
45// Custom Element's Result
46// *****************************************************
47
48// In the result, we can see the is-logged-in
49// attribute and its value as set in Velo
50// using the setAttribute() function.
51
52<my-custom-element logged-in="true">Hello World!</my-custom-element>
53
54
55// ************************************************
56// Logged When Member Logs In
57// ************************************************
58//
59// Attribute changed.
60// logged-in null true
Set a custom element attribute with info about the page from Velo

Copy Code
1// **********************************************
2// Custom Element Implementation on an HTML Page
3// **********************************************
4
5// 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';
9
10const STYLE = `
11#img.shake {
12 animation: shake 0.5s;
13 animation-iteration-count: infinite;
14 }
15
16 @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`;
30
31// Code to check if the size of the custom element has
32// 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;
37
38 // Use dispatchEvent() to create a new custom event that
39 // Velo can handle. In our example, the event is
40 // triggered when the size of the custom element gets bigger or
41 // smaller.
42 if (gettingSmall || gettingBig) {
43 root.dispatchEvent(new CustomEvent('sizeChange',
44 { detail: { data: gettingSmall ? 'small' : 'big' } }));
45 }
46};
47
48// 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}
59
60// Code to create each image that the logo comprises and
61// 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}
70
71// Code to define the custom element based on the
72// definitions above.
73class allEffects extends HTMLElement {
74
75 constructor() {
76 super();
77
78 document.addEventListener('wheel', scrollHandler(this), {
79 capture: false, passive: true })
80 }
81
82 // 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);
91
92 const style = document.createElement('style');
93 style.innerHTML = STYLE;
94 this.appendChild(style);
95
96 }
97
98 // 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 }
108
109 // 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}
115
116// Code to register the custom element. The name my-logo-effects is the
117// tag name to specify when adding the custom element in the Wix
118// Editor to the site. Make sure the tag name is in lowercase characters.
119customElements.define('my-logo-effects', allEffects);
120
121
122// **********************************************
123// Velo Code for Custom Element on Page
124// **********************************************
125
126// Use on() to handle the sizeChange event defined in the
127// custom element. In this case, if the logo is very small,
128// the menu on the page is hidden. This is because one of the
129// defined behaviors of the element is that the logo gets
130// 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});
140
141// **********************************************
142// Velo Code for Custom Element in masterPage.js
143// **********************************************
144
145// The custom element's behavior will change for the entire
146// 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 behaviors
153// 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});
Create and embed a Web Component in a page

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.

Copy Code
1/******************
2 * Home Page Code *
3 ******************/
4
5$w.onReady(function () {
6 $w('#customElement').on('sayHello', ({ detail: { data } }) => {
7 $w('#message').text = data;
8 })
9
10 $w('#sendButton').onClick(() => {
11 $w('#customElement').setAttribute('msg', "HELLO FROM THE PAGE");
12 });
13});
14
15/*********************************************
16 * Custom Element Implementation in .js File *
17 *********************************************/
18
19const createH2 = () => {
20 const h2Element = document.createElement('h2');
21 h2Element.textContent = 'THIS IS THE CUSTOM ELEMENT';
22 h2Element.id = 'hello-h2';
23 return h2Element;
24};
25
26const 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};
32
33const createButton = () => {
34 const buttonElement = document.createElement('button');
35 buttonElement.textContent = 'Button';
36 buttonElement.id = 'hello-button';
37 return buttonElement;
38};
39
40const createContainer = () => {
41 const container = document.createElement('div');
42 container.id = 'hello-container';
43 return container;
44};
45
46const 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 }
58
59 #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 }
67
68 #hello-h2 {
69 font-size: 24px;
70 color: white;
71 }
72
73 #hello-p {
74 font-size: 20px;
75 color: white;
76 }
77
78 #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: blue
89 }
90 `;
91 return styleElement;
92};
93
94class HelloWorld extends HTMLElement {
95 constructor() {
96 super();
97 }
98
99 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 }
113
114 get msg() {
115 return this.getAttribute('msg');
116 }
117
118 set msg(value) {
119 this.setAttribute('msg', value);
120 }
121
122 static get observedAttributes() {
123 return ['msg'];
124 }
125
126 attributeChangedCallback(name, oldVal, newVal) {
127 this.render();
128 }
129
130 render() {
131 document.getElementById('hello-p').textContent = this.msg;
132 }
133}
134customElements.define('hello-world', HelloWorld);