I'm new to javascript.
Lets say I need to create a new <p>
everytime the user clicks on a button.
So I create a button in the html body and assign a function as the event handler of onclick
.
This function is in a separate file called "file.js"
which I include in the main html file using <script type="text/javascript" src = "file.js">
.
In my "file.js" there is that function that does this:
var body = document.getElementsByTagName("body")[0];
var para = document.createElement("p");
var text = document.createTextNode("hello");
para.appendChild(text);
body.appendChild(para);
Now is it possible that this function being in a separate file access the DOM elements in another html file?
I found that the above thing works.
But what if I've included the same "file.js" in many html files?
Will it do the same stuff independently to each of the html files?
And one more question :
How right is it put all the javascript code in the <script> tags of the html file?
Is it considered any better to put all the js code in separate .js files?
I've noticed that many sites (including this) have some js code written in html file itself.
Please help.
Thanks