/    Sign up×
Community /Pin to ProfileBookmark

Dynamic DIVs, classes or colors via Javascript?

The short story is that I’m looking for a way to dynamically render colors within discrete cells of an HTML table.

More detail: I’m modifying some code I inherited and know enough Javascript to make myself dangerous. The page uses VBScript (which I don’t know at all and I merely add here for sake of completeness) to pull SQL server data that represents blocks of data. An HTML table is used to display those blocks of data numerically, one block per row. The number of rows is dynamic, depending upon the data.

I needed to add graphic visualization of these same blocks of data within this same page. So I’m using Walter Zorn’s Javascript VectorGraphics library ([url]http://www.walterzorn.com/jsgraphics/jsgraphics_e.htm[/url]) to render each data block in visually representative colors and positions. This library requires rendering either directly to the doc or to a named ID used as a canvas. So I set up a DIV and am successfully applying colors stored in a Javascript array to render the colored blocks. So far so good. Now….

The problem is that, for each data block, I also need to display the analogous array color [I][U]somehow[/U][/I] in each HTML row where the numeric version is displayed—a color key that tells the eye what numeric data row goes with various color block representations. For sake of simplicity, it can just be a color swatch that takes for the form of the cell background color or a CSS style background color. From what I can tell, neither HTML or CSS supports the variable structure needed to do this… so I’m assuming that Javascript is the way to go. I’m certainly open to other suggestions. In theory, I can use the jsgraphics.js functions to do this… which would require dynamically defining a unique div name for the cell in question in each HTML row… but I can’t figure out a good way to do that. I’ve tried adapting some posts employing the combo of [I]document.createElement[/I] and [I]document.body.appendChild[/I] but 1) I’ve had no luck and 2) ideally I need to have this div appear in place in each HTML row rather than at the end of the doc.

I’m open to any approach (although I don’t know any other languages.) I suppose a completely different alternative is blowing off the HTML table and presenting the data completely via Javascript and CSS, but I still need a way to dynamically change the colors.

Thanks so much!

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@infinityspiralMay 14.2009 — I was a little confused by the explanation, are you looking for a way to color a div in a row dynamically? If not, can you walk me through one iteration of your program's cycle?

If you're looking to create colored squares in a row you could create an array of hex colors and then assign them out as the program loops through each iteration.
Copy linkTweet thisAlerts:
@jeffburgerauthorMay 14.2009 — Thanks for your reply, infinityspiral. Yes, at it's simplest, I'm looking for a way to color a div in each row dynamically. Your suggestion to "create an array of hex colors and then assign them out as the program loops through each iteration" is exactly what I'm trying to figure out how to do. ?

I have the array already. Can you please advise re the basic mechanism to assign the array colors on the fly? (I'm assuming that it involves using Javascript to dynamically create or modify either the DIVs or the CSS classes/styles associated with those DIVs... but can't figure out how.)

Thanks so very much! ?
Copy linkTweet thisAlerts:
@infinityspiralMay 14.2009 — I did up a quick example of assigning css colors to objects using jquery so give this a try and see if it's close to what you're looking for.[CODE]
<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" type="text/javascript"></script>
<script>
/* wait until the page and scripts have been loaded */
$(function (){

/* assign colors */
$("td[title='red']").css("background-color","#ff0000");
$("td[title='blue']").css("background-color","#0000ff");
});
</script>

</head>

<body>
<table width="200" border="1">
<tr>
<th>item</th>
<th>color</th>
</tr>
<tr>
<td>data#1</td>
<td title="blue">blue target</td>
</tr>
<tr>
<td>data#2</td>
<td title="red">red target</td>
</tr>
</table>
</body>
</html>
[/CODE]
Copy linkTweet thisAlerts:
@jeffburgerauthorMay 14.2009 — Thanks so much, infinity!?

Alas, your example only addresses half the problem (I'll read up on jquery to understand why that part works). However, your example seems to assume hard coding of each table row/cell. I'm looking for a way to apply predefined colors dynamically within a loop. Here's some pseudo code to illustrate:

<!-- define colors, ideally via the array I'm already using elsewhere on this same page, but I could do parallel definitions via your jquery approach -->

var bgcolors = new Array("red", "blue", "green");

var SQLrecord;

<table>

while (SQLrecord<3){

<td><tr>

[COLOR="DarkRed"]<--dynamically assign bgcolors[SQLrecord] -->[/COLOR]

</td></tr>

SQLrecord++;

}

</table>

Thanks again! ?
Copy linkTweet thisAlerts:
@infinityspiralMay 15.2009 — Well if you want to iterate through the color array you could apply it like this:
[CODE]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" type="text/javascript"></script>
<script>
$(function (){
var bgcolor = new Array("red", "blue", "green");
var elementSelection = $('.colorflag');

var iter = 0;
jQuery.each(elementSelection, function(i,val) {
if(iter == bgcolor.length){
iter=0;
}
$(this).css("background-color",bgcolor[iter]);
iter++;
});

});
</script>
</head>

<body>
<table width="200" border="1">
<tr>
<td>label</td>
</td><td class="colorflag">data#1</td>
</tr>
<tr>
<td>label</td>
<td class="colorflag">data#2</td>
</tr>
<tr>
<td>label</td>
<td class="colorflag">data#3</td>
</tr>
<tr>
<td>label</td>
<td class="colorflag">data#4</td>
</tr>
<tr>
<td>label</td>
<td class="colorflag">data#5</td>
</tr>
<tr>
<td>label</td>
<td class="colorflag">data#6</td>
</tr>
</table>
</body>
</html>
[/CODE]


I assigned colorflag classes to certain td's in the table show you how to target and color only certain td's inside a table. A quick breakdown of what this script is doing:

[CODE] $(function (){
[/CODE]

This is a jQuery function that says to hold off on executing any jquery functions until the jquery library and page dom have been loaded.

[CODE] var bgcolor = new Array("red", "blue", "green");
var elementSelection = $('.colorflag');
[/CODE]

These are actually both arrays- one is an array of the colors, the other is an array of dom objects found. In this case it's all the objects with the class of "colorflag"

[CODE] var iter = 0;
[/CODE]

Starting value for our loop count

[CODE] jQuery.each(elementSelection, function(i,val) {
[/CODE]

jQuery function to execute a list of commands to every matched element. Since our target is elementSelection which is an array of objects with the class colorflag, this list of commands will be executed once for each element with the colorflag class.

[CODE] if(iter == bgcolor.length){
iter=0;
}
[/CODE]

if the number of times (iter) that the commands have been executed equals the number of colors, set the number of times count back down to zeros so we car start assigning colors from the beginning of the list.

[CODE]
$(this).css("background-color",bgcolor[iter]);
[/CODE]

target the particular matched object using "this" keyword and apply the background color from our list of colors to the background of the matched element. If you wanted to use hex values you could, just make sure to include the # before the number when setting up the array.

[CODE]
iter++;
[/CODE]

increase the count for how many times the commands have been executed

[CODE] });

});
[/CODE]

close our each function and then close our jquery page ready function
×

Success!

Help @jeffburger spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...