...

View Full Version : Problems with simple object fade code



eddo
07-28-2011, 07:14 PM
Hi all. I'm learning JS from pretty much scratch and the first thing I'm trying to do is simply make an image fade function. I just can't seem to make it work though, the image starts off at the right opacity (im this case 0.5) but after that the page goes white and the script never stops. It does seem to be counting up normally "opacity: 0.6 opacity: 0.7" etc. though.



<img src="1.jpg" id="pic1">

<script type="text/javascript">
var amount = 0.5;
var target = document.getElementById('pic1');

function fade() {

if (target.style.opacity < 1.0) {

target.style.opacity = amount;
amount = amount + 0.1;

document.write("<br>opacity: " + target.style.opacity);

setTimeout("fade()", 1000)
//fade();
}

}

fade();

</script>


edit I rewrote it to make it simpler but still having basically the same problem D:!

eddo
07-29-2011, 08:17 AM
Any ideas on this one? I rewrote it to make it simpler but still getting the same basic problem :/

vwphillips
07-29-2011, 08:38 AM
<!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>
<title></title>
</head>

<body>
<img src="http://www.vicsjavascripts.org.uk/StdImages/Egypt5.jpg" id="pic1">

<script type="text/javascript">
var amount = 0.5;
var target = document.getElementById('pic1');

function fade() {

if (target.style.opacity < 1.0) {

target.style.opacity = amount;
amount = amount + 0.1;

target.style.opacity=amount;

setTimeout("fade()", 1000)
//fade();
}

}

fade();

</script>
</body>

</html>

eddo
07-29-2011, 10:47 AM
Dang, I'd tried that before and it didn't work so I was trying to make the reverse work instead. No idea what I did wrong the first time! Many thanks.

devnull69
07-29-2011, 10:57 AM
What went wrong? It's the document.write() .... this will always create a new document if applied after page load. So document.write() is really ONLY useful to show content during the initial load of the page.

eddo
07-29-2011, 12:20 PM
What went wrong? It's the document.write() .... this will always create a new document if applied after page load. So document.write() is really ONLY useful to show content during the initial load of the page.

Ahhhhhhhhhhhhh so that's what it was! So what can I use if I want to print a var's current value for debugging purposes?

devnull69
07-29-2011, 01:18 PM
It depends on which browser you are using. You can use

1. console.log() in some cases, if you have the possibility to access the javascript console or you have extensions like Firebug for Firefox or the Development Tools for IE
2. alert() ... which shows you a dialogue window
3.


HTML
<div id="messagearea"></div>

Javascript:
document.getElementById('messagearea').innerHTML = "This is a message";



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum