Question

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/

Was it helpful?

Solution 2

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/

OTHER TIPS

Not too hard. You don't even need jQuery.

http://jsfiddle.net/pxmmh/4/

// 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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top