Alessandro Lacava’s Blog

Google
 

November 24, 2006

How to add scrollbars to a block (e.g. a <div>) element

Filed under: Computer, CSS — alessandrolacava @ 11:21 am

If you need to customize a list box then the <select> HTML element might not be enough. In such a case you’d like to have something that simulates the <select> behaviour. In practise, you want to obtain something like the following figure without using the <select> HTML element.
customListBox.JPG

customListBox.JPG

Here is the code to use to obtain that result:

<html>
<head>
</head>

<body>
<div style="width: 200px; height: 200px; overflow: auto;">
<table width="100%" height="100%">
<script>
for (var i = 0; i < 30; i++)
if (i % 2 == 0)
document.write(
"<tr style='background-color:#0066ff; color: #ffffff'>" +
"<td>JavaScript</td></tr>");
else
document.write(
"<tr style='background-color:#ff6600; color: #ffffff'>" +
"<td>JavaScript</td></tr>");
</script>
</table>
</div>
</body>
</html>

The key CSS element is overflow. If you use overflow: auto then the scrollbars are displayed only if they are needed. If you want to display them in any case then you need to use overflow: scroll.


November 20, 2006

Sorting an array of objects with the sortBy method of Prototype

Filed under: Computer, JavaScript, Prototype — alessandrolacava @ 5:34 pm

Here is an example of how easy it is to sort an array of objects using the Enumerable.sortBy method of the Prototype framework:

JavaScript:
  1. var obj1 = {
  2. lastName : "Lacava",
  3. firstName : "Alessandro"
  4. };
  5.  
  6. var obj2 = {
  7. lastName : "Brown",
  8. firstName : "John"
  9. };
  10.  
  11. var obj3 = {
  12. lastName : "Simpson",
  13. firstName : "Bart"
  14. };
  15.  
  16. var arr = [obj1, obj2, obj3];
  17.  
  18. //order by last name
  19. var sorted = arr.sortBy( function(obj)
  20. {
  21. return obj.lastName.toLowerCase();
  22. }
  23. );
  24.  
  25. var str = "";
  26. sorted.each( function(obj, index)
  27. {
  28. str += index + 1 + " - " + obj.lastName + " " + obj.firstName + "
  29. ";
  30. }
  31. );
  32.  
  33. //display the elements ordered by last name
  34. document.write(str);