JavaScript code does not work in chrome [closed]

0

I'm starting with javascript and I made the following code, only it is not working in google chrome, why?

HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Teste</title>
</head>
<body>
<form>
    <input type="text" name="teste" id="teste"/>
</form>
</body>
<script type="text/javascript" src="test.js"></script>
</html>

test.js

var teste = document.getElementById("teste");

teste.addEventListener('click', function(){
    alert(1);
});

I have already tested it on Firefox and the JS Bin site and it works perfectly.

    
asked by anonymous 28.05.2017 / 20:06

2 answers

4

The problem may be the location of the script tag, it is not correct to place it after closing body .

If you want the script to be loaded after the body of the HTML, put the tag before closing from body .

This can range from one browser to another and from version to version, I tested it on Chrome and Firefox (both on Windows) and on neither of the two was the alert shown. In any case the best always to follow W3C . See an excerpt from the section on the tag script.

  

This element may appear any number of times in the HEAD or BODY of an HTML document.

Free Translation

  

This element can appear as many times as necessary in the HEAD or BODY of an HTML document.

Your HTML code should therefore be:

<body>
  <form>
    <input type="text" name="teste" id="teste"/>
  </form>
  <script type="text/javascript" src="test.js"></script>
</body>

If you want, you can test on the validator of the W3C that you will see an error being acknowledged.

    
29.05.2017 / 18:16
-3

Try adding the following code:

window.document.onload = function(e){ 
  var teste = document.getElementById("teste");
  teste.addEventListener('click', function(){
     alert(1);
  });
}

This will add the event to the button after the page is ready / accessible DOM

    
29.05.2017 / 04:41