Need: Find a way to add a valid tag/attribute/property to a normal html control.
What I have is some javascript/jquery adding a click event to a link that will show
You can't get away with adding custom attributes to HTML elements whilst still being valid. It will generally work in current browsers, but it's a bit fragile in that if you happen to pick a name that is in use (now or in the future) as an HTML or JavaScript property by any browser, the clash will stop it from working.
HTML5 proposes attributes whose names start with “data-” as valid extension mechanisms. You could also consider namespaced elements in XHTML; this still isn't technically “valid XHTML” by the DTD but at least it is safe from collisions.
<a href="..." class="showItLink" textToShow="This is the text to show">HI
I suggest using the ‘title’ attribute for this particular purpose.
If your textToShow attribute was an expando property, then this.textToShow would not return undefined, but since it is a custom attribute, you need to use jQuery's this.attr("textToShow") or the standard DOM this.getAttribute("textToShow").
The best way to do this kind of thing is to hide the text in another element and then toggle that element. Try something like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>clear test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#show-it").click(function() {
$("#message").toggle();
});
});
</script>
</head>
<body>
<div>
<a id="show-it" href="javascript:void(0);">show it</a>
<div id="message" style="display:none;"> hidden message</div>
hello world
</div>
</body>
</html>
The way you add an attribute to an html control is by using the element.setAttribute("attributeName", "attributeValue") where "element" is the element you want to add the attribute to.
To get an attribute you use getAttribute("attributeName");
If you're using JQuery, just get and set the attributes with .attr().
Get: this.attr("textToShow")
Set: this.attr("textToShow", value)