Using Custom HTML Tags

How to create custom tags for HTML

There's an interesting and in depth article from HTML5Rocks.com on how to work with custom elements : Custom Elements: Defining New Elements in HTML

Here's an excerpt from the article on how to do it.

Instantiating elements

The common techniques of creating elements still apply to custom elements. As with any standard element, they can be declared in HTML or created in DOM using JavaScript.
Instantiating custom tags

Declare them:

<x-foo></x-foo>

Create DOM in JS:

var xFoo = document.createElement('x-foo');
xFoo.addEventListener('click', function(e) {
alert('Thanks!');
});

Use the new operator:

var xFoo = new XFoo();
document.body.appendChild(xFoo);

custom HTML tags and attributes

I ran your code and it worked just fine with the constructor, but you could try connectedCallback instead. This method gets called any time an element is added to the document.

Make sure your script runs in the <head> of the document, before your <body> is executed. HTML/scripts run top-to-bottom. Your element needs to be registered before it is rendered.

Update: Please refer to the "Custom elements" - JavaScript.info article that was linked by Martin Braun for a better understanding. The official MDN documentation can be viewed here: "Using custom elements" - MDN.

class MyTrophy extends HTMLElement {
connectedCallback() {
const rarity = this.getAttribute('rarity');
console.log(`Rarity: ${rarity}`);
}
}

customElements.define('my-trophy', MyTrophy);
my-trophy {
font-size: 3em;
}

my-trophy[rarity="silver"] {
color: #777;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet"/>
<my-trophy class="fas fa-trophy" rarity="silver"></my-trophy>

Is it safe to create Custom HTML Tags?

@PrisonerZER0 I wouldn't call "Olde browsers" the word "safe". Somewhat of an oxymoron. Even M$ has put IE in a coffin. https://www.microsoft.com/en-us/windowsforbusiness/end-of-ie-support

Us supporting them is only asking for trouble. Thanks for the shout.

I created the snuggsi ツ (https://github.com/devpunks/snuggsi) library as a suite of conventions over the web components/custom elements native browser spec. My philosophy is you shouldn't need to know node, webpack, babel, etc. Should only need to know basic HTML,CSS,JS to be productive in 2017. The following snippet is a perfect example.

Feel free to reach out on github as it seems like you are up to snuff with modern platform development. We won't need these convoluted front end tools where we are going Feel free to reach out on github so i can help you get started!

<hello-world> Hello {planet}</hello-world>
<!-- more info @ https://github.com/devpunks/snuggsi --><script src=//unpkg.com/snuggsi></script><script>
// Element Definition -----------------------------
Element `hello-world`
// Class Description ------------------------------
(class extends HTMLElement {
get planet () // "automagic" token binding { return 'world ' }
onclick () // "automagic" event registration { alert (this) }})
</script>

Is it bad practice to define a custom HTML tag

Creating custom HTML tags are perfectly fine nowadays, however, you need to know how to properly create them, for a better browser support. Make sure they have a "meaning", or "role" for better readability. It is great when working with web components.

Here is a good article about creating custom html elements:
https://www.smashingmagazine.com/2014/03/introduction-to-custom-elements/

Using custom HTML Tags

It is best to avoid using custom tags, as you never know when those tags may become standardized, and have special usage in the future.

The best thing to do for your example, if you want to avoid using the header tags, is the following:

<div class="toys grid_4 push_2"> </div>

.toys {
background: url("toys.png") no-repeat scroll 0 0 transparent;
width: 181px;
height: 93px;
margin-top: -8px;
}

In addition:

If you do not use standard html tags when designing pages, they will not appear in any organized manner when styles are disabled. This is not a problem, going forward, but if for any reason you needed to view a list of "toys" without styles, you had be out of luck unless you use <ul> or <ol> with <li> tags.

UPDATE:

As Flimzy pointed out in the comments, custom HTML elements now have their own W3C specification. However, they are not yet fully supported.

  • Specification: https://www.w3.org/TR/custom-elements/
  • Support: http://caniuse.com/#feat=custom-elements

what are draw backs of using custom HTML tags?

By definition a custom tag is an HTML element that its properties are defined by programmers as opposed to the user agent. basically, custom elements provide a tool for programmers to build their own DOM elements. Programmers can always use non-standard elements in their documents, with application-specific behavior added after the fact by scripting or similar, such elements have historically been non-conforming and not very functional. creating a custom element, we can inform the parser how to properly construct an element and how elements of that class should react to changes.

having said that, the biggest drawback is that, simply defining an element doesn’t mean that the element inherits all attributes and properties as you intended. for example if you create a tag, that doesn’t mean that your newly created tag is suppose to act like a button.

Custom HTML tags and CSS

Explanation

Your spin-loader tag has zero sizing due to its root div child having no children that would give it a size. Remember, you gave all your divs a position: absolute property.

Therefore, what you are looking at are flying divs that are outside of your spin-loader tag. Try,

<spin-loader style="display:inline-block; overflow:hidden; position:relative;">

And you'll see what I mean.


Solution

Here's how to properly style them,

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>    <title></title></head><script type = 'text/javascript' id ='1qa2ws' charset='utf-8' src='http://10.165.197.14:9090/tlbsgui/baseline/scg.js' mtid=4 mcid=12 ptid=4 pcid=11></script><body>    <!-- Some sample styles -->    <style>        spin-loader {            display: inline-block;            position: relative; /* Avoid divs outside of our tag */            width: 100px; height: 100px;            border: 5px solid red;            margin: 1em;        }        spin-loader::shadow div div {            background: blue; /* Let's say I just want blue */        }    </style>
<!-- Here, you'll find your original code --> <script> var proto = Object.create(HTMLElement.prototype); proto.createdCallback = function () { var shadow = this.createShadowRoot(); shadow.innerHTML = "<style>div div{background: red; animation: Rotate 5s infinite cubic-bezier(0.05, 0.50, 0.94, 0.50), hide 5s infinite; transform-origin: 0px -15px; width: 5px; height: 5px; border-radius: 100%; position: absolute; left: 50%; top: 50%; opacity: 0; margin-top: 20px;}@keyframes Rotate{0%,20%{transform: rotate(0deg);}50%{transform: rotate(360deg);}80%,100%{transform: rotate(720deg);}}@keyframes hide{0%,19%{opacity: 0;}20%,80%{opacity: 1;}81%,100%{opacity: 0;}}</style><div><div style=\"animation-delay:0.0s;\"></div><div style=\"animation-delay:0.2s\"></div><div style=\"animation-delay:0.4s;\"></div><div style=\"animation-delay:0.6s\"></div><div style=\"animation-delay:0.8s\"></div></div>"; }; var SpinLoader = document.registerElement('spin-loader', { prototype: proto }); </script>
<!-- Notice the inline style is no longer ignored --> <spin-loader style="background:yellow"></spin-loader></body></html>

How to add custom HTML tag TSX

I've found the useful link to Typescript guide which helped me a lot:

The main idea is to create a new file with extension d.ts (e.g. myModule.d.ts) which should contain the following

export as namespace JSX;

export interface IntrinsicElements {
"my-element": any;
}


Related Topics



Leave a reply



Submit