What are JavaScript DOM Events?

JavascriptWeb DevelopmentFront End Technology

You can execute JavaScript on occurring of an event such as the user clicking the mouse, loading of an image, when the user clicks on an HTML element, submitting HTML form, etc. Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events, which can trigger JavaScript code.

Example

Let’s see an example, which allows you to call a function from an event handler to change the text

Live Demo

<!DOCTYPE html>
<html>
   <body>
      <p onclick="myEvent(this)">Click me</p>
      <script>
         function myEvent(id) {
            id.innerHTML = "Welcome!";
         }
      </script>
   </body>
</html>

Here we will see a few examples to understand a relation between Event and JavaScript.

 onclick Event Type

This is the most frequently used event type, which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type.

Example

Try the following example.

Live Demo

<html>
   <head>
      <script>
         <!--
            function sayHello()  {
               alert("Hello World")
            }
         //-->
      </script>
   </head>
   <body>
      <p>Click the following button and see result</p>
      <form>
         <input type="button" onclick="sayHello()" value="Say Hello" />
      </form>
   </body>
</html>

onmouseover and onmouseout

These two event types will help you create nice effects with images or even with text as well. The onmouseover event triggers when you bring your mouse over any element and the onmouseout triggers when you move your mouse out from that element. 

Example

Try the following example.

Live Demo

<html>
   <head>
      <script>
         <!--
            function over() {
               document.write ("Mouse Over");
            }
            function out() {
               document.write ("Mouse Out");
            }
         //-->
      </script>
   </head>
   <body>
      <p>Bring your mouse inside the division to see the result:</p>
      <div onmouseover="over()" onmouseout="out()">
         <h2> This is inside the division </h2>
      </div>
   </body>
</html>
raja
Published on 30-Jan-2018 15:00:39
Advertisements