Invoking JavaScript Functions from HTML A Quick Guide

0
53
Invoking JavaScript Functions from HTML A Quick Guide

In the realm of web development, the interaction between HTML and JavaScript is crucial for creating dynamic and interactive web pages. Call JavaScript function from HTML enables developers to respond to user actions, manipulate the DOM (Document Object Model), and enhance the overall user experience. In this guide, we’ll explore how to seamlessly Invoking Java Script function from within HTML.

Inline JavaScript Calls

One of the simplest ways to call a JavaScript function from HTML is to use inline event attributes. Here’s an example:

<!DOCTYPE html>
<html>
<head>
<title>Calling JavaScript from HTML</title>
</head>
<body>
<button onclick=”sayHello()”>Click me</button>

<script>
function sayHello() {
alert(‘Hello, world!’);
}
</script>
</body>
</html>

Using Event Listeners

While inline event attributes are simple, a more organized approach involves using event listeners. Event listeners provide greater flexibility and separation of concerns.

<!DOCTYPE html>
<html>
<head>
<title>Calling JavaScript from HTML</title>
</head>
<body>
<button id=”myButton”>Click me</button>

<script>
function sayHello() {
alert(‘Hello, world!’);
}

// Attach event listener to the button
var button = document.getElementById(‘myButton’);
button.addEventListener(‘click’, sayHello);
</script>
</body>
</html>

In this version, the JavaScript function sayHello() is attached to the button element using the addEventListener() method. When the button is clicked, the sayHello() function is executed.

Calling Functions with Parameters

You can also call JavaScript functions with parameters from HTML:

<!DOCTYPE html>
<html>
<head>
<title>Calling JavaScript with Parameters</title>
</head>
<body>
<button id=”greetButton”>Greet</button>

<script>
function greet(name) {
alert(‘Hello, ‘ + name + ‘!’);
}

var greetButton = document.getElementById(‘greetButton’);
greetButton.addEventListener(‘click’, function() {
var userName = prompt(‘Enter your name:’);
greet(userName);
});
</script>
</body>
</html>

In this example, the greet() function is called with the user’s name as a parameter when the button is clicked. The name is obtained through a prompt() input.

Call JavaScript function from HTML is a fundamental skill for creating interactive web pages. Whether using inline event attributes or event listeners, this capability empowers developers to respond to user actions and dynamically modify web content. By understanding the techniques presented here, you’re well on your way to crafting engaging and interactive web experiences.