Thursday, July 29, 2010

Fun stuff with JQuery

Well, I've just about got to the stage where the data is being sucked out of the project XML file and into the database - and I'll add more detail about that when I have tidied it. However, in the meantime I thought I'd put a bit in here about the planned presentation.

The idea is to graph the resources' usage over a given time period. A guideline would be used to indicate whether the resources are over or under allocated.
The solution I had in mind was to use <div> tags of solid colour with a height varied to the height of the column in graph, dependent on the resource usage for that time period.
And to do this, the brave world of JQuery.

To begin with, I wanted to see if I could vary the height of a div tag using a text value input into a form on the page. Here is the code:
<script type="text/javascript" src="/Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#setHeight").click(function () {
$("#variable").height(parseInt($("#height").val()));
});
});
</script>

For a half-decent overview of JQuery, check this:

Let's break this down. The first line
<script type="text/javascript" src="/Scripts/jquery-1.4.1.js"></script>
is used to make the JScript functions available to the rest of the page.

$(document).ready(function () {
This is the line that ensures the HTML DOM is fully loaded. It stops code trying to work with objects that are not yet rendered.

$("#setHeight").click(function () {
When the button (not relevant) of id="setHeight" (very relevant) is clicked, carry out the instructions...

$("#variable").height(parseInt($("#height").val()));
Bit more complicated, but not much. For the item (the div) with id="variable", update the height to the value in the text box with id="height". The parseInt is required to cast the string returned to an integer value. I'm always surprised when Javascript, a language that isn't strongly typed, doesn't do this kind of thing for you.

For reference, the HTML elements in play here were:
<input type="text" id="height" />
<input type="button" id="setHeight" value="Set Height"/>
<div id="variable" style="background-color:Red; border:2; height:100px; width:100px">


1 comment:

  1. Buddy, save your self hours of head scratching at some point: always put 10 as the second parameter into parseInt. Here's why:
    http://stackoverflow.com/questions/850341/workarounds-for-javascript-parseint-octal-bug

    ReplyDelete