PDA

View Full Version : dynamic text changing in Firefox



Jacquih
06-23-2006, 06:43 PM
I'm relatively new to JS and definitely new to Firefox.

This script works in IE but not FF (http://habibihon.com/shahrzad/barebones.html):



<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript" language="javascript">
function showPic (whichpic) {
if (document.getElementById) {
document.payment.amount.value = whichpic.price;
document.payment.item_name.value = whichpic.description;
document.getElementById('placeholder').src = whichpic.src;
document.getElementById('amount').childNodes[0].nodeValue = whichpic.price;
document.getElementById('desc').childNodes[0].nodeValue = whichpic.description;
document.getElementById('stuff').childNodes[0].nodeValue = whichpic.other;
document.payment.amount.value = whichpic.price;
document.payment.item_name.value = whichpic.description;
return false;
} else {
return true;
}
}
</script>

<body onload="document.payment.item_name.value=0; document.payment.amount.value=0;")>

<img name="whichpic" src="210.jpg" onclick="showPic(this)" price="100" other="sale" description="silver bedlah" height="100" />

<img name="whichpic" src="211.jpg" onclick="showPic(this)" description="purple bedlah" price="101" other="available" height="100" />

<img name="whichpic" src="212.jpg" onclick="showPic(this)" other="sale" description="gold bedlah" price="102" height="100" />

<br/><br />

<img id="placeholder" src="blank.jpg" height="250" alt="" />

<br/><br />

<p>item: <span id="desc">&nbsp;</span></p>
<p>price: <span id="amount">&nbsp;</span></p>
<p>status: <span id="stuff">&nbsp;</span></p>

<br/><br />

<form method="POST" name="payment">
item: <input type="text" name="item_name" value="" />
price: <input type="text" name="amount" value="" />
</form>

</body>
</html>


It would be great to get some advice on how to make this more compatible with FF. I was thinking perhaps of having the images and their details each be part of individual forms, and using getElementByName.

Thank you in advance for any help!

Twey
06-23-2006, 06:59 PM
It should be
document.forms['payment'].elements['amount'].valuenot
document.payment.amount.value

You should use FX and other standards-compliant browsers to test your site during design, then compensate for IE's bugs later. IE renders things often totally different to other browsers.

otaku
06-23-2006, 08:28 PM
Hello Jacquih,

You should always use element.getAttribute(attributeName) instead of element.attributeName to get the value as some browsers may not register user defined attributes as a properties of the element.



<script type="text/javascript">
function showPic(whichpic){
if (document.getElementById){
document.getElementById('placeholder').src = whichpic.getAttribute("src");
document.getElementById('amount').firstChild.nodeValue = whichpic.getAttribute("price");
document.getElementById('desc').firstChild.nodeValue = whichpic.getAttribute("description");
document.getElementById('stuff').firstChild.nodeValue = whichpic.getAttribute("other");
document.payment.amount.value = whichpic.getAttribute("price");
document.payment.item_name.value = whichpic.getAttribute("description");
}
}
</script>

Jacquih
06-24-2006, 05:12 AM
Thank you both very much! I will definitely be using FF first from now on :D

Good links, Twey, and Otaku, www.getElementById.com is a great site!

Twey
06-24-2006, 06:03 AM
Lol, the 404 is so awesome. :p
I really need to upload all that stuff again.

otaku
06-24-2006, 01:26 PM
Thank you both very much! I will definitely be using FF first from now on :D

Good links, Twey, and Otaku, www.getElementById.com is a great site!

Hi Jacquih,

You're welcome and thank you for you kinds words on getElementById.com.

I just want to let you know that I don't agree with Twey anti-microsoft philosophy. Yes IE has bugs but FX as bugs too. You should visit bugzilla at http://bugzilla.mozilla.org to see how much moz has bugs.

There is no IE bug in this particular thread. Twey hate microsoft and I see bugs even when there is no bugs. His goal is to convince people to dump IE and microsoft products. Most of these posts on this forum are oriented that way.

Using FX to test your site during design, then compensate for IE's bugs later it's a very bad idea. You should test with as much browser as you can at the very beginning of your project, exactly as you made by opening this thread.

Remember that more than 85% use IE. If you dump IE you will dump all these people and shoot yourself in the foot.

I just wanted to you let know Jacquih that in any circonstance I want to be associate with that kind of negative marketing philosophy. I do not come here to promote a browser over another one. I came here to help people.

Best regards,

Twey
06-24-2006, 07:02 PM
And you, my dear chap, have totally missed my point.
There is no IE bug in this particular thread.You're quite right. I was giving general advice, not anything specific to this thread. Had I been doing so, I would have pointed out the exact bug that was causing this problem, which, as you can see quite clearly, I have not done.
Twey hate microsoft and I see bugs even when there is no bugs.I presume you meant that I see bugs where there are none. If so, you are entirely wrong. I do indeed have an anti-Microsoft philosophy: I disagree with their personnel, their business ethics, and the software they produce as a result, and most certainly I would -- and do -- advise people against using their products wherever possible. What I do not do is fabricate failures. The products I recommend against generally have enough real problems to make that quite unnecessary. If they do not, and I am advising against them on a purely ethical stance, I point this out clearly.
Remember that more than 85% use IE. If you dump IE you will dump all these people and shoot yourself in the foot.I am well aware that the majority of desktop owners use IE, although to give a precise figure is misleading, since web statistics are notoriously unreliable. As such, I am most certainly not recommending that anyone "drop" IE (if by that you mean as a consideration when designing sites; as a general-purpose browser, I would indeed recommend this). The point I am attempting to make is that designing a site around IE, its problems and its non-standard features and then attempting to make it work in everything else is a much more difficult task than creating a standards-compliant site that works in everything else and then inserting a little code to patch over IE's bugs.
Yes IE has bugs but FX as bugs too. You should visit bugzilla at http://bugzilla.mozilla.org to see how much moz has bugs.Of course it has bugs. All software has bugs. It has substantially less than Internet Explorer, however. Looking at Mozilla's bug tracker as a comparison between the numbers of bugs in Internet Explorer and Firefox is a ridiculous idea, mostly because a lot of the bugs in Internet Explorer are never disclosed by Microsoft, or are classified as "features" despite causing non-adherence to the standards. Another, more relevant point that you have inadvertantly made is that those bugs are on the bug tracker. This means they're due to be fixed, something Microsoft does not always bother to do (within the year in which the bug was reported, anyway).

Tonester
08-30-2006, 04:17 AM
Can you explain this? I am trying to work out how to dynamically change both text and style, and both IE and FF work in mutually exclusive ways with what I am trying to achieve.

<h1 id="HeadingOne">Original Heading</h1>
<script type="text/javascript">
// Works in Firefox but Not IE
document.getElementById('HeadingOne').setAttribute('style','font-size: 11pt; color: red; background-color: yellow;');

// Works in IE but Not Firefox
var theParagraph = document.getElementById('HeadingOne');
theParagraph.setAttribute('style','font-size: 11pt; color: red; background-color: yellow;');
var oNodes = theParagraph.childNodes;
for (i = 0; i < oNodes.length; i++) {
var oNode = oNodes(i);
oNode.nodeValue = 'Changed Heading'
}
</script>

Twey
08-30-2006, 05:51 AM
var h1 = document.getElementById("HeadingOne");
h1.style.fontSize = "11pt";
h1.style.color = "red";
h1.style.backgroundColor = "yellow";

var fd = false;

while(h1.hasChildNodes())
if(h1.firstChild.nodeType === 3 && !fd)
h1.firstChild.nodeValue = fd = "Changed Heading";
else
h1.removeChild(h1.firstChild);

Tonester
08-30-2006, 06:40 AM
Thanks Twey, but I still have a problem. Your code to change the text doesn't seem to work. Initially it used to get stuck in some sort of endless loop when run under IE6, but now the text is just blank.

while(h1.hasChildNodes())
if(h1.firstChild.nodeType === 3 && !fd)
h1.firstChild.nodeValue = fd = "Changed Heading";
else
h1.removeChild(h1.firstChild);
The style code is perfect - thanks.

Adding some of your logic to my original code does not help either (with FF).

var i = 0;
var oNodes = h1.childNodes;
while (i < oNodes.length && !fd) {
var oNode = oNodes(i);
if(oNode.nodeType === 3) {
oNode.nodeValue = 'Changed Heading';
fd = true;
}
i++;
}

Twey
08-30-2006, 07:02 AM
Argh, you're right.


while(h1.childNodes[1])
if(h1.firstChild.nodeType === 3 && !fd)
h1.firstChild.nodeValue = fd = "Changed Heading";
else
h1.removeChild(h1.firstChild);

Tonester
08-30-2006, 07:23 AM
You sound reasonable Twey ... but I think it's time to up my medication. Your code still does not work. Consider this code:

document.write ('With h1.childNodes[1]<BR>');
while(h1.childNodes[1])
{
document.write ('&nbsp;&nbsp;Node Value = ' + h1.firstChild.nodeValue + ', Node Type = ' + h1.firstChild.nodeType + '<BR>');
if(h1.firstChild.nodeType === 3 && !fd)
h1.firstChild.nodeValue = fd = "Changed Heading";
else
h1.removeChild(h1.firstChild);
}

document.write ('<BR>With h1.hasChildNodes()<BR>');
while(h1.hasChildNodes())
{
document.write ('&nbsp;&nbsp;Node Value = ' + h1.firstChild.nodeValue + ', Node Type = ' + h1.firstChild.nodeType + '<BR>');
if(h1.firstChild.nodeType === 3 && !fd)
h1.firstChild.nodeValue = fd = "Changed Heading";
else
h1.removeChild(h1.firstChild);
}
It produces this output:

With h1.childNodes[1]

With h1.hasChildNodes()
Node Value = Original Heading, Node Type = 3
Node Value = Changed Heading, Node Type = 3
As you can see, your new method is not cycling through any nodes. However, the h1.firstChild.nodeValue line is obviously working but not in the manner I would have expected. Any ideas?

Twey
08-30-2006, 01:12 PM
Damn it, let's take the easy route:
while(h1.hasChildNodes()) h1.removeChild(h1.firstChild);
h1.appendChild(document.createTextNode("Changed Heading"));

mwinter
08-30-2006, 01:16 PM
var theParagraph = document.getElementById('HeadingOne');

I hope that you actually use feature detection and don't use identifiers like "HeadingOne". Also, wouldn't "theHeading" be a more accurate variable name?



var theHeading;

if (document.getElementById
&& (theHeading = document.getElementById('HeadingOne'))
&& theHeading.style && theHeading.childNodes) {
/* ... */
}
theHeading = null;




theParagraph.setAttribute('style','font-size: 11pt; color: red; background-color: yellow;');

The pt unit is absolute (it uses physical dimensions) and intended for printing. Use percentages.



for (i = 0; i < oNodes.length; i++) {

You don't seem to have declared that index variable.



var oNode = oNodes(i);

Your problem here is that oNodes is not a function: it is a collection. Though MSIE lets you get away with using parentheses, you must use square brackets (or the item method, but brackets are preferable).



var theHeading, style, nodes;

if (document.getElementById
&& (theHeading = document.getElementById('HeadingOne'))
&& (style = theHeading.style) && (nodes = theHeading.childNodes)) {
style.fontSize = '140%';
style.color = 'red';
style.backgroundColor = 'yellow';

for (var i = 0; i < nodes.length; ++i) {
nodes[i].nodeValue = 'Changed heading';
}
}
theHeading = style
= nodes
= null;

Mike

Twey
08-30-2006, 01:22 PM
nodes[i].nodeValue = 'Changed heading';What effect will this have on non-text nodes? How about unexpected text nodes (white space &c.)?

mburt
08-30-2006, 01:26 PM
I know this is all in good fun but:


Also, wouldn't "theHeading" be a more accurate variable name?

There's no right for variable names. Everyone knows you can call them whatever you want :)

mwinter
08-30-2006, 01:44 PM
What effect will this have on non-text nodes?

It depends on the node.



How about unexpected text nodes (white space &c.)?

It will change the values of them, of course.

There's no point in looking at this particular operation in a generic fashion. Your suggestion would remove any element children, for example. In the demonstrated case, there will be only one child node, and it will be a text node, so any loops will be unnecessary. As Tonester hasn't shown a real example (where iteration might be appropriate, for some reason), I suggested changes as far as was practical.




There's no right for variable names.

Of course there is! Variable names should be descriptive and should indicate what the variable references. Mislabeling or using obscure names makes maintenance more difficult.

Mike

Tonester
08-30-2006, 10:43 PM
Actually I like Twey's solution best - simple and elegant. And also if there are mulitple text nodes for that particular ElementId then all those nodes are destroyed (which is often the case for long paragraphs). Excellent!

With Twey's code I have now created this function:


// ----------------------------------------------------------------------------
function ChangeTextById(id, newText, fontSize, textColor)
// A function to change the text of region of text based on the ID of that region.
{
if (id != '')
{
var theParagraph = document.getElementById(id);
if (fontSize != '') theParagraph.style.fontSize = fontSize;
if (textColor != '') theParagraph.style.color = textColor;

if (newText != '')
{
while(theParagraph.hasChildNodes())
theParagraph.removeChild(theParagraph.firstChild);
theParagraph.appendChild(document.createTextNode(newText));
}
}
}
// ----------------------------------------------------------------------------

I can only assume that this naming convention will satisfy mwinter's desire for descriptive variable names. I hope the indentation and commenting is sufficient as well. Actually I like you Mike. You remind me of when I was young and stupid. Do you really think that code on a forum has to pass a code review? We're just thrashing around ideas, mate.

Now that I have my "best practices" function finished I can call it elsewhere using the following:


<h1 id="TheHeading">Original Heading</h1>
<p id="Message">MESSAGE</p>
<hr />
<script type="text/javascript">
ChangeTextById('TheHeading', 'Twey is a Legend', "16pt", "red");
ChangeTextById('Message', 'Hi Mike - thanks for your input', "11pt", "blue");
</script>

Nice and simple. Thanks for your help Twey, and you Mike

mwinter
08-30-2006, 11:34 PM
Do you really think that code on a forum has to pass a code review?

Considering the amount of rubbish that can be found on the Web, yes, I do. Small snippets that illustrate specific points are one thing; code that others might actually use is quite another.

Mike