JavaScript Question

Discuss any other topics here
Post Reply
Matte
Posts: 321
Joined: Fri Oct 19, 2007 7:49 pm

JavaScript Question

Post 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>
User avatar
QuestOfDreams
Site Admin
Posts: 1525
Joined: Sun Jul 03, 2005 11:12 pm
Location: Austria
Contact:

Re: JavaScript Question

Post by QuestOfDreams »

try this instead

Code: Select all

function changecolor() 
{
	
	if(document.bgColor == '#ffffff')
	{
		document.bgColor='black';
	}
	else
	{
		document.bgColor='white';
	}
}
Matte
Posts: 321
Joined: Fri Oct 19, 2007 7:49 pm

Re: JavaScript Question

Post by Matte »

It worked!
Thanks!
What exactly is diffirent about #ffffff?
User avatar
QuestOfDreams
Site Admin
Posts: 1525
Joined: Sun Jul 03, 2005 11:12 pm
Location: Austria
Contact:

Re: JavaScript Question

Post 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:
Matte
Posts: 321
Joined: Fri Oct 19, 2007 7:49 pm

Re: JavaScript Question

Post 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.
Post Reply