Introduction to JavaScript in HTML

Introduction to JavaScript in HTML

This tutorial introduces how to use JavaScript within HTML to create interactive web pages.

Open the Tutorial in Google Colab

Open in Google Colab

Embedding JavaScript in HTML

You can embed JavaScript directly into HTML using the <script> tag. The script can be placed in the <head> section, the <body> section, or both, depending on when you want the script to load.

from IPython.display import HTML
HTML('''



    Page Title
    



    

My First Heading

My first paragraph.

''')

Explanation for JavaScript Input Example

In the JavaScript Input Example, an input field and a button are provided. When the user enters text into the input field and clicks the 'Submit' button, the JavaScript function showInput() is called. This function retrieves the value from the input field, using document.getElementById('myInput').value, and displays it in the paragraph with id='inputResult' by setting its innerHTML property.

Explanation

In the above example, we have a simple HTML document with a JavaScript function defined within the <script> tag in the <head> section. This function, showMessage, changes the text of the paragraph with id='demo' when the button is clicked.

Explanation for JavaScript Calculation Example

In this example, two input fields accept numerical values. Upon clicking the 'Calculate Sum' button, the calculateSum() JavaScript function is triggered. This function fetches the values from both input fields, calculates their sum, and displays the result in the paragraph with id='sumResult'. The sum is calculated by converting the input values to integers using parseInt() and then adding them.

JavaScript Input Example

from IPython.display import HTML
HTML('''




JavaScript Input Example

Your input will appear here.

''')

JavaScript Calculation Example

from IPython.display import HTML
HTML('''




JavaScript Calculation Example

Enter numbers to calculate their sum:

Result will appear here.

''')

Basic Chat Message Input and Response Example

This example demonstrates a basic chat interface where the user can input a message. Upon submitting the message, a predefined response appears.

from IPython.display import HTML
HTML('''




Basic Chat Interface

You:

Bot: I'm here to help!

''')

Explanation for Basic Chat Message Input and Response

In the Basic Chat Interface example, an input field allows the user to type a message. When the 'Send' button is clicked, the sendMessage() JavaScript function is executed. This function captures the user's message from the input field and displays it under 'You:'. It then generates a predefined response under 'Bot:'. This simple interaction simulates a basic chat interface.