Limiting Characters per Line

PHOTO EMBED

Wed Aug 24 2022 16:26:24 GMT+0000 (Coordinated Universal Time)

Saved by @camtonguyen #javascript

(function() {
    const inputEls = document.querySelectorAll('input[name="product[name]"], textarea[name="product[short_description]"');
    function checkInputCharacters(input, inpuName) {
        const limit = 3; // <---max no. of lines
        const spaces = '40'; // <---max characters of each line
        const inputSpaces = '45'; // <---max characters of input
        const range = inpuName === 'product[short_description]' ? limit : inputSpaces;
        input.addEventListener('keyup', function() {
            const lines = inpuName === 'product[short_description]' ? input.value.split("\n") : input.value;
            for (let i = 0; i < lines.length; i++) {
                    if (lines[i].length <= spaces) continue;
                    let j = 0;
        
                    let space = spaces;
        
                    while (j++ <= spaces) {
                        if (lines[i].charAt(j) === " ") space = j;  
                    }
                lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] || "");
                lines[i] = lines[i].substring(0, space);
            }

            handleInputStateColor(input, lines, range);

            if (inpuName === 'product[short_description]') {
                input.value = lines.slice(0, limit).join("\n");
            } else {
                lines.length > inputSpaces && (input.value = lines.slice(0, -(lines.length - inputSpaces)));
            }
        })
    }
    
    function handleInputStateColor(input, inputVal, limit) {
      if (inputVal.length > limit) {
            input.style.color = 'red';
            setTimeout (function(){
                input.style.color = '';
            },500);
        }
    }

    Array.prototype.forEach.call(inputEls, (el) => {
      checkInputCharacters(el, el.name);
    });
})();
content_copyCOPY