1

My code in jsfiddle is working but when I try to use it in local it doesn't. I don't know how to fix it because i think that the code is right. I tried also to download the Jquery file and I linked it in the code but it doesn't working. I'm sure that is a stupid error, but I don't know how to solve it.

Working Jsfiddle

My prova.php file:

<html lang="it">
      <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <meta charset="UTF-8">
            <link rel="stylesheet" href="style.css"/>
        </head>
        <script type="text/javascript">

$('#btn').click(function() {
  var primo = document.getElementById('faketxt');
  var wordLimit = 145;
  var words = primo.textContent.replace(/(&lt;([^&gt;]+)&gt;)/ig,"").split(/\s/);
  if (words.length) {
    var count = 0;
    var div = createDiv();
    words.forEach(function(word) {
      if (++count > wordLimit) {
        count = 1;
        div = createDiv();
      }
      if (div.innerHTML) {
        div.append(' ');
      }
      div.append(word);
    });
  }
});

function createDiv() {
  div = document.createElement('div');
  div.className = 'fakes';
  document.getElementById('boxes').append(div);
  return div;
}

        </script> 
        <body>
<div id="faketxt" contenteditable>Write Here</div>
<button id='btn'>OK</button> <br>
<div id='boxes'>

</div>

</body>
</html>

My style.css:

#faketxt {
  -moz-appearance: textfield-multiline;
  -webkit-appearance: textarea;
  border: 1px solid gray;
  height: 28px;
  overflow: auto;
  padding: 2px;
  resize: both;
  width: 400px;
}

.fakes {
  width: 150px;
  height: 300px;
  font-size: 10px;
  border-style: solid;
  display: inline-block;
  float: left;
}

#boxes {
  display: flex;
  display: inline-block;
}
Niccolò Guidi
  • 195
  • 2
  • 14

2 Answers2

1

It is because your html is after js code. Put the js code after the html code or put it in dom ready.

What is happening is when your javascript code executes there is no #btn, no #faketxt and no #boxes. So the $("#btn") declared before <button id="btn"></button> returns an empty string because there is no element matched by it.

user31782
  • 7,087
  • 14
  • 68
  • 143
0

Possible Answers:

1: You linked a file with '//' like '//code.jquery.com'. Fix it: Replace '//' with 'http://'

2: Are you sure your CSS file is linked correctly? Maybe the file inside a subfolder css. Fix it: '/css/style.css'

howtoweb
  • 349
  • 1
  • 3
  • 10