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

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

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.

Thank you!

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).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.