David David - 1 year ago 86
CSS Question

Assigning CSS style to variable in JavaScript

I am writing a simple JavaScript function that takes a td (table cell) and either gives it a red border style or turns this off. The code is:

function doStuff(theCell)
{
var highlight = "2px solid rgb(255, 0, 0)";
if(borderStyle==highlight)
{
theCell.style.border="";
}
else
{
theCell.style.border=highlight;
}
}


This works fine. However to try to make the code cleaner I tried to replace the css border style by a variable (declared just below the first one):

var borderStyle = theCell.style.border;


This works OK when I use it in the equality comparison, but not when I put it in the style assignation in the ‘else’ clause.

I must be trying to do something very foolish. Could anyone explain.

Answer Source

Javascript does not create reference to the object if you write code such as var borderStyle = theCell.style.border;. Here a copy of only the value of border is assigned to borderStyle. The object which is theCell remained unharmed at its place. No reference is created to it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download