JSFiddle - React, Tailwind, and code Playground
by ryanwheale
HTML
<label for="ccnumber">Credit Card Number:</label>
<input type="text" name="myinput" id="ccnumber" />
<p id="logger"></p>
CSS
.alert {
color: red
}
#logger {
height: 250px;
margin-top: 2em;
border: 1px solid #ccc;
overflow: auto;
}
JavaScript
// TODO: wrap this up in a pretty little object for reuse
$(function() {
var // Keep count of key strokes
keyCount = 0,
// Number of times the event handlers have been bound
applyHandlerCount = 0,
// Holder for the interval function
applyHandlerInterval = 0,
// Used to give event handlers an unpredictable namespace... but this isn't enough
handlerNamespace = randomString(20),
// Context in which to call event handlers. The handlers must match the secret key.
safeContext = { secretKey: randomString(40) },
// For deduping purposes
closeTime = 0,
$logger = $('#logger'),
$ccInput = $('#ccnumber'),
$ccLabel = $('label[for="' + $ccInput.attr('id') + '"]'),
ccLabelText = $ccLabel.length ? $ccLabel.text() : 'What is your credit card number.?';
// Applies event handlers. The interval function checks to make sure these handlers work.
function applyHandlers() {
log('Applying event handlers in namespace "' + handlerNamespace + '"');
if (applyHandlerCount < 5) {
applyHandlerCount++;
$ccInput.unbind('.' + handlerNamespace );
$ccInput.on('focus.' + handlerNamespace, handleFocus);
$ccInput.on('keyup.' + handlerNamespace, handleKeyup);
} else {
clearInterval( applyHandlerInterval );
// Something keeps on removing the event handlers.
// Warn the user that it appears as though security has been breached
}
}
applyHandlers();
function handleFocus (ev) {
// Check to see if firing in safe context and match the secret key
if(this.secretKey) {
return this.secretKey === safeContext.secretKey;
}
var len = 0,
result,
stars,
lastFour,
fireTime = (new Date()).getTime();
// De-dupe the focus event
if(fireTime -...