I want to add a click event to the button with id: hamb-btn, where when clicked it will add a new class in the div class = "nav-link show" element. like that is an example of adding the class if the hamb button is pressed. its my code... note: i use webpack.
import { html, css, LitElement } from 'lit-element'; class SinDrawer extends LitElement { static get styles() { return css` nav { display: flex; padding: 8px; background-color: var(--main-color); } `; } constructor() { super(); } render() { return html` <nav> <div class="nav-brand"> <a href="#/home"> <img src="./icons/icon_512.png" alt="sr-brand" height="50" title="Sinfor-Resto"> </a> </div> <div class="nav-link"> <a href="#/home" class="nav-anchor">Beranda</a> <a href="#/favorite" class="nav-anchor">Favorite</a> <a href="#/about" class="nav-anchor">Tentang</a> </div> <button id="hamb-btn" onclick="">☰</button> </nav> `; } } customElements.define('sin-drawer', SinDrawer);
You can always use classMap
or styleMap
directives for the dynamic styling in the Lit Component. More information available at Dynamic classes and styles .
import { html, css, LitElement } from 'lit-element';
import { classMap } from 'lit/directives/class-map.js';
class SinDrawer extends LitElement {
static get styles() {
return css`
nav {
display: flex;
padding: 8px;
background-color: var(--main-color);
}
`;
}
static get properties() {
return {
_show: { state: true },
};
}
constructor() {
super();
this._show = false;
}
show() {
this._show = !this._show;
}
render() {
return html`
<nav>
<div class="nav-brand">
<a href="#/home">
<img src="./icons/icon_512.png" alt="sr-brand" height="50" title="Sinfor-Resto" />
</a>
</div>
<div class="nav-link ${classMap({ show: this._show })}">
<a href="#/home" class="nav-anchor">Beranda</a>
<a href="#/favorite" class="nav-anchor">Favorite</a>
<a href="#/about" class="nav-anchor">Tentang</a>
</div>
<button id="hamb-btn" @click=${this.show}>☰</button>
</nav>
`;
}
}
customElements.define('sin-drawer', SinDrawer);
This can be done in 3 simple steps.
static get properties(){
return{
newClass: String
}
}
<div class="nav-link ${this.newClass}">
<button id="hamb-btn" @click=${e=>this.newClass =”newClassName”}>☰</button>
Since this.newClass is added to properties of the element, it will rerender the DOM and update the div with class=”nav-link newClassName”
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.