Page 1 of 1

JavaScript Question

Posted: Thu Nov 06, 2008 5:09 pm
by Matte
I started learning JavaScript by myself, basing my scripts on my knowledge of HTML and basic knowledge of Python and Java.
However, when you click the button, it changes the background to black. When you click it again, it is supposed to go back to white. However, it goes white 1 sec, and then back to black.
EDIT: After reading my code carefully, I managed to think that it is quite logical. It changes the color to white, but the script says that it has to change it back to black if it's white. How do I stop the website after it executed the else command?
Thanks!

Here's the script:

Code: Select all

<html>
<head>
<title>H1ome</title>
<SCRIPT language="JavaScript">

<!--

function changecolor() 
{
	if(document.bgColor='white')
             {
	document.bgColor='black';
	}
	else
	{
	document.bgColor='white';
	}
}

//-->

</SCRIPT>
</head>
<body>
Clicking this button will change the background color to black. 
Clicking it again will change it back.
<FORM>
<INPUT type="button" value="click" name="button01"  onClick="changecolor()">
</FORM>
</body>
</html>

Re: JavaScript Question

Posted: Thu Nov 06, 2008 9:19 pm
by QuestOfDreams
try this instead

Code: Select all

function changecolor() 
{
	
	if(document.bgColor == '#ffffff')
	{
		document.bgColor='black';
	}
	else
	{
		document.bgColor='white';
	}
}

Re: JavaScript Question

Posted: Thu Nov 06, 2008 9:22 pm
by Matte
It worked!
Thanks!
What exactly is diffirent about #ffffff?

Re: JavaScript Question

Posted: Thu Nov 06, 2008 10:04 pm
by QuestOfDreams
Well, firstly, you had = in your if-statement which is an assignment, but you need a == for comparison. Secondly white, black, blue, etc are just shortcuts for the hex color codes. If you do an alert of document.bgColor you'll see the browser is converting 'black' into '#000000', white into '#ffffff' etc.

PS: Note that document.bgColor is deprecated :wink:

Re: JavaScript Question

Posted: Fri Nov 07, 2008 4:56 pm
by Matte
Ok. So to change something, I need to use =, and to check if something is true ==.

I will see if I can write a script that RF users can use lol.