Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

keep track of previous change 1

Status
Not open for further replies.

machine08

Technical User
Dec 16, 2007
22
0
0
US
Hi all,

This is my second day at JS. Need some basic help. I have an html table with all cell having a blue background. When you click on a cell it changes to yellow. I'm successful at this basic example.

What I would like next, is the second cell I click on have it turn yellow (which it does) but have the previous cell turn back to blue. I imagine this can be accomplished with Global variables but I'm having trouble getting it to work.

Here's what I have:
Code:
function setStyle(x)
{
document.getElementById(x).style.background="yellow";
//alert(x);
}

When I call this function I do:
Code:
onclick="setStyle(this.id)"

Can someone help me figure out how to keep track of the previous element?
Thank you in advance!
 
First, no need to pass the id and then repull the element via the id - just pass a reference to the element itself:
Code:
onclick="setStyle(this)"

Second, just store a reference to the element in a global variable and use that to set back the color of the previously clicked cell. To make a variable global, just declare it outside any functions.

Code:
var lastClicked = false;
function setStyle(x) {
   if (lastClicked) {
      lastClicked.style.backgroundColor = "blue";
   }
   x.style.backgroundColor = "yellow";
   lastClicked = x;
}

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson

[small]<P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
 
Thank you Kaht! Your example worked like a charm and I appreciate your explanation! Thanks again! I'm really digging JS! :)

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top