Search code examples
htmlweb-component

Error creating a Web component


I'm new to Web components and I am trying to create a very simple component to understand how it works. But I have a problem creating one. I followed the steps mentioned in both chrome and Mozilla docs but I still cant create one successfully and also couldn't find the problem.

class toolTip extends HTMLElement {
  var msg = this.getAttribute('msg');
  var value = this.getAttribute('value');
  console.log(msg);
  console.log(value);
  this.innerHTML = msg + ' - ' + value;
}

customElements.define('mdm-tooltip', toolTip);
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Web Components</title>
</head>

<body>
  <mdm-tooltip value='1st tooltip' msg='this the 1st tooltip created using WC'></mdm-tooltip>
  <mdm-tooltip value='2nd tooltip' msg='I replaced the existing text'>Im the existing text</mdm-tooltip>
</body>
<script src="main.js" defer></script>

</html>

This is the error browser throws, I'm running this code in Chrome V67.0.3396.99

This is error browser throws


Solution

  • Within a class, you need to define methods that actually contain executable code. In your case, your code looks a lot like initialization code, so a constructor seems appropriate.

    class ToolTip extends HTMLElement {
        constructor() {
            let msg = this.getAttribute('msg');
            let value = this.getAttribute('value');
            console.log(msg);
            console.log(value);
            this.innerHTML = msg + ' - ' + value;
        }
    }
    
    customElements.define('mdm-tooltip', ToolTip);
    

    Also, one of the naming conventions in JavaScript is that classes should be pascal-cased (start with a capital letter).