Open In App

How does inline JavaScript work with HTML ?

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Inline JavaScript refers to JavaScript code embedded directly within HTML elements using the onclick, onmouseover, or other event attributes. This allows you to execute JavaScript code in response to user interactions or specific events without needing a separate JavaScript file or script block.

Syntax

<script>
// JavaScript Code
</script>

Example: In this example, the Inline JavaScript in the onclick attribute triggers the showAlert() function when the button is clicked, validating the input field and showing an alert with a greeting or error message.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Inline JavaScript</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>

<body>
    <div class="container">
        <h1 style="text-align:center;color:green;">
            GeeksforGeeks
        </h1>
        <form>
            <div class="form-group">
                <label for="">Enter Your Name:</label>
                <input id="name" class="form-control" 
                       type="text" 
                       placeholder="Input Your Name Here">
            </div>
            <div class="form-group">
                <button class="btn btn-success btn-lg float-right" 
                        type="button"
                        onclick="showAlert()">
                    Submit
                </button>
            </div>
        </form>
    </div>
    <script>
        function showAlert() {
            let user_name = document.getElementById("name");
            let value = user_name.value.trim();
            if (!value)
                alert("Name Cannot be empty!");
            else
                alert("Hello, " + value + "!\nGreetings From GeeksforGeeks.");
        }
    </script>
</body>

</html>

Output:

12121212121321

Output

For deeper knowledge, you can visit What is the inline function in JavaScript?

Note:

Using inline JavaScript is generally considered bad practice and is not recommended for production. It can be useful for demonstration purposes, allowing the demonstrator to avoid dealing with two separate files. For better code organization and maintainability, it’s recommended to write JavaScript code in a separate .js file and link it using the src attribute in the <script> tag.



Next Article

Similar Reads