Programming Tutorials

Different methods to embed JavaScript in HTML.

By: aathishankaran in JavaScript Tutorials on 2007-03-21  

HTML gives you the capability to create remarkable static Web pages. Although these documents have been creative, interesting, and by all means useful, JavaScript gives you the capability to make these extensive static pages interactive and more responsive to user actions and input. Extending your HTML pages with JavaScript puts more power to your page and gives you more flexibility with what your HTML can do. JavaScript cannot stand-alone but is always tied to your HTML page and the browser. JavaScript is an interpreted language that is processed by the browser when the page loads. 

JavaScript enables the Web developer to create pages that are more dynamic by embedding a scripting language in the existing HTML structure. You can now put processes behind buttons, run calculations on form-entered data, or perform actions when the user moves the mouse over an HTML object.

There are several ways to embed JavaScript code in HTML:

Inline Script:

You can add JavaScript code inside an HTML element by using the on attribute. For example:

<button onclick="alert('Hello World!')">Click Me</button>

Script Tag:

You can add JavaScript code using the <script> tag. You can include the code inside the tag, or reference an external file. For example:

<script>
function greet() {
alert('Hello World!');
}
</script> <script src="script.js"></script>

Event Handlers:

You can attach JavaScript code to an HTML element using event handlers. For example:

<button id="myButton">Click Me</button>
<script>
document.getElementById('myButton').addEventListener('click', function() {
alert('Hello World!');
});
</script>

URL Handlers:

You can use the javascript: protocol to execute JavaScript code when the user clicks on a link. For example:

<a href="javascript:alert('Hello World!')">Click Me</a>

External Library:

You can use an external library such as jQuery to add JavaScript code to your HTML page. For example:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
$(document).ready(function() {
$('#myButton').click(function() {
alert('Hello World!');
});
});
</script>

These are some of the ways to embed JavaScript code in HTML






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in JavaScript )

Latest Articles (in JavaScript)