Attributes on custom HTML elements - html

When working with custom HTML elements in web components, should I still name custom attributes with the prefix data?
For example:
<!-- Should form be data-form? -->
<my-button form="foo">click me</my-button>

No, that's not necessary.
Existing HTML elements have a defined set of attributes, which means you would invalidate the HTML by just adding any attribute. By introducing the data- attributes, it was made possible to extend existing elements without invalidating them.
Web components are custom elements. They have no defined set of attributes, you define them yourself. Whether or not you use data- attributes is completely up to you, but you don't have to. Your component cannot become invalid because there is no definition of valid for it.
If you care about semantic/valid HTML, this answer may be relevant to you too: Are custom elements valid HTML5?. In short: use a dash in your component name to make sure it's picked up as valid HTML.

In general, there is no difference between custom elements and predefined. You might create an element of your choice with document.createElement and register it with document.registerElement. The result would be:
console.log(document.createElement('my-button').constructor);
//⇒ function HTMLElement() { [native code] }
console.log(document.registerElement('my-button'));
//⇒ function my-button() { [native code] }
console.log(document.createElement('my-button').constructor);
//⇒ function my-button() { [native code] }
As you could see, once registered, the element is awarded with it’s own constructor. That provides an ability for components to behave in it’s own way. But:
console.log(document.createElement('my-button').__proto__.__proto__);
//⇒ HTMLElement
is still a good old plain HTMLElement. So, the rules for attribute naming were not changed.
Please note, that libraries, like polymer, might add additional attribute handling; the above is true for plain web-components only.

Related

What does it mean to set data-target attribute of a div to the id of that div?

I'm reading some code and there is a piece of html that reads:
<div id="uniqueId1234" data-target=".uniqueId1234">
...
</div>
and then earlier on in the same html file there is a span element that seems to use this div as a class:
<span class="uniqueId1234">
...
</span>
Can someone explain how this works? I thought that a class was something created in a css file. Sorry if this is a dumb question.
This is likely part of some piece of Javascript code or a library that listens for some type of change or event on your element with the data-target attribute.
When this event is triggered, it can then use the value of that attribute as a selector for performing some other logic as seen in this basic jQuery-based example below:
// When an element containing your data-target attribute is clicked
$('[data-target]').click(function(){
// Find the appropriate target (i.e. ".uniqueId1234")
var target = $(this).data('target');
// Then use it as a selector for some type of operation
$(target).toggle();
});
Classes are very common within CSS to style multiple elements, but they can also commonly be used as a mechanism in Javascript as well, which is likely the case in your scenario here.
What does it mean to set data-target attribute of a div to the id of that div?
Nothing standard. data-* attributes are designed to hold custom data for custom code (typically client side JS) to process.
I thought that a class was something created in a css file.
Classes are an HTML feature used to put elements into arbitrary groups. They are commonly used when writing CSS, but also client side JS and other code.

What is HTML "is" attribute?

I have seen it a lot here and there, yet I could find any description or documentation about it!
Example:
<paper-input-decorator label="Your Name">
<input is="core-input">
</paper-input-decorator>
In 2020:
The is attribute is now part of HTML spec in the Custom Elements specification.
It follows the polymer spec and is documented for developers at mdn.
Only Edge still hasn't updated to include this spec but it its new chromium-based implementation, in 2020, its availability may become widespread.
In 2017:
There is no is attribute in HTML.
It is a proposed extension that appears in the Custom Elements specification (which evolved from the Polymer spec mentioned below).
It allows you to say that an existing, standard element is really a custom element.
<button is="fancy-button" disabled>Fancy button!</button>
… which allows for backwards compatibility. If custom elements are not supported by the browser (the spec is still a draft and has very limited browser support) then it will fall back to the default behaviour.
In 2014:
It is not HTML. It is an expando-attribute for Polymer custom elements.
If you used extends to create a Polymer element that derives from an existing DOM element (something other than HTMLElement), use the is syntax
It is part of the W3C Draft spec for Web Components' Custom Elements.
Latest Working Draft: http://www.w3.org/TR/custom-elements/#type-extension-semantics
Latest Editor's Draft: http://w3c.github.io/webcomponents/spec/custom/#type-extension-example
The is keyword is part of the W3C Draft spec for creating custom HTML elements with custom behavior.
In specific, is is used when extending a built-in element like <input>, <button> or <table>. For example, you could have a plastic-button element that extends <button> to provide some fancy animation when clicked.
You'd add the button to the page like this:
<button is="plastic-button">Click Me!</button>
Before you do this, you need to register plastic-button as a custom HTML element like this:
customElements.define("plastic-button", PlasticButton, { extends: "button" });
This references a PlasticButton Javascript class, which would look something like this:
class PlasticButton extends HTMLButtonElement {
constructor() {
super();
this.addEventListener("click", () => {
// Draw some fancy animation effects!
});
}
}
It'd be great if you could say <plastic-button>Click Me!</plastic-button> instead of <button is="plastic-button">Click Me!</button>, but that would create an HTMLElement with no special behavior.
If you are NOT extending a built-in HTML element like <button> and instead creating a new element that extends the generic HTMLElement, you can use the <plastic-button> syntax. But you won't get any of <button>'s behavior.
This is part of the W3C Draft spec for Web Components' Custom Elements:
http://www.w3.org/TR/custom-elements/#type-extension-semantics
You use the is attribute to markup a customized built-in element, a custom element that extends a built-in element.
There are two types of custom elements:
Autonomous custom elements are standalone — they don’t inherit from standard HTML elements. You use these on a page by literally writing them out as an HTML element. For example <popup-info>, or document.createElement("popup-info").
Customized built-in elements inherit from basic HTML elements. To create one of these, you have to specify which element they extend (as implied in the examples above), and they are used by writing out the basic element but specifying the name of the custom element in the is attribute (or property). For example <p is="word-count">, or document.createElement("p", { is: "word-count" }).
https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements
It's part of web components spec for Custom Elements. So it's HTML.
Frameworks like Vue.js also supports is atribute in compliance with web components standard.

P attribute inside <li> tag

I have seen this code from the tutorial that I'm studying. I searched for the purpose of the p attribute inside the li tag but found no answer. What is the purpose of that p attribute inside the li tag?
$msgs .= "<li p=\"$no_of_paginations\" class=\"inactive\">Last</li>";
The purpose cannot be inferred from the code snippet. As such, the attribute, being not defined in any HTML specification or draft or browser-specific extension, has no effect beyond being stored as data into the p element node in the document tree.
Such an attribute, though invalid by the specs, can be used like any other attribute in styling (e.g. attribute selector .p) in CSS or in scripting. In this case, it is probable, but by no means certain, that the attribute is meant to be used in scripting to carry a number as its value, with that number inserted with some server-side code, so that this value can be accessed in client-side scripting, as relating to a specific element.
The recommended way is to use data-* attributes instead, such as data-p, to avoid any risk of clashing with attribute names that might be introduced in some future HTML version.
The default HTML(whichever version) namespace doesn't have a purpose for "p" inside a li tag. If there's another namespace declared then that's where it's from. Other than that, it's not valid by w3 standards.
It should be a custom attribute to use in JavaScript codes to get something.
That is just a custom tag used in some javascript functions

Is it against input tag semantics to use them for interactivity?

I have been busy making an interactive tab layout using only CSS and I've had someone tell me that this is not the intended semantic meaning of <input> tags. Now, I know that HTML5 focuses a lot more on semantics than previous versions of HTML did, so I was wondering, is something that does something like the following against the input semantics:
<label for="toggleTab" class="togglelabel">Toggle tab</label>
<input type="checkbox" id="toggleTab" class="toggleinput">
<div class="toggletab">Look at this thing hide and show</div>
CSS:
.toggletab, .togglelabel {border:1px solid #AAA;display:block;}
.toggleinput, .toggletab {display:none;}
.toggleinput:checked + .toggletab {display:block;}
(demo)
The standards[1][2] both say the same thing:
The input element represents a typed data field, usually with a form control to allow the user to edit the data.
So to me this seems like this is indeed against what the input tag should be used for (since this has nothing to do with data, but just with displaying certain things to the user or not).
And then of course my followup question would be, if this is indeed not what input tags should be used for according to the standard, is it bad to go against the semantics standards?
Well structurally this will be quite difficult. Inputs need go inside form elements, and if you are going to be using these all over the page, most of your page will be wrapped as one giant form, potentially will nested forms, for search bars, user input and the like.
As your quote says:
The input element represents a typed data field, usually with a form control to allow the user to edit the data.
The control you are suggesting isn't for editing data its for adding graphical user functionality. If you were to bing the input to a form, either by placing the input inline into a form, or using the #form attribute as your comment suggests, what exactly is the semantic of that form? If would have no action, it would have no site to post to, and if an accessibile browser were to try and render the elements of that form in a different way it would have no semantic content.
For the kind of hide/show toggle functionality, I'd recommend instead using an a link and hanging some javascript off that. As stated:
If the a element has an href attribute, then it represents a hyperlink (a hypertext anchor) labeled by its contents.
In this context Hyperlink does not preclude the use of javascript as the acting force on the page, if it did most pages would be non-compliant to the spec. This is backed up by the first type of link suggested in the definition of hyperlink suggests that the link can be "used to augment the current document".
As a side note, in accessible browsers, inputs like these maye be rendered or presented in ways different to what you expect. Each form might be pulled out into a list of possible data editing options, and this would not fit the semantics of what a user might expect.
Semantics & custom behaviour
If the question is about which element has the least implied semantics, I reckon your best bet is the <button type="button"> element: the HTML5 spec describes it as « a button with no additional semantics» which, without scripting, « does nothing » — unlike the <a> element, which has implicit behaviour as a hypertext link and anchor.
The HTML4 forms spec refers to these as 'push buttons', which « …have no default behavior. Each push button may have client-side scripts associated with the element's event attributes ».
Furthermore, the HTML4 spec cites buttons repeatedly in its description of scripts: they are the only element referenced specifically in the introduction to scripts, although inputs also feature in the examples of DOM-event triggered scripts — however, as buttons are non-self-closing, they can contain other DOM nodes, which may make them more flexible depending on your needs.
Non-<input> solution
Using the push button, custom behaviour can be inferred by using data-* attributes for CSS selectors:
.toggleinput[ data-checked ] + .toggletab {
display:block;
}
…and scripted as follows:
// Use Array's forEach to loop through selection
Array.prototype.forEach.call(
// …of all `.toggleinput` elements
document.querySelectorAll( '.toggleinput' ),
function bind( input ){
input.addEventListener( 'click', function toggleCheckedState(){
// `dataset` is an object representation of data-* attributes
if( this.dataset.checked ){
// Remove the attribute if it exists
delete this.dataset.checked;
}
else {
// Declare it if it doesn't
this.dataset.checked = true;
}
}, false );
}
);
Forked code demo

Is there a generic attribute for all HTML elements aside from ID and class?

Like a tag that I can use to store some necessary info? But really isn’t required or used by the HTML? Works like the tag attribute for objects on Visual Basic?
Up until HTML5 no. With HTML 5 there is provision for this with the data-* attribute.
For example:-
<div id="myStuff" data-mydata="here is my data">
In current technology there is no "official" away to do this. However all browsers allow you to add any arbitary attribute to a HTML element so in HTML4 you can do this:-
<div id="myStuff" data-mydata="here is my data">
Which as you can see is identical but not offically sactioned and if you want strict XHMTL compliance will be considered "broken".
You can access the attribute just as you would any other:-
var mydata = document.getElementById("myStuff").getAttribute("data-mydata");
You could perhaps use the html5 data-* attributes? It'll fail validation on html4, but it is still probably the best option...
If you're storing data to use in javascript, you can also use something like jQuery's Metadata plugin. Basically, you can store data within the element's class="" attribute, like so:
<div id="aaa" class="class1 class2 class3 { type: 'food', color: 'green' }"></div>
Then in javascript:
alert($('#aaa').metadata().color) // "green"
Other kits use the title or rel attributes to store data. While this is more validation friendly, it may or may not be better than using AnthonyWJones' answer of just using non-standard attributes. It'll "break" validation, but then again according to Dojo, custom attributes are perfectly valid HTML, even if they don't validate against a DTD.
So no - there isn't a single well accepted specific attribute where you can dump all data. All existing attributes are for specific uses. But you can either 1) create your own attributes, or 2) coopt an existing tag to reuse for your purposes. Just wanted to point out the alternative.
Have a look at www.htmlref.com or W3C for the used attributes.
Other than those you can just add your own, they will render and they will be accessible via code for instance in C# you can access a controls attribute collection.
Control.Attributes["MyCustomAttribute"] = "Hello World";
there’s rel and rev attributes, which work in elements with an href-attribute. they have a semantic meaning, but are often abused as an attribute to store additional information