How to Use Events to Create Interactions in HTML Websites with JavaScript

How to Use Events to Create Interactions in HTML Websites with JavaScript

Have you ever imagined a web-page that doesn’t offer any interaction? it would felt like uninteresting and not useful at all. While browsing you actually perform some kind of actions by clicking, pointing to a button, refreshing a page, dragging/dropping and etc. etc. Interaction give you controls to make changes to a page, like filling up a form to sign up, choosing desired meal for an order, getting or sending information to a web-page, and much more. Let’s take a look on how these interactions are made possible in a web-page for HTML elements using JavaScript.

Events allow us to create interactions between elements and user in a web-page. These interactions include, clicking on a button, entering text, filling up a survey and switching picture in a gallery automatically. HTML elements from button, text-box, selection-box, check-box, radio buttons, text area, images, links, forms all are capable to receive event.

To make possible for an HTML elements to execute event, we have to connect an event to the element which will add interactivity to these controls. These connector are known as Event-handler which connects events to an HTML element. Some of the most common event handlers are onclick, onload, onclose, onunload, onchange, keypress, onabort, and onmouseover,etc.

EventHandler -> HTML Element -> Event Triggers on user/system interaction

1. How We Can Connect an Event-handler to an HTML Element?

The example below gives you an idea of connecting an onclickevent-handler to a button. Here greetMe() function is connected to an event-handler onclick to make sure the function must execute when someone clicks “Welcome” . The code onclick= "greetMe()" actually connects event-handler to your element. This is how we set specific things to happen at certain situations.

<html>
    <head>
      <script lang="JavaScript">

          function greetMe(){
              var myName = prompt("Please enter your Name");

              alert("Hello "+myName);
          }

      </script>
    </head>
  
    <body>

    //connecting an event-handler
      <button onclick="greetMe()">Welcome</button>

    </body>
</html>

Q: Which Eventhandler let us to execute an action on loading/refresh a webpage?

It’s onload event-handler inside tag e.g. onload=”function name” You can even execute a JavaScript code inside your HTML element with event-handlers.

  //JavaScript code execution
    <button onclick="document.write('Thank for submission!')">Submit</button>

Also, if you would like cancel an event from execution you return false from the function and use return keyword in the event-handler as well, but for that you need to have understanding how return works in event handlers. It will be discussed later on…

2. How to Connect Event-handler Using Object’s Properties:

There is one another way of connecting event-handlers to HTML elements using DOM object’s properties of your HTML element. It’s better to get an understanding of DOM which allows us to access all the HTML element apply event-handlers to add as much as interactivity possible to the web-page:

//Connecting event-handlers using HTML element’s DOM properties
<input  type="button"  id="submitBtn"  value="submit">

<script lang="JavaScript">

    function onSubmit()
        {
         document.write("Thank you for you submission");
        }
        
    document.getElementById("submitBtn").onclick = onSubmit; // simple element selection

</script>

In the above, we accessed document object’s element with submitBtn ID then calls event when someone clicks this elements with onclick event-handler.

Pro Tip: Today a more simple and secure way to Connect Events to HTML Elements is addEventListener() and it is recommended to use.


document.getElementById("submitBtn").addEventListener('click', onSubmit)

Use of return keyword in Event-handler:

<a href=http://www.seocliff.com onclick="return (confirm())">SEO Cliff</a>

event.preventDefault() method also cancels default behavior as well which is a part of return = false in event-handler.

3. Accessing Any HTML Element’s Reference from Function:

At some occasions, you may need to pass the HTML element‘s reference to provide direct access of the HTML object to the calling function. In HTML element, passing ‘this’ keyword as an argument to the calling function to its event-handler attribute, you pass the reference of this HTML element into the function. However, in the function definition, it is discouraged to use ‘this’ as parameter to avoid incorrect referencing of HTML objects. Developers usually write “that” or any other keyword except “this” to represent reference of current object in function definition.

Pro Tip: Today to speed up referencing process we use Jquery $(#selectorName).function This simply selects an element with id #selectorName

Fun Project: Creating a Quick Image Slider

Now It’s time doing a fun project using Event handlers and HTML elements. We will be creating an image slider that will load all the images in a folder automaticlly with some delay. First we will access to HTML elements DOM properties “src”. This will help us changing the Image over a period of time. Here is the code:

<script>

    var imageIndex = 0;

    var myImages = new Array("image1", "image2", "image3", "image4", "image5", "image6", 							 "image7", "image8", "image9", "image10", "image11", 									"image12", "image13");



function changeImg()
    {
     //recursively calling changeImg method to act as loop
	 if(imageIndex >=0 && imageIndex < myImages.length-1){
       		window.setTimeout("changeImg()",3000);
	        imageIndex++;
      document.images["img"].src = myImages[imageIndex] + ".jpg"; 
     
     } 
        
</script>
       
<body onload="changeImg()">
   	<!-- image object -->
    <img src="image1.jpg" style="height:300px; width:768px; background-size: contain; 		border-style:groove; border-color:aquamarine;object-fit:cover" name="img"> 
</body>       

Conclusion:

Now its time for you start playing with HTML element and add interactivity to them by use of events and write some cool function and let’s show how much it helped to add interactivity to your page. Next, we’ll going to show how to get the most of your DOM properties and create more cool functions to give to a feel of maximum control over most of your web-page controls to solve any problem.

Comments

Popular posts from this blog

My Mission

How HTML Forms Works with JavaScript and Optimize Your Productivity with JQuery

How to Use JavaScript to Do Calculation and Make Decisions in Your Website???…