How does inline JavaScript work with HTML ?

You can include inline JavaScript directly within the HTML body using the <script> tag. Unlike linking an external JavaScript file with the src attribute, inline JavaScript is written directly within the <script> tags. This method allows for quick implementation of JavaScript functionalities within specific HTML elements or sections of a webpage.

Syntax:

<script>
    // JavaScript Code
</script>

Example: In this example, an HTML document features a form with a name input and a submit button. The inline JavaScript validates the input upon submission, displaying an alert. If the name is empty, it prompts the user; otherwise, it greets them along with a message from w3wiki.

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;"> 
        w3wiki 
    </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 id="btn-alert"
                        class="btn btn-success btn-lg float-right"
                        type="submit"> 
                    Submit 
                </button> 
            </div> 
        </form> 
    </div> 
    <script> 
        let user_name = document.getElementById("name"); 
        document.getElementById("btn-alert").addEventListener("click", function(){ 
            let value=user_name.value.trim(); 
            if(!value) 
                alert("Name Cannot be empty!"); 
            else 
                alert("Hello, " + value + "!\nGreetings From w3wiki."); 
        }); 
    </script> 
</body> 

</html> 

Output:

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.


Contact Us