Reputation:
I am struggling to see how to turn a piece of javascript from obtrusive to unobtrusive, can anybody shed some light?
Here's the script:
function limitText(limitField, limitCount, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
} else {
limitCount.value = limitNum - limitField.value.length;
}
Here's the JSFiddle: http://jsfiddle.net/pxmmh/
Upvotes: 0
Views: 267
Reputation: 187034
Not too hard. You don't even need jQuery.
// your function you have now
function limitText(limitField, limitCount, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
} else {
limitCount.value = limitNum - limitField.value.length;
}
}
// bind event handlers to the DOM
var field = document.getElementById('limited');
field.onkeydown = function() {
var counter = document.getElementById('limited-count');
var limit = parseInt(field.dataset.limit, 10)
limitText(field, counter, limit);
};
The field and the counter have been given id's, allowing us to find them. And the limit is now a data-*
HTML5 property we can access with the .dataset
property in JavaScript, which allows the element to say what's it's own limit is.
Upvotes: 1
Reputation: 33823
If you want a truly unobtrusive solution, some jQuery will work wonders for you
$(document).ready(function () {
$('#limitedtextfield').keyup(function () {
limitText(this.form.limitedtextfield, this.form.countdown, 15);
});
$('#limitedtextfield').keydown(function () {
limitText(this.form.limitedtextfield, this.form.countdown, 15);
});
function limitText(limitField, limitCount, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
} else {
limitCount.value = limitNum - limitField.value.length;
}
}
});
See JSFiddle here http://jsfiddle.net/x65Kw/
Upvotes: 0
Reputation: 86504
In this case, it's not terribly obtrusive; if JS is off, nothing significant is broken. What you'd want to do, though, is attach the events in an onload, and have the paragraph that says "You have X chars left", either hidden or absent by default. Have that same onload either unhide or add it, since it'll only be useful if the JS runs anyway.
Upvotes: 0