HTML5: How to define a client-side script?
Solution:
HTML Code:
<!DOCTYPE html><!-- Define document type as HTML5 -->
<html><!-- Start of HTML document -->
<head><!-- Start of head section -->
<meta charset="utf-8"><!-- Define character encoding -->
<title>How to define a client-side script</title><!-- Title of the document -->
</head><!-- End of head section -->
<body><!-- Start of body section -->
<p id="output">Click Me</p><!-- Define a paragraph with an id for interaction -->
<script type="text/javascript"><!-- Start of JavaScript script -->
function w3r(){ // Define a JavaScript function named "w3r"
console.log('This is an example of script element'); // Output a message to the browser console
}
var el = document.getElementById('output'); // Get the element with the id "output"
el.addEventListener("click", w3r, false); // Add a click event listener to the element, calling the "w3r" function
</script><!-- End of JavaScript script -->
</body><!-- End of body section -->
</html><!-- End of HTML document -->
Explanation:
- This HTML code demonstrates how to define a client-side script using the <script> element.
- Inside the <script> element, JavaScript code is written to define a function named w3r() and add an event listener to an HTML element.
- The console.log() function is used to output a message to the browser console.
- The document.getElementById() method is used to retrieve an HTML element with the id "output".
- An event listener is added to the element using addEventListener(), which triggers the w3r() function when the element is clicked.
- This script demonstrates a simple example of client-side scripting, where JavaScript code is used to interact with HTML elements and handle events.
Live Demo:
See the Pen script-answer by w3resource (@w3resource) on CodePen.
See the solution in the browser
Supported browser
Yes | Yes | Yes | Yes | Yes |
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/html-css-exercise/basic/script-answer.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics