× back

Events in JavaScript

What we will do

HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can "react" on these events.
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:

Often, when events happen, you may want to do something.
HTML allows event handler attributes, with JavaScript code, to the added to HTML elements.

4 ways of writing events in JavaScript

  1. Using inline events alert();
  2. By Calling a function (We already seen and most common way of writing).
  3. Using Inline events (HTML onclick="" property and element.onclick)
  4. Using Event Listeners (addEventListener and IE's attachEvent)

Common JavaScript Events ⇗

                    
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        @import url("https://fonts.googleapis.com/css?family=Iconsolata:400, 700");

        body {
            font-family: 'Inconsolata', san-serif;
            background: #2a364f;
        }

        h1 {
            text-align: center;
            color: rgba(255, 255, 255, 0.8);
        }

        .credit {
            text-align: center;
            color: rgba(255, 255, 255, 0.4);
        }

        .content {
            padding-top: 45px;
            padding-bottom: 20px;
        }

        .button_container {
            width: 176px;
            margin: 0 auto;
            margin-top: 30px;
            padding-top: 40px;
        }

        .button_su {
            overflow: hidden;
            position: relative;
            display: inline-block;
            border-radius: 3px;
            margin-bottom: 30px;
            box-shadow: 0px 10px 8px -8px rgba(0, 0, 0, 0.6);
        }

        .su_button_circle {
            background-color: red;
            border-radius: 1000px;
            position: absolute;
            left: 0;
            top: 0;
            width: 0px;
            height: 0px;
            margin-left: 0px;
            margin-top: 0px;
            pointer-events: none;
        }

        .button_su_inner {
            display: inline-block;
            background: #F8B627;
            color: #000000;
            font-size: 16px;
            font-weight: normal;
            width: 132px;
            text-align: center;
            border-radius: 3px;
            transition: 400ms;
            text-decoration: none;
            padding: 22px;
            z-index: 100000;
        }

        .button_text_container {
            position: relative;
            z-index: 10000;
        }

        .explode-circle {
            animation: explode 0.5s forwards;
        }

        .displode-circle {
            animation: displode 0.5s forwards;
        }
    </style>
</head>

<body>
    <div class="content">
        <h1>Different Events Types in JavaScript</h1>
        <div class="button_container">
            <div class="button_su">
                <span class="su_button_circle"></span>
                <a href="" class="button_su_inner" onclick="alert('I am awesome, But No one use mer')">
                <span class="button_text_container">simple Inline alert()</span></a>
            </div>
            <div class="button_su">
                <span class="su_button_circle"></span>
                <a href="" class="button_su_inner" onclick="callingFunction()">
                    <span class="button_text_container">By Calling a Function</span>
                </a>
            </div>
            <div class="button_su">
                <span class="su_button_circle"></span>
                <a href="" class="button_su_inner" id="thirdWay">
                    <span class="button_text_container">Inline event</span>
                </a>
            </div>
            <div class="button_su">
                <span class="su_button_circle"></span>
                <a href="" class="button_su_inner" id="fourtWay">
                    <span class="button_text_container">Event Listeners</span>
                </a>
            </div>
        </div>
    </div>
    <script>
        const callingFunction = () => {
            alert('Most common way of writing functions');
        }

        // Third way of event call
        const thirdWay = document.getElementById('thirdWay');
        thirdWay.onclick = function () {
            alert('Most common way of writing functions again');
        }
        thirdWay.onclick = function () {
            console.log('Most common way of writing functions again'); // only this will occur
        }
        // If more event are added separately then only last one will occur, other will be overwritten.

        // Fourth way of event call
        const fourtWay = document.querySelector('#fourtWay');
        fourtWay.addEventListener('click', () => {
            alert('I love this way of way of writing functions');
        })
        fourtWay.addEventListener('click', () => {
            console.log('I love this way of way of writing functions'); // both will occur
        })
        </script>
</body>

</html>
                    
                

What is Event Object?

                        
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            font-family: 'Inconsolata', san-serif;
            background: #2a364f;
        }

        h1 {
            text-align: center;
            color: rgba(255, 255, 255, 0.8);
        }

        .credit {
            text-align: center;
            color: rgba(255, 255, 255, 0.4);
        }

        .content {
            padding-top: 45px;
            padding-bottom: 20px;
        }

        .button_container {
            width: 176px;
            margin: 0 auto;
            margin-top: 30px;
            padding-top: 40px;
        }

        .button_su {
            overflow: hidden;
            position: relative;
            display: inline-block;
            border-radius: 3px;
            margin-bottom: 30px;
            box-shadow: 0px 10px 8px -8px rgba(0, 0, 0, 0.6);
        }

        .su_button_circle {
            background-color: red;
            border-radius: 1000px;
            position: absolute;
            left: 0;
            top: 0;
            width: 0px;
            height: 0px;
            margin-left: 0px;
            margin-top: 0px;
            pointer-events: none;
        }

        .button_su_inner {
            display: inline-block;
            background: #F8B627;
            color: #000000;
            font-size: 16px;
            font-weight: normal;
            width: 132px;
            text-align: center;
            border-radius: 3px;
            transition: 400ms;
            text-decoration: none;
            padding: 22px;
            z-index: 100000;
        }

        .button_text_container {
            position: relative;
            z-index: 10000;
        }

        .explode-circle {
            animation: explode 0.5s forwards;
        }

        .displode-circle {
            animation: displode 0.5s forwards;
        }

        pre code {
            color: white;
        }
    </style>
</head>

<body>
    <div class="content">
        <h1>Let's See what is Event Object &smile;</h1>
        <div class="button_container">
            <div class="button_su">
                <span class="su_button_circle"></span>
                <a href="" class="button_su_inner" id="fourtWay">
                    <span class="button_text_container">Event Listeners</span></a>
            </div>
        </div>
        <pre>
            <code>
conole.log(event);
conole.log(event.target);
conole.log(event.type);
            </code>
        </pre>
    </div>
    <script>
        const fourtWay = document.getElementById('fourtWay');

        const checkEvent = () => {
            console.log(event);
            console.log(event.target);
            console.log(event.type);
        }

        fourtWay.addEventListener('click', checkEvent);

        // to get all the information about the event we use Event Object
    </script>
</body>

</html>
                        
                    

MouseEvent in JavaScript

                        
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mouse Event</title>
    <style>
        body {
            font-family: sans-serif;
            background-color: #2a364f;
            display: grid;
            place-items: center;
        }

        button {
            display: inline-block;
            background: #F8B627;
            text-align: center;
            border-radius: 3px;
            text-decoration: none;
            padding: 10px 22px;
            z-index: 100000;
            outline: none;
            border: none;
            color: white;
        }

        p {
            text-align: center;
            color: rgba(255, 255, 255, 1);
            padding: 10px;
            font-size: 28px;
        }

        h1 {
            color: aquamarine;
        }
    </style>
</head>

<body>
<p id="myP" onmousedown="mouseDown()" onmouseup="mouseUp()">Click the text! The mouseDown() function is triggered when the mouse button is pressed down over this paragraph, and sets the color of the text to red. The mouseUp() function is triggered when the mouse button is released, and set the color of the text to green.</p>
<script>
    function mouseDown() {
        document.getElementById("myP").style.color = "#F8B627";
    }
    function mouseUp() {
        document.getElementById("myP").style.color = "#fff";
    }
</script>
</body>

</html>
                        
                    
                        
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mouse Enter Event</title>
    <style>
        body {
            font-family: 'Inconsolata', san-serif;
            background: #2a364f;
            color: #fff;
        }

        .main-div {
            width: 500px;
            height: 500px;
            display: grid;
            margin: auto;
            place-items: center;
        }

        #box {
            width: 100px;
            height: 100px;
            background: yellow;
        }
    </style>
</head>

<body>
    <div class="main-div">
        <div id="box"></div>
    </div>
    <ul>
        <li>mouseenter event</li>
        <li>mouseleave event</li>
        <li>See console for logs</li>
    </ul>
    <script>
        const mEnter = document.getElementById('box');

        mEnter.addEventListener('mouseenter', () => {
            mEnter.style.backgroundColor = 'red';
            console.log('Mouse Enter Bro');
        });

        mEnter.addEventListener('mouseleave', () => {
            console.log('Mouse Leave Bro');
            mEnter.style.backgroundColor = 'skyblue';
        });
    </script>
</body>

</html>
                        
                    

KeyboardEvent in JavaScript

                        
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            font-family: sans-serif;
            background-color: #2a364f;
            display: grid;
            place-items: center;
            font-size: 18px;
            color: white;
        }

        input {
            margin-top: 30px;
            height: 25px;

        }

        .main-p {
            padding-top: 30px;
            font-size: 19px;
            text-align: center;
            color: rgb(242, 173, 83);
        }
    </style>
</head>

<body>
    <div class="main-div">
        <div class="main-p">A function is triggered when the user is pressing a key in the input field.
            <br>
            <br>
            onkeyPress event &darr;
            <br>
            <input type="text" onkeypress="keyPress()" name="" id="">
            <br>
            <p id="keys1"></p>
            <br>
            <p>onkeyup and onkeydown event &darr;</p>
            <input type="text" onkeydown="keyDown()" onkeyup="keyUp()" name="" id="">
            <br>
            <p id="keys2"></p>
        </div>
    </div>
    <script>
        const keyPress = () => {
            document.getElementById('keys1').innerHTML = `you press ${event.key} and it's code is ${event.code}`
        }

        // better to use 2nd and 3ed once

        const keyDown = () => {
            document.getElementById('keys2').innerHTML = 'key is Down';
            // when we click backslah (delete) to delete then it will run
        }

        const keyUp = () => {
            document.getElementById('keys2').innerHTML = 'key is up';
            // when we click backslash to delete then it will run
        }
    </script>
</body>

</html>
                        
                    

InputEvents in JavaScript

                        
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>onchange input event</title>
    <style>
        body {
            font-family: sans-serif;
            background-color: #2a364f;
            display: grid;
            place-items: center;
            color: rgb(246, 204, 204);
            font-size: 17px;
            padding-top: 100px;
        }
        label{
            padding: 10px;
            display: inline-block;
        }
        input{
            font-size: 17px;
        }
        select{
            font-size: 16px;
        }
        #result{
            font-size: 20px;
            color: beige;
        }
    </style>
</head>
<body>
     <div class="main-div">
        <div>
            <label for="">Your Name &rarr;
            <input type="text" name="" id="ice"></label>
            <br><label for="">Choose an ice cream flavor &rarr;
                <select name="iceCreams" id="iceCreams" onchange="selectElement()" >
                <option value="">Select One ...</option>
                <option value="chocolate">Chocolate</option>
                <option value="sardine">Sardine</option>
                <option value="vanilla">Vanilla</option>
            </select>
            </label>
            <br>
            <div id="result"></div>
        </div>
     </div>
     <script>
        // const selectElement = () => {
        //     const inputChange = document.getElementById('ice').value;
        //     const iceCreams = document.getElementById('iceCreams').value;
        //     const result = document.getElementById('result');
        //     result.innerHTML = `Mr ${inputChange} select ${iceCreams} ice-cream flavour`;
        // }
        // we can also do it using addEventListeners
        const iceCreams = document.getElementById('iceCreams');
        iceCreams.addEventListener('change', () => {
            const inputChange = document.getElementById('ice').value;
            const result = document.getElementById('result');
            result.innerHTML = `Mr ${inputChange} select ${iceCreams.value} ice-cream flavour`;
        });
     </script>
</body>
</html>
                        
                    

Interview Question

Difference between onclick and addEventListener?

                
// lets say we have a div 
const someDiv = document.getElementById('someDive');
someDiv.onclick = function () {
    alert('Most common way of writing functions again');
}
someDiv.onclick = function () {
    console.log('Most common way of writing functions again'); // only this will occur
}
                
            
                
// Now same situation with addEventListener
const someDiv = document.getElementById('someDive');
someDiv.addEventListener('click', () => {
    alert('This will happen');
});
someDiv.addEventListener('click', () => {
    console.log('Then this will happen');
});
                
            

Conclusion