PDA

View Full Version : Adding an attribute...


qrayg
05-24-2005, 10:10 PM
I'm not a JS expert in the least but I've narrowed my problem down to this hunk of code:

var a, sTitle;
var anchors = document.getElementsByTagName ("a");

for (var i = 0; i < anchors.length; i ++) {
a = anchors[i];
sTitle = a.getAttribute("title");
if(sTitle) {
a.setAttribute("tiptitle", sTitle);
a.removeAttribute("title");
a.removeAttribute("alt");
a.onmouseover = function () {tooltip.show (this.tiptitle)};
a.onmouseout = function () {tooltip.hide ()};
}
}

What I'm trying to do is create a new attribute called "tiptitle" on any <a> tag that contains a "title" attribute. I then want to set the value of the tiptitle attribute to the value of the title attibute. Finally I want to remove the title attribute.

This works fine in IE but it returns "undefined" in Mozilla.

Does anyone know what I'm doing wrong?

hemebond
05-24-2005, 11:01 PM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>59719</title>
</head>
<body>
<p>
<a href="" title="this is a link">
text link
</a>
</p>

<script type="text/javascript">
var a, sTitle;
var anchors = document.getElementsByTagName ("a");

for (var i = 0; i < anchors.length; i ++)
{
a = anchors[i];
sTitle = a.getAttribute("title");
if(sTitle)
{
a.setAttribute("tiptitle", sTitle);
a.removeAttribute("title");
a.removeAttribute("alt");
a.onmouseover = function() {tooltip.show(this.getAttribute('tiptitle'))};
a.onmouseout = function() {tooltip.hide()};
}
}
</script>
</body>
</html>

Harry Armadillo
05-24-2005, 11:01 PM
a.onmouseover=function () {tooltip.show (this.getAttribute('tiptitle'))};

IE doesn't really distinguish between HTML-attributes and javascript variables, whereas Gecko-browsers do. If you set an attribute (with setAttribute() ), you should fetch it with getAttribute(), not the dot-notation of javascript variables.

Meanwhile, if you attach a javascript variable to an element-object ( element.variablename ), use dot-notation or square-bracket-notation ( element['variablename'] ) to retrieve it.

qrayg
05-24-2005, 11:11 PM
@hemebond

Thank you!!! It worked.

Here's the resulting page (http://lom.qrayg.com/walkthrough/map/) (mouseover the numbers in the table).

I made a dynamic tooltip script that takes an <a> tag's title attribute and displays it in a div that follows the mouse. The div and custom attribute are written on the fly and do not affect the site's html at all. The reason why I wanted to remove the title attribute is because most browsers display the title attribute as it's own tooltip and it overlaps the dynamic one.

The script is a combination of 2 different tooltip scripts as well as my own code.