Javascript code does not work on Chrome

Asked

Viewed 3,358 times

0

I’m starting with javascript and I made the following code below, only it’s not working on 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 tested it on Firefox and JS Bin site and it works perfectly.

  • Include in your script: <script type="text/javascript" src="test.js" defer></script>

  • 1

    Also include your tag script before closing the tag body and not later. Alias, which version of Chrome are you using? My version 58.0.3029.110 (64-bit) is working, I do not know if this has influence, but Chrome corrected the structure, automatically putting the tag script before the closure of body.

  • The younger one, this "Defer" is for what? but I think I know what happened, Chrome was caching the old code and not the new one.

  • 1

    defer ensures that the script is only loaded after loading html, for very old versions of browsers, does not work

  • 1

    Tip: always use anonymity mode to do your tests, and it’s okay to use the script between tags <body>

  • Okay, thank you, is there a "developer mode" for testing cacheless scripts?

  • 1
  • I tested on Chrome and it worked smoothly - i.e. I can’t reproduce the problem.

  • @Henriqueoliveira, solved your problem? It was really cache?

Show 4 more comments

2 answers

4

Problem may be the tag location script, it is not correct to put it after the closure of body.

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

This may vary from a browser for another and version to version, I tested in Chrome and Firefox (both in Windows) and in neither of the two Alert was shown. Anyway the best is at all times follow the recommendations of W3C. See an excerpt from the section about the script tag.

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

In free translation

This widget can appear as often as needed in the HEAD or BODY of an HTML document.

Therefore, your HTML code should 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 try Validator W3C who will see an error being accused.

-3

Try to add the following code:

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

Thus the event will be added to the button after the page is ready / Accessible DOM

Browser other questions tagged

You are not signed in. Login or sign up in order to post.