DEV Community

loading...

A simple OffCanvas webComponent

artydev
・1 min read

There are dozens libraries to create custom elements.
For this demo, I have choosen uce.

If you have any questions or suggestions, feel free to comment.

Here, I have defined two custom elements:

  • my-sidebar
  • my-link

Here is how they ared used in an html page :

<div class="topbar">
  <my-sidebar>
    <my-link label='Google' target="https://www.google.com"></my-link>
  </my-sidebar>
  <div style="text-align:center">
    Custom side bar with uce
  </div>
  <div>
    About
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

The JS part :


const {html, define, render} = uce

 define("my-sidebar", {
    init() {
      this.width = this.getAttribute("width") || 250
      this.links = Array
        .from(this.querySelectorAll("my-link"))
        .map(l => ({
          label: l.getAttribute("label"),
          target: l.getAttribute("target")
        }))
      this.render()
    },
    render() {
      this.html`
        <div id="mySidenav" class="sidenav">
          <a class=${`closebtn `} onclick=${()=> this.closeNav()}>X</a>
          <div style='border-bottom:1px solid grey;position:relative;top:-11px'></div>
          ${this.links.map(l => html`<a href="${l.target}">${l.label}</a>`)}
        </div>
        <span style="font-size:30px;cursor:pointer" onclick=${()=> this.openNav()}>&#9776</span>
      `
    },
    openNav() {
      (mySidenav).style.width = "250px"
    },
    closeNav() {
      (mySidenav).style.width = "0px"
    }
  })

  define("my-link", {})

Enter fullscreen mode Exit fullscreen mode

You can test it here : UceOffCanvas

Discussion (0)

Forem Open with the Forem app