Anniversaire
Il existe une version plus récente de cette page qui utilise davantage les fonctionnalités nouvelles de HTML 5.
Le code suivant figure dans l'en-tête du document :
<script type="text/javascript">
function countdown(year, month, day) {
var temp;
var future = new Date(year, month-1, day);
var today = new Date();
temp= Math.floor((future.getTime() - today.getTime()) /(24*60*60*1000)) + 1;
if (temp < 0) { temp = temp + 365; }
return temp;
function age(year, month, day) {
var today = new Date();
var current_year = today.getFullYear();
nb_years = current_year - year;
var had_birthday = (today >= new Date(current_year, month -1, day));
temp = had_birthday ? nb_years : nb_years -1; // if the birthday is over we remove 1 year
return temp;
}
function check_text(entry) {
var temp;
var exp = new RegExp(/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/);
temp = exp.test(entry);
if (temp == false) { age_block.innerHTML = "Date invalide.";}
return temp;
}
function check_date(year, month, day) {
var temp;
var newDate = new Date(year, month-1, day); // we try to generate the date
if (newDate.getFullYear() == year && newDate.getMonth() == month-1 && newDate.getDate() == day) { temp = true; }
else { age_block.innerHTML = "Cette date n'existe pas."; temp = false; }
return temp;
}
function result() {
var temp;
var year; var month; var day;
// ancien format dd/mm/yyyy ou dd / mm / yyyy
var birthday_date = date.value.replace(/ /g, '');
date_valid = check_text(birthday_date);
if (date_valid) {
temp = birthday_date.split('/');
year = temp[2]; month = temp[1]; day = temp[0];
date_valid = check_date(year, month, day);
if (date_valid) {
age_block.innerHTML = "Vous avez " + age(year, month, day) + " ans.";
var today = new Date();
var wait = countdown(today.getFullYear(), month, day);
if (wait == 0) {
birthday_block.innerHTML ='' + image_with_caption(image_name, image_width, image_height, image_caption) + '
Bon anniversaire.
';
setTimeout(anime, 2200);
clearTimeout(anime);
}
else { birthday_block.innerHTML = "
Il reste " + wait + " jours avant votre anniversaire."; }
}
}
}
</script>
Le code suivant figure dans le corps du document :
<form id = "form_test_id" onsubmit = "result(); return false;">
<label for="date_id">Votre date de naissance: </label><input type="text" id="date_id" maxlength="10" value="DD/MM/YYYY" required><br>
<br>
<input type='button' value="Validation" onclick = "result();">
</form>
<div id="age_block_id"></div>
<div id="birthday_block_id"></div>
<script type="text/javascript">
/* these constants must be initialized after the page is displayed */
const age_block = document.getElementById('age_block_id');
const birthday_block = document.getElementById('birthday_block_id');
const date = document.getElementById('date_id');
</script>
Adresse de cette page: http://www.didac-tic.fr/web/javascript/birthday.php