How to Insert JavaScript Using Event Handler (Inline JavaScript)

How to Insert JavaScript Using Event Handler (Inline JavaScript)

The third way to run JavaScript is to call it using an Event Handler from within an HTML tag.

 

The concept of Event Handler will be studied specifically in a separate tutorial, but in simple terms, event handlers are javascript code calls when 'something' happens in an HTML tag.

 

Something here means when an element in HTML is clicked, right-clicked, mouse-over, and so on. Event handlers in JavaScript are written with the addition of the word on. So if a button is clicked, it is called onclick, if the mouse is above the element it is called onmouseover, and so on.

 

For example, when a button is clicked, we can display an alert(“Hello World!!”). Here is an example of the program code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8" />
<head>
<title>Belajar JavaScript di Duniailkom</title>
</head>
 
<body>
<h1>Belajar JavaScript</h1>
<p>Saya sedang belajar JavaScript di duniailkom.com</p>
<p>Belajar Web Programming di Duniailkom.</p>
 
<button onclick="alert('Hello World!!')">Klik Saya
 
</body>
</html>


 


Pay attention to the 13th line of the code example above, namely the writing of the <button> tag. Inside the tag, I added onclick="alert('Hello World!!')", this is the JavaScript code that is inputted via the event handler method.

 

This way of inputting JavaScript code using an Event Handler, although practical, is not recommended, because we mix JavaScript with HTML. And if the JavaScript code is a bit long, it will be difficult to separate the HTML code from the JavaScript.

The results obtained using the event handler above, should be moved into the <script> tag.

In Javascript programming, there is a term called Unobtrusive JavaScript. Unobtrusive JavaScript is a programming philosophy or paradigm which argues that content (HTML) should be as separate from behavior (JavaScript) as possible to make it easier to maintain and more flexible. This concept can be read at http://en.wikipedia.org/wiki/Unobtrusive_JavaScript.


For discussion about : 
I will explain in the next article separately

 

 

Post a Comment

Previous Post Next Post