The HTML and CSS for this is dead simple, so I'm not going to bother to go through it in detail. The button to bind the event to is
button#generate
, and the letter appears in div#letter
.To bind the event to the button I used jQuery. I wanted to use jQuery to populate the div with the generated letter because the code would be much cleaner. This is an incredibly short bit of scripting.
$(document).ready(function(){
$('#generate').click(function() {
$('#letter').text(String.fromCharCode(65 + Math.round(Math.random() * 25)));
});
});
The clever part here is how the letter is generated. I've generated a random number under 25 (26 letters in English alphabet, 0 based) and then added 65 to it. This gives the decimal code from the ASCII table for upper case, English alphabet characters. Change this to 97 if you want lower case letters. By feeding this into the function String.fromCharCode you change your randomly generated number into a letter.
No comments:
Post a Comment