Let’s say I’m generating markup through server-side code. I’m generating a bunch of HTML tags but I want to add custom client-side behavior.
With JavaScript (if I had a reference to the DOM node) I could have written:
var myDOMNode = ...
myDOMNode.myCustomAttribute = "Hi!";
Now the issue here is that I don’t want to qualify every element with an unique id just to initialize data. And it’s really strange to me, that there’s not an easier and unobtrusive way to attach client-side behavior.
If I’m remembing this correctly, this is valid IE stuff.
<div onload="this.myCustomAttribute='Hi!'"></div>
If I was able to do this, I should be able to access it’s “data context” though the identifier ‘myCustomAttribute’, which is really what I want.
I do appricate the input but I’ve finally figured this out and it’s the way I go about initialization that has been the thorn in my side.
What you never wan’t do is to pollute your global namespace with a bunch of short lived identifiers. Any time you put
id=""on an element you’re doing exactly that (same thing for any top level function). By relying on jQuery, HTML5 data and CSS there’s a solution to my problem which I think is quite elegant.What I do is that I reserve a CSS class for a specific behavior and then use HTML5 data to parameterize the behavior. When the document is ready, I query the document (using Query) for the CSS class that represents the behavior and initialize the client-side behavior.
I’ve been doing a lot of ASP.NET and within this context both the
id=""andname=""belongs to ASP.NET and is pretty useless for anything else than internal ASP.NET stuff. What you typically find yourself doing is to get at a server-side property calledClientIDyou can refer to this from client-side JavaScript, it’s a lot of hassle. They made it easier in 4.0 but fundamentally I think it’s pretty much broken.Using this hybrid of CSS, HTML5 data and jQuery solves this problem altogether. Here’s an example of an attached behavior that uses regular expressions to validate the input of a textbox.
And here’s the script:
Totally clean, no funky
id=""or obtrusive dependency.