0

I am new in javascript code. and my question about insert javascript external to html. and i see that whenn I use form tag in html so i have to write script code after form tag, if i write script code at head tage or before form tag so the code javascript will no work. please check detail below.

I have textbox_message.js

var text = "i am just a box only";
var textid = document.getElementById("text_id");
var linkid = document.getElementById("link_id");

linkid.onmouseover = function(){
     textid.value=text;
}

linkid.onmouseout = function(){
    textid.value = " ";
}

And textbox_message.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

</head>

<body>

<a href="pr4_1.html" id="link_id"> thi is link </a>
<form>
<input type="text" id="text_id" />
</form>
<script src="textbox_message.js" type="text/javascript"></script>
</body>
</html>

This code work okay but my question is: if I write script tag before as follow

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="textbox_message.js" type="text/javascript"></script>

</head>

<body>

<a href="pr4_1.html" id="link_id"> thi is link </a>
<form>
<input type="text" id="text_id" />
</form>
</body>
</html>

Or write script tag befor form tag

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

</head>

<body>
<script src="textbox_message.js" type="text/javascript"></script>

<a href="pr4_1.html" id="link_id"> thi is link </a>
<form>
<input type="text" id="text_id" />
</form>
</body>
</html>

Javascript will not work? Why?

user3536919
  • 93
  • 1
  • 2
  • 7

2 Answers2

0

The code you posted is executed immediately, so it will not "see" elements you are referencing to in latter cases. To fix this, use:

document.addEventListener('DOMContentLoaded', function() {
    // your code here
});

this will trigger code executing then DOM of the page is ready, so all elements you are referencing too will be available to use.

Petr Abdulin
  • 30,380
  • 8
  • 56
  • 90
0

this is because your javascript will be loaded first before your Input text element get loaded , so the Element will not found . same when you load your javascript after the the </body> tag the DOM get loaded and work well

Karthick Kumar
  • 2,364
  • 1
  • 14
  • 28