I've got some java script code that implements a kind of slide show. It uses a series of img tags as a table to control its actions. I probably used some code I found some where as a basis. Anyway, the img tags contain a data-img attribute which I can't find in any definition of the img tag. Now I find I need to add more data to the img tags. So my questions are:
1) Is the data-img actually a real attribute or something adhoc?
2) Can I invent yet more attributes?
3) What is the danger of using such attributes?
1) It's valid in HTML 5; it is an invalid attribute (that will, as far as I know, still work in all browsers, it but will break validation) in HTML 4
2) As far as I am aware, you can add arbitrary attributes and query them in Javascript, but chances are those attributes will not survive certain DOM manipulation and other operations where the browser creates markup - it's possible the invalid attributes will simply be dropped
3) Your pages will no longer validate.
Background: Custom attributes - Yay or nay?
Depends on implementation.
YES, its often quite useful to do so.
If created in #2, not really, no, they are part of the DOM at that point, i know of no browser that removes attributes.
They are a valid HTML5 attributes.
If you need to add and get that data only with javascript for client side without communicating with the server side you can implement a store and retrieve mechanism similar to the one used by Mootools.
It doesn't pollute the DOM and store also javascript objects.
Related
AddThis uses a notation which seems to extend the parameters available in an HTML div tag.
The tag that contains the button array can include additional parameters such as:
<div addthis:url="someUrl"> </div>
Along with defining some css classes for the element seems to give their JavaScript code access to manipulate this element AND read the value of the additional addthis: parameter.
I'd like to implement something similar myself but am confused as to how to correctly allow additional parameters in the standard HTML tags.
I've also seen the AddThis code throw W3C validation errors sometimes so wonder if this is entirely legitimate.
Searching around I've found some discussions about extending the HTML tags via extending the prototypes in JavaScript but everything I've read seems to be about adding new events etc.
This addthis:url notation looks more 'schema'-like to me, or am I on completely the wrong track?
I've made some progress on this, at least functionally, but what I have now breaks the HTML validation quite seriously.
To explain a little further what I am trying to achieve...
In the same way that AddThis allows you to include their sharing elements by adding a simple <DIV> tag to your page and including some JavaScript, I want to provide similar functionality with <IMG> tags.
Someone wanting to use this functionality will include an <IMG> tag that has some additional name=value pairs that are outside of the standard image tags attribute and are defined by my spec.
The JavaScript that is included will then read these additional attributes and perform some actions on the image tags.
To this end I have the following:
<IMG id="first image" class="imageThatCanBeWorkedOn" src="holding.png"
my-API-name:attribute1="some data"
my-API-name:attribute2="some other data">
I then use `getAttribute('my-API-name:attribute1') to access the additional tag data from JavaScript.
(I'm selecting all of the tags with a particular class name into an array and then processing each tag in turn, in case anyone is interested.)
This all works great - I can manipulate the <IMG> tags as needed based on the additional data, BUT the markup is not valid HTML according to the W3C validator.
With the above I get:
Warning Attribute my-API-name:attribute1 is not serializable as XML 1.0.
Warning Attribute my-API-name:attribute2 is not serializable as XML 1.0.
Error: Attribute my-API-name:attribute1 not allowed on element img at this point.
Error: Attribute my-API-name:attribute2 not allowed on element img at this point.
If I remove the : from the attribute name (eg my-API-name-attribute2) the 'not serializable' warnings disappear but I still get the 'not allowed' errors.
So how would I add these additional bits of data to an <IMG> tag and not invalidate the markup but while maintaining a level of clarity/branding by including the 'my-API-name' part in the way that AddThis does?
(I note from the comments that I could use data- attributes. I haven't tried these yet, but I'd prefer to be able to do this in the 'branded' way that AddThis seems to have managed without breaking their users' markup.)
If we were talking about XML (which includes XHTML) it'd be a namespace prefix. In HTML5 it's just a regular attribute:
Attribute names must consist of one or more characters other than the
space characters, U+0000 NULL, U+0022 QUOTATION MARK ("), U+0027
APOSTROPHE ('), U+003E GREATER-THAN SIGN (>), U+002F SOLIDUS (/), and
U+003D EQUALS SIGN (=) characters, the control characters, and any
characters that are not defined by Unicode.
... though slightly harder to manipulate (not too much, though) and totally non-standard.
I'd like to implement something similar myself but am confused as to
how to correctly allow additional parameters in the standard HTML
tags.
Before HTML5, some web developers deployed a technique of adding custom data to an element's class attribute (or to any other attribute which will happily attach itself to any element).
This worked, but it was self-evidently a hack.
For this reason HTML5 introduced custom data-* attributes as the standard approach to extending an element's attributes - and data-* is precisely what you should be deploying.
So how would I add these additional bits of data to an tag and
not invalidate the markup but while maintaining a level of
clarity/branding by including the 'my-API-name' part in the way that
AddThis does?
<img id="first image" class="imageThatCanBeWorkedOn" src="holding.png"
data-myAPIName_attribute1="some data"
data-myAPIName_attribute2="some other data" />
Further Reading:
Time Travel back to 2010: http://html5doctor.com/html5-custom-data-attributes/
Time Travel back to 2008: http://ejohn.org/blog/html-5-data-attributes/
I'm looking to inject HTML via JavaScript into a page at work.
What I'd like to know is if injecting a re-write of the page is more or less efficient than injecting snippets throughout the page with methods like getElementById().
For example:
document.getElementById("Example").innerHTML = '<h2 id="Example" name="Example">Text</H2>'
document.getElementsByClassName("Example").innerHTML = '<H1>Test</H1>'
...etc. Is this more efficient/effective than simply injecting my own version of the entire page's HTML start to finish?
Edit: Per Lix's comment, I should clarify that I likely will be injecting a large amount of content into the page, but it will affect no more than a dozen elements at any time.
If your project can manage it, it could be better to create DOM Elements and append them to the tree.
The big problem with efficiency would be that setting .innerHTML property would first remove all the nodes and only then parse the html and append it to the DOM.
It's obvious that you should avoid removing and the re-appending identical elements, so if you're sure the "Example" elements would always remain on the page, your way of setting them seems to be a nice optimazation.
If you want to optimize it even further, you could parse the html you want to append to nodes and have a function that checks which ones should be appended and which one shouldn't. But be aware that accessing the DOM is costly. Read more about the ECMA-DOM bridge.
Edit: In some cases it might be better to let the browser do the html parsing and injecting through innerHTML. It depends on the amount of HTML you're inserting and the amount you're deleting. See #Nelson Menezes's comments about innerHTML vs. append.
Depends on the context. If it was only decoration of existing content, then your proposal would suffice. I'd use jQuery anyway, but that's only my preference.
But when injecting the actual content you have two concerns:
maintainability - Make the structure of your code readable and subject to easy change when you need (and you will need).
accessibility - When javascript is disabled, then no content will be visible at all. You should provide a link to desired content in <noscript/> tag or ensure accessibility to everyone any other way you prefer. That's a minority of internet users at the moment, but for professional webmasters they make it count.
To address both of above concerns I prefer to use ajax to load a whole page, some part or even plaintext into existing element. It makes it readable, 'cause the content is sitting in another file completely separated from the script. And since it's a file, you may redirect to it directly when javascript is disabled. It makes the content accessible to anyone.
For plain javascript you'd have to use XMLHttpRequest object, like here.
With jQuery it's even simpler. Depending on what you need you may use .load, .get or .ajax.
Best practice today is using JQuery Manipulation functions.
Most time you'd use one of this 3 functions :
Replace existing HTML node:
$("div").html("New content");
Append a sibling node:
$("div").append("New content");
Remove a node:
$("div").remove();
I want to implement a timer in DOM but I don't want to use any Javascript. Is this actually possible?
I already have the code in Javascript but I would like to change it to DOM so that I don't have to activate JS.
Thanks for any help :D
The only way to reliably modify the Document Object Model is with JavaScript. DOM is just a structure for accessing parts of a webpage, nothing more.
So unless you have a vendetta against JavaScript and would rather using something like client side VBscript (IE only) you have to use JavaScript.
If you just want to get a similar effect you could try playing with CSS pseudo-elements which I doubt will cover your needs. Also CSS pseudo-elements aren't really part of the page so there are quirks; pseudo-element text cannot be selected for example.
In short, you must use JavaScript to "use" DOM, its a structure, not a language.
I have a web page that used client side templating to update part of the page based on json obtained via an ajax call.
At the moment I'm using an unordered list where inside each Li I have markup to display information about a product.
I'm interested to know, are some tags faster when inserting into the DOM than others? That is to say should I look to either change my ul into some other tag or maybe change the tags inside the Li s?
thanks
b
The fastest way is to construct HTML as text and set the innerHTML property once.
Another approach is to create a document fragment and once done put it into the DOM.
There might be a difference in the speed of insertion of one tag or another, but it will be marginal and different between browsers.
The thing is that touching the DOM is a very expensive operation - if speed is what you are after - minimize that.
Have a look at Stoyan Stefanov's performance tips.
First off, that is completely dependent on the browser.
That being said, the difference between the rendering time of different tags should be negligible. Use the tag which provides the best semantic meaning. Don't worry about render times of different tags.
This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
Custom attributes - Yay or nay?
Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?
In current learning project I am working on, I need to add an attribute whose value will be a number. At first I thought of using "id" for this purpose but an answer revealed that it is not good to do that.
Is it OK if I create my own attribute, say "messid" and assign a numeric value such as "12", "6" etc to it?
Here is why I want to do this so that you can correct me if I am doing it totally wrong:
I need to access this number in my JavaScript (using jQuery). Just taking the value of attribute is easy but extracting the numeric value from a string like "m12" or "m6" is a pain. (I am a beginner in JavaScript world.)
There has been much discussion about this:
Custom attributes - Yay or nay?
How to store arbitrary data for some HTML tags
Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?
At the end of the day, I am on the camp that believes data attributes are the best way to go. They are being introducted in HTML5 to avoid name conflicts. Essentially, if you want to store anything data related you just prepend "data-" on the attribute name:
<div class="user" data-userid="5"></div>
The only con to the whole thing is then that your XHTML won't validate, but I honestly don't care about that stuff. (That's right, I said it)
In HTML 5 you're allowed to add any attribute starting with data-, so e.g. <div data-messid="12"> is OK.
HTML 4 and XHTML 1 won't validate if you add your own attribute, but besides that nothing bad will happen if you choose attribute name unique enough (so it won't conflict with any current or future HTML attribute).
Just so you know, you can easily extract an ID from a string like m12 or m6, I would do it like this:
//name the IDs m_12, m_3 etc
var number = $('#someElement').attr('id').split('_')[1];
Or if say, you have a bunch of links with numbers in the ID as above, and all the links have the clickMe class:
$('a.clickMe').click(function() {
alert($(this).attr('id').split('_')[1]);
});
I use custom attributes, and since they are supported by all browsers I checked I think it is not bad to use them. You can also use custom HTML tags to simulate HTML5, with some IE hack, so why not use attributes, if they don't need any hacks?
Anyway, you can read similar discussion here:
Custom attributes - Yea or nay?
This isn't a definitive answer, but having had to do this in the past I can say this not only works well, it is cross-browser friendly.
If using jQuery you can use .data to store custom information against an element.
The downside of custom attributes are:
IE6 creates extra objects to store custom 'expando' attributes these have a tendency to leak especially if they are created via script.
validation issues
No - it's not.