JavaScript Where and Whys

In this post you will learn about Java Script and will get the answers of all your what/where and whys about Java Script. Where we can use this on our web page. Let’s check out below:

JavaScript Functions and Events

A JavaScript function is a block of JavaScript code, which can be executed when “called”. For example, a function can be called when an event occurs, such as when a user clicks or double click a button.

JavaScript in <head>

In this example, a JavaScript function is placed in the part of an HTML page. The function is invoked (invoked) when the button is clicked. You can also place java script in body tag, and it will work same, but it is recommended to add java script only under head tag.

<!DOCTYPE html>
<html>
<head>
<script>
function myFirstFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h2>Demo JavaScript Function is in Head Section </h2>

<p id="demo">A Paragraph</p>
<button type="button" onclick="myFirstFunction()">Try it</button>

</body>
</html>

We can have multiple methods in head section and also can pass multiple input parameters. You can pass input parameters (like ‘name‘ in below example) and can use those input parameters in code. Like

<!DOCTYPE html>
<html>
<head>
<script>
function myFirstFunction(var name) {
  document.getElementById("demo").innerHTML = "Text is changed on "+ name;
}
</script>
</head>
<body>
<h2>Demo JavaScript Function is in Head Section</h2>

<p id="demo">A Paragraph</p>
<button type="button" onclick="myFirstFunction("CodeConfig")">Try it</button>

</body>
</html>

External JavaScript

We can write java script code in separate file and can refer that file on our webpage. Let’ see how we can achieve this. Support I have external JS file named as: myJSScript.js and it contain following code.

function myFunction() {
  document.getElementById("demo").innerHTML = "Welcome to code config";
}

Above external scripts files are more practical when the same code need to be is used in many different web pages. JavaScript files have the file extension as .js. Now, to use an external JavaScript script, put the name of the script file in the src (source) attribute of a <script> tag:

<script src="myJSScript.js"></script>

Additionally, you can place reference of Above JS file in <head> or <body> tag, as per your requirement.

Leave a Reply

Your email address will not be published. Required fields are marked *