0

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

4
Contributors
4
Replies
7
Views
5 Years
Discussion Span
Last Post by Taywin
0

Yes, it is possible. We use external css file to add on the elements of HTML....

0

If you share the same javascript code among multiple pages, you should move your javascript code to an external file. For one, it will be easier to manage in the event that you need to make a change. And secondly, it keeps your HTML code organized and easy to read.

0

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?

Two people have already answered your first part of your question.

The second portion, it depends on how you organise your script and page. It is good to keep your HTML page clean from script tag; however, under some rare circumstances (especially when you deal with security), you may not want to include all scripts in every page. In this case, you should separate scripts into multiple .js files and select only certain files to be included in each page. Often times, there is no right or wrong in organising your script files. However, I would not put all js scripts in one file and include them in every page. I would leave certain js scripts in its own page if the functionality is depended to the page (when it is hard-code to deal with certain DOM elements).

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.