The online racing simulator
JavaScript!
Google has a countdown to 2009 and with all of the newb questions on how to do a proper JavaScript Timer, I thought I would dissect this for ya all and post it up here. Pretty good job from the google guys, but then, I would expect nothing less. I guess I'll do the Calendar next


<?php 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
    <
head>
        <
meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <
title>Google Timer</title>
        <
style type="text/css">
            
htmlbody {
                
margin1em 0 0 0;
                
padding0 0 0 0;
                
background-color#002040;
                
color#FFFFFF;
                
font1em Arial;
            }
        </
style>
        <
script charset="utf-8" type="text/javascript">
            var 
= new Date();
            var 
today d.getDate();

            function 
Calcage(secstimeUnittimeUnitMax) {
                var 
= ((Math.floor(secs timeUnit)) % timeUnitMax).toString();
                if (
s.length 2)
                    
'0' s;
                return (
s);
            }

            function 
CountBackLoop(targetDatepreFix) {
                var 
dthen = new Date(targetDate);
                var 
dnow = new Date();
                var 
ddiff = new Date(dthen dnow);
                var 
secs Math.floor(ddiff.valueOf() / 1000);

                
// calculate the amount of time remaining 
                
var ddays Calcage(secs86400100000);
                var 
dhrs Calcage(secs360024);
                var 
dmins Calcage(secs6060);
                var 
dsecs Calcage(secs160);
                if (
secs <= 0)
                    
ddays dhrs dmins dsecs 0
                
else
                    
setTimeout('CountBackLoop();'990);

                
// write the amount of time remaining to the countdown timer
                
document.getElementById(preFix '_day').innerHTML ddays;
                
document.getElementById(preFix '_hr').innerHTML dhrs;
                
document.getElementById(preFix '_min').innerHTML dmins;
                
document.getElementById(preFix '_sec').innerHTML dsecs;
            }

            function 
pageInit() {
                
CountBackLoop('12/28/2008 15:00''TopGear');
                
CountBackLoop('01/01/2009 00:00''2009');
            }
        
</script>
    </head>
    <body onload="pageInit();">
        <center>
            <h2 id="timer">
                <span id="countdown">
                    <span id="TopGear_day"></span> days,
                    <span id="TopGear_hr"></span> hours,
                    <span id="TopGear_min"></span> mins,
                    <span id="TopGear_sec"></span> secs
                    until Next Episode of TopGear!
                </span>
                <br />
                <span id="countdown">
                    <span id="2009_day"></span> days,
                    <span id="2009_hr"></span> hours,
                    <span id="2009_min"></span> mins,
                    <span id="2009_sec"></span> secs
                    until 2009!
                </span>
            </h2>
        </center>
    </body>
</html>
?>

Quote from Dygear :on how to do a proper JavaScript Timer

Just a plea to any planning on using JS in any sort of major manner (i.e. in a large project) - make it gracefully degrade. The google countdown is a good example of how to assume that it's turned on, and what happens when it's not.

Use JS to rewrite the DOM, rather than write it completely and provide complete functionality
Quote from the_angry_angel :Just a plea to any planning on using JS in any sort of major manner (i.e. in a large project) - make it gracefully degrade. The google countdown is a good example of how to assume that it's turned on, and what happens when it's not.

Use JS to rewrite the DOM, rather than write it completely and provide complete functionality

Mind posting an Example?
Quote from the_angry_angel :Just a plea to any planning on using JS in any sort of major manner (i.e. in a large project) - make it gracefully degrade. The google countdown is a good example of how to assume that it's turned on, and what happens when it's not.

I disabled JS for the hell of it, and I see what you mean. At the top of the page, it just says " days, hours, mins, secs until 2009!". And the calendar doesn't even show up! Wow, google, wow.

Quote from Dygear :Mind posting an Example?

noscript tag? That would allow limited functionality. Like displaying the countdown from when the page was refreshed (which would, however, require server-side scripting obviously), but still show the whole calendar thing below it, and the search box. Limited functionality, but better then the page being all messed up. Problem, of course, is the larger amount of disk space required to render the page. Perhaps, a server-side javascript renderer would work better. There would be an application which would render all the javascript on the page and send it to the user as regular HTML. Limit of that method is processing power being used up.
-
(wheel4hummer) DELETED by wheel4hummer : double post
Quote from wheel4hummer :noscript tag? That would allow limited functionality. Like displaying the countdown from when the page was refreshed (which would, however, require server-side scripting obviously), but still show the whole calendar thing below it, and the search box. Limited functionality, but better then the page being all messed up. Problem, of course, is the larger amount of disk space required to render the page. Perhaps, a server-side javascript renderer would work better. There would be an application which would render all the javascript on the page and send it to the user as regular HTML. Limit of that method is processing power being used up.

I do have a php function that I made a while back that makes Calendars ...


<?php 
php
function generate_calendar($year NULL$month NULL$days = array(), $day_name_length 3$month_href NULL$first_day 0$pn = array()){

    if (
$year === NULL) {
        
$year date('Y');
    }
    if (
$month === NULL) {
        
$month date('m');
    }

    
$first_of_month gmmktime(0,0,0,$month,1,$year);
    
$day_names = array();
    for (
$n 0,$t = ($first_day) * 86400$n 7$n++, $t += 86400)
        
$day_names[$n] = ucfirst(gmstrftime('%A',$t));
    list (
$month$year$month_name$weekday) = explode(','gmstrftime('%m,%Y,%B,%w'$first_of_month));
    
$weekday = ($weekday $first_day) % 7;
    
$title   htmlentities(ucfirst($month_name)) . ' ' $year;
    @list(
$p$pl) = each($pn);
    @list(
$n$nl) = each($pn);
    if(
$p$p '<span class="calendar-prev">' . ($pl '<a href="' htmlspecialchars($pl) . '">' $p '</a>' $p) . '</span> ';
    if(
$n$n ' <span class="calendar-next">' . ($nl '<a href="' htmlspecialchars($nl) . '">' $n '</a>' $n) . '</span>';
    
$calendar '<table class="calendar">' "\n" '<caption class="calendar-month">' $p . ($month_href '<a href="' htmlspecialchars($month_href) . '">' $title '</a>' $title) . $n "</caption>\n<tr>";
    if (
$day_name_length) {
        foreach(
$day_names as $d)
            
$calendar .= '<th abbr="'.htmlentities($d).'">'.htmlentities($day_name_length substr($d,0,$day_name_length) : $d).'</th>';
        
$calendar .= "</tr>\n<tr>";
    }
    if (
$weekday 0)
        
$calendar .= '<td colspan="' $weekday '"> </td>';
    for (
$day 1$days_in_month gmdate('t'$first_of_month); $day <= $days_in_month$day++, $weekday++) {
        if (
$weekday == 7){
            
$weekday   0;
            
$calendar .= "</tr>\n<tr>";
        }
        if (isset(
$days[$day]) && is_array($days[$day])) {
            @list(
$link$classes$content) = $days[$day];
            if (
is_null($content))
                
$content  $day;
            
$calendar .= '<td' . ($classes ' class="'.htmlspecialchars($classes) . '">' '>'). ($link '<a href="' htmlspecialchars($link) . '">' $content '</a>' $content) . '</td>';
        } else {
            
$calendar .= "<td>$day</td>";
        }
    }
    if (
$weekday != 7)
        
$calendar .= '<td colspan="' . (7-$weekday) . '"> </td>';
    return 
$calendar "</tr>\n</table>\n";
}
?>

edit: irrelevant.
Quote from Dygear :Mind posting an Example?

Unfortunately most of the real world code I've written to do this sort of stuff over the last 3 years is in a non-public application for work, and most of the personal stuff I do doesn't need the fancy JS stuff, as its only me using it.

However, a high level example would be something like this - a rating form for an item - the client by default gets a full form, with a dropdown list of "poor", "good", "excellant" and a submit button. To make it cooler, on full document load (I use jQuery, so "document ready") I find the form, remove the submit button, and hide the dropdown list. I then insert 3 images (stars), with applicable functions on hover, which changes the star to a filled in star, and on click which submits the rating for that item using a XMLHttpRequest, and sets the value of the dropdown list to match (because in the actual code this happens in, it's possible to submit the form in other ways).

Using jQuery or Prototype, etc. makes stuff like this very easy. Now some will argue that you're making life harder for yourself, and to an extent you are. However, I view it this way - I'm writing 1 full application, which will work in almost any browser from the last 10-15 years, and then I am modifying it only slightly.

If you're using MVC in some form, it makes dealing with getting data back in a compatible format very easy. For the Zend Framework you can write your own context handler, or use the AjaxContext controller plugin, there are applicable examples for almost every framework out there. If you've rolled your own it's almost as easy to do, as most popular JS frameworks send a "X_REQUESTED_WITH: XMLHttpRequest" header, so it's trivial to detect an "ajax" request.

Edit:
Simon Willison's talk from May of this year might be of interest as it covers unobtrusive/graceful degradation - http://simonwillison.net/static/2008/xtech/
Quote from the_angry_angel :However, a high level example would be something like this

Here's a working example from a site I made a while ago. It's not a rating system, but the gallery there is coded up in the same basic way you described. If JS is turned off or unavailable, each of the thumbnails in the gallery just link to a new page with the selected image. If it's on, the image gets loaded and inserted dynamically into the currently loaded page.
Quote from the_angry_angel :Just a plea to any planning on using JS in any sort of major manner (i.e. in a large project) - make it gracefully degrade.

Entirely agree.

Quote :Use JS to rewrite the DOM, rather than write it completely and provide complete functionality

Exactly
MySQL SELECTING VALUES FROM one TABLE to INSERT INTO another.
I have a question about MySQL querys.

My problem, I have a table that has users who have been added out of order of their joindate (JDate) so when I sort the table by `JDate` it provides a result that is inconsistent with a incrementing numerical value of the PRIMAY KEY `id`. I would like to craft a query that would allow me to select the values from one table and insert them into another table. The table `members` and `members_sorted` have the same structure as shown in the query.

Here is the query so far:

--
-- Table structure for table `members_sorted`
--

CREATE TABLE IF NOT EXISTS `members_sorted` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`FName` varchar(32) NOT NULL,
`LName` varchar(32) NOT NULL,
`Status` set('Advisor','Active','Inactive','Medical','Leave') NOT NULL,
`JDate` date NOT NULL,
`BDate` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MEMORY DEFAULT CHARSET=latin1;

--
-- Dumping data for table `members` SORTING VALUES INTO `members_sorted`;
--

INSERT INTO `members_sorted` SELECT `FName`, `LName`, `Status`, `JDate`, `BDate` FROM `members` ORDER BY `JDate`, `LName`;

However this query returns the error: #1136 - Column count doesn't match value count at row 1; I know this is due to myself omitting the `id` from the list, but I don't want that value to be transmitted over to the new table, I would like that value to be dynamically rebuilt with this query.
Quote from Dygear :However this query returns the error: #1136 - Column count doesn't match value count at row 1;

A select into might be more useful in your situation Dygear -
SELECT `FName`, `LName`, `Status`, `JDate`, `BDate` INTO `members_sorted` FROM `members` ORDER BY `JDate`, `LName`;

Or
INSERT INTO `members_sorted` (`FName`, `LName`, `Status`, `JDate`, `BDate`) VALUES(SELECT `FName`, `LName`, `Status`, `JDate`, `BDate` FROM `members` ORDER BY `JDate`, `LName`);

Either should work, if I've remembered correctly. Edit: That said, a view might even be more appropriate, assuming your SQL engine supports them.
Quote from Dygear :However this query returns the error: #1136 - Column count doesn't match value count at row 1; I know this is due to myself omitting the `id` from the list, but I don't want that value to be transmitted over to the new table, I would like that value to be dynamically rebuilt with this query.

Is there any difference using the below create table statement rather the one you included above?


CREATE TABLE IF NOT EXISTS `members_sorted` (
`id` int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
`FName` varchar(32) NOT NULL,
`LName` varchar(32) NOT NULL,
`Status` set('Advisor','Active','Inactive','Medical','Leave') NOT NULL,
`JDate` date NOT NULL,
`BDate` date NOT NULL
) ENGINE=MEMORY DEFAULT CHARSET=latin1;

INSERT INTO `members_sorted` SELECT [b]`id` = NULL[/b], `FName`, `LName`, `Status`, `JDate`, `BDate` FROM `members` ORDER BY `JDate`, `LName`;

That worked. LOL;
I think that's what they call an elegant solution.
Incidentally, how do you all pronounce SQL? I was always taught to pronounce it ess-qee-ell, but over the last few years I've made the mental gear-shift to start pronouncing it as sequel, as that's how the Amaracans say it. I prefer the original French abbreviation, I think.
Quote from DarkTimes :Incidentally, how do you all pronounce SQL?

I'm a firm believer in "call it whatever the hell you like". I hate these creative pronunciations the geek community always insists on using. "guh-nome", "postgres-cue-ell", "sequel"... gimme a frikkin' break. If they want me to pronounce it that way they can spell it accordingly. (Which means I pronounce it ess-cue-ell, since... that what it says.)
Quote from wien :I'm a firm believer in "call it whatever the hell you like". I hate these creative pronunciations the geek community always insists on using. "guh-nome", "postgres-cue-ell", "sequel"... gimme a frikkin' break. If they want me to pronounce it that way they can spell it accordingly. (Which means I pronounce it ess-cue-ell, since... that what it says.)

This man speaks bucket-loads of sense "Ess-cue-ell" is the way forward.
Quote from DarkTimes :Incidentally, how do you all pronounce SQL? I was always taught to pronounce it ess-qee-ell, but over the last few years I've made the mental gear-shift to start pronouncing it as sequel, as that's how the Amaracans say it. I prefer the original French abbreviation, I think.

The right pronounciation is ess-cue-ell
Quote from DarkTimes :Incidentally, how do you all pronounce SQL?

Quote from Wikipedia :The first version of SQL was developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in the early 1970s. This version, initially called SEQUEL, was designed to manipulate and retrieve data stored in IBM's original relational database product

Sequel it is then...

Sequel is faster and easier to say anyway.
If you read the whole article you can see that is the old name for the SQL predecessor. There's no "C" or "E" so I am proud to pronounce it as "es queue el"
Quote from DarkTimes :Incidentally, how do you all pronounce SQL? I was always taught to pronounce it ess-qee-ell, but over the last few years I've made the mental gear-shift to start pronouncing it as sequel, as that's how the Amaracans say it. I prefer the original French abbreviation, I think.

I pronounce it ess-qee-ell, I find the term sequel to be inaccurate as it an acronym not a word. Though I call AOL Instant Messager aim and not by each letter individually ... A-I-M.
Quote from Dygear :I pronounce it ess-qee-ell

Why qee?

Surely 'Q' is pronounced cue, or queue etc.
Quote from pb32000 :Why qee?

Surely 'Q' is pronounced cue, or queue etc.

SQL = ess-cue-ell (normal) || ess-qee-ell (accent)

The Off Topic Programming Thread!
(309 posts, started )
FGED GREDG RDFGDR GSFDG