Robert Zamboni Robert Zamboni - 4 months ago 19
HTML Question

Code works in jsfiddle but not in html page

I am using code from Max lines textarea to create a textarea with only 9 lines and this code works perfectly on my jsfiddle, https://jsfiddle.net/cityFoeS/3j48cpzn/ The textarea will not limit the textarea to 9 lines like I want it to.

my HTML:

<html>
<head>
<style>
body {
background: black;
}
textarea {
overflow: hidden;
resize: none;
font-family: courier;
color: white;
outline: none;
line-height: 20px;
margin: 0;
padding: 0;
border: 0;
left: 45px;
position: absolute;
font-size: 14px;
background-color: black;
border-bottom: 1px solid white;
}
div {
font-family: courier;
color: white;
line-height:20px;
position: absolute;
font-size: 14px;
width: 29px;
border-right: 1px solid white;
border-bottom: 1px solid white;
left: 10px;
}
</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
var limit = 9; // <---max no of lines you want in textarea
var textarea = document.getElementById("splitLines");
var spaces = textarea.getAttribute("cols");

textarea.onkeyup = function() {
var lines = textarea.value.split("\n");

for (var i = 0; i < lines.length; i++)
{
if (lines[i].length <= spaces) continue;
var j = 0;

var 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);
}
if(lines.length>limit)
{
textarea.style.color = 'red';
setTimeout(function(){
textarea.style.color = '';
},500);
}
textarea.value = lines.slice(0, limit).join("\n");
};
</script>
</head>
<body>
<div>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10</div><textarea rows="10" cols="50" id="splitLines" onpaste="return false;"></textarea>
</body>
</html>

Answer

The problem is that in JSFiddle, you have the option "Load Type" set to "onload" under the JavaScript options.

In your code, however, the JavaScript runs immediately, before the HTML — this will cause the error (and this is what I get when running it as a standalone HTML page):

Uncaught TypeError: Cannot read property 'getAttribute' of null

There are two solutions:

  1. Moving the <script> tags to the end of the <body> tag. For example:

    <body>
        <!-- all your visible HTML elements -->
        <script>
            // all your JS code
        </script>
    </body>
    
  2. Encapsulating all the JavaScript in a window.onload function or a $(function() {}) (for use with jQuery). For example:

    <script>
        window.onload = function() {
            // all your JS code
        };
    </script>
    
Comments