Most Important Events in JavaScript

ADMEC Multimedia > Web Design > Most Important Events in JavaScript

In this article I will try to explain the various events which are used and their purpose in Javascript. JavaScript’s interaction with HTML is handled through events that occur when the user or the browser manipulates a page. Without events and handlers we would never be able to create client-side web applications.

Events allow JavaScript to detect when a certain action has been performed by the user, e.g. hovering over an element, clicking a link, scrolling the page, resizing the window, when the user clicks a button, that click is an event. Other examples include events like pressing any key, closing a window, resizing a window, when the mouse moves over an element etc.

Events are a part of the Document Object Model (DOM) and every HTML element contains a set of events which can trigger JavaScript Code. JavaScript code can register a handler function which is triggered when a particular event occurs. Most browsers pass a single object to the function which contains information about the event, i.e. what keys were pressed, the position of the cursor, etc.

Categories of various JavaScript HTML DOM Events

1. Form Events

Keyboard Events explains what happens when user interaction happens with the form elements. Some of the form events are as follows:-

a. onfocus

The focus event triggers when a visitor focuses on an element. Onfocus is most often used with <input>, <select>, and <a>.

Example:

<!DOCTYPE html>
<html>
<body>
    First name: <input type="text" id="fname" onfocus="myFunction(this.id)"><br>
    Last name: <input type="text" id="lname" onfocus="myFunction(this.id)">

<script>
    function myFunction(x) {
         document.getElementById(x).style.background = "yellow";
    }
</script>
</body>
</html>

In the above example, we are trying to change the background color of the input box as soon as the field gets focused.

b. onchange

The onchange event occurs when the value of an element has been changed. It will work for radio buttons and checkboxes.

Example:

<!DOCTYPE html>
<html>
<body>
     <p>Select a color from the list.</p>
     <select id="mySelect" onchange="main()">
          <option value="Red">Red
          <option value="Green">Green
          <option value="Blue">Blue
     </select>
     <p id="demo"></p>
     <script>
        function main() {
            var x = document.getElementById("mySelect").value;
            document.getElementById("demo").innerHTML = "You selected: " + x;
        }
     </script>
</body>
</html>

In the above example, when you select a color, a function is triggered which will display the message in the browser “You select Red” if Red has been selected.

c. onselect

The onselect event occurs after some text has been selected in an element.It is used on <input type=”text”> or <textarea> elements.

Example:

<!DOCTYPE html>
<html>
<body>
     Select some of the text: <input type="text" value="Hello world!" onselect="main()">
     <script>
          function main() {
              alert("Text has been selected”);
          }
      </script>
</body>
</html>

In the above code, whenever some text is selected inside the input box, it will pop up an alert message “Text has been selected”.

d. onsubmit

The onsubmit event occurs when a form is submitted. It will work only for buttons.

Example:

<!DOCTYPE html>
<html>
<body>
     <form action="form.asp" onsubmit="main()">
          Enter name: <input type="text" name="fname">
          <input type="submit" value="Submit">
     </form>
     <script>
          function main() {
              alert("The form was submitted");
          }
     </script>
</body>
</html>

In the above example, we want that an alert message should be popped up in case of clicking on submit button.

e. onreset

The onreset event occurs when a form is reset. When a form is reset, all controls within the form are set to their initial values.

Example:

<!DOCTYPE html>
<html>
<body>
    <form onreset="myFunction()">
         Enter name: <input type="text">
         <input type="reset">
    </form>
    <script>
        function myFunction() {
            alert("The form was reset");
        }
    </script>
</body>
</html>

This example demonstrates how to use the onreset event for a form object. Reset the form by clicking the Reset button. When the button is pressed the form is reset, first will pop up an alert message and after that whatever has been entered in the input box will be reset to the default state i.e. it was blank.

2. Keyboard Events

Keyboard Events explains what happens when user interaction happens with the keyboard. Some of the keyboard events are as follows:-

a. onkeypress

In order to understand the difference between keydown and keypress, it is useful to understand the difference between a “character” and a “key”. A “key” is a physical button on the computer’s keyboard while a “character” is a symbol typed by pressing a button. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character is being typed.

b. onkeypress

The onkeypress event occurs when the character is being typed from the keyboard. It will not work for Alt, Ctrl, ESC, uparrow, downarrow, shift keys.

Example:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
     <input type="text" onkeypress="main()">
     <script>
         function main() {
             alert("You pressed a key ");
         }
     </script>
</body>
</html>

The above example shows that after pressing a character from the keyboard, an alert message is popped up and will reflect the key in the input box.

c. onkeydown

The onkeydown event occurs when any key from the key is pressed. This will work for both characters and keys when pressed from the keyboard.

Example:

<!DOCTYPE html>
<html>
<body>
    <input type="text" onkeydown="main()">

<script>
    function main() {
        alert("You pressed a key inside the input field");
    }
</script>
</body>
</html>

d. onkeyup

The onkeyup event occurs when any key from the key is released. This will work for both characters and keys when released from the keyboard.

Example:

<!DOCTYPE html>
<html>
<body>
    <input type="text" id="demo" onkeydown="keydownFunc()" onkeyup="keyupFunc()">
<script>
    function keydownFunc() {
         document.getElementById("demo").style.backgroundColor = "red";
    }

    function keyupFunc() {
        document.getElementById("demo").style.backgroundColor = "green";
    }
</script>
</body>
</html>

The above example shows that after pressing a character from the keyboard, textbox color will be red and on release it will become green.

3. Mouse Events

The MouseEvent interface represents events that occur due to the user interacting with a pointing device (such as a mouse). Some of the mouse events are as follows:-

a. onclick

The onclick event will occur when we will click on an element.

b. ondblclick

The ondblclick event will occur when we double-click on an element.

c. onmouseover

The onmouseover event occurs when the mouse pointer is moved onto an element, or onto one of its children.

d. onmouseout

The onmouseout event occurs when the mouse pointer is moved out of an element, or out of one of its children.

Example:-

<!DOCTYPE html>
<html>
<head>
     <title>dom manipulation</title>
     <style type="text/css">
         li{list-style-type: none; width: 300px; padding: 20px; background-color: #6e6e6e; border:1px solid #3e3e3e;}
     </style>
</head>
<body>
     <script type="text/javascript">
        var gBdy = document.getElementsByTagName('body')[0];
        var cUl = document.createElement('ul');
        gBdy.appendChild(cUl);
        for (var i = 0; i < 10; i++) {
            var cLi = document.createElement('li');
            var cTxt = document.createTextNode('List '+i);        
            cLi.appendChild(cTxt);
            cUl.appendChild(cLi);
            cLi.ondblclick = function (){
                cUl.removeChild(this);
            }
            cLi.onclick = function (){
                this.style.fontSize = "24px";
            }
            cLi.onmouseover = function (){
                this.style.backgroundColor = "yellow";
            }
            cLi.onmouseout = function (){
                this.style.backgroundColor = "beige";
            }
        };
    </script>
</body>
</html>

In the above DOM manipulation example we will be using all the four Mouse events studied above. Onmouseover the color will be yellow and onmouseout the color will change to beige.

onclick event will increase the font size and ondblclick will remove the list item using remove child method mentioned above. We can have different actions for an even depending upon our requirements.

4. Object Events

a. onload Event

The onload event occurs when an object has been loaded. Like we want that when the page is loaded it should execute the code. It should pop up an alert message.

<!DOCTYPE html>
<html>
<body onload="main()">
<script>
        function main() {
            alert("Page is loaded");
        }
</script>
</body>
</html>

b. onscroll Event

The onscroll event occurs when an element’s scrollbar is being scrolled. Try the below example to see what happens:-

<!DOCTYPE html>
<html>
<head>
<style>
div {
    border: 1px solid black;
    width: 200px;
    height: 100px;
    overflow: scroll;
}
</style>
</head>
<body>
     <p>Do scrolling to check</p>
     <div onscroll="myFunction()">JavaScript is a client side scripting language which is when linked with HTML makes our web pages interactive. By client side scripting language we mean that script will run at the client side in a browser. We cannot create dynamic web pages without JavaScript. It adds behaviour to the web pages.
<br><br>
Most of the validations are done with the help of it. JavaScript code is written within the <script></script> tags.This tag will tell the browser to interpret text written between these tags as a script.</div>

     <p>Scrolled <span id="demo">0</span> times.</p>
<script>
     var x = 0;
     function myFunction() {
          document.getElementById("demo").innerHTML = x += 1;
     }
</script>
</body>
</html>

c. onresize Event

The onresize event occurs when the browser window has been resized. In the below example when we minimize or maximize our browser window, it will change the size and width of the browser window.

<!DOCTYPE html>
<html>
<body onresize="main()">
     <p>Try to resize the browser window </p>
     <p id="demo"></p>
<script>
     function main() {
         var w = window.outerWidth;
         var h = window.outerHeight;
         var txt = "Window size: width=" + w + ", height=" + h;
         document.getElementById("demo").innerHTML = txt;
     }
</script>
</body>
</html>

Whatever I have covered in this article regarding events, I hope you all will have gained a good understanding of how events work. As per my understanding it’s very important to practice all the above mentioned examples of events.

Once you have learned to master the examples given above and start making small assignments on your own, there’s no end to the possibilities you can achieve with JavaScript and event handling!


View Full Presentation on slideshare:

JavaScript Basics

JavaScript Basics from ADMEC Multimedia Institute

Leave a Reply

Related Posts

Copy link
Powered by Social Snap