Your First step into JS

Your First step into JS

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. Now the question comes out, how these events are performed? Before that you must know what HTML elements your web-page consists of and which element can receive events. These elements include button, text-box, selection-box, check-box, radio buttons, text area, images, links, forms and etc.

To make possible for an HTML elements to execute event, we have to connect an events 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.

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: To let something happen when your webpage will load, which event-handler we’ll use?


We will have to use onload event-handler inside tag e.g. onload=”function name” You can even execute a JavaScript code inside your HTML element with event-handlers. 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…

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

2. How to Connect EventHandler 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

<script lang="JavaScript">

    function onSubmit()
        {
         document.write("Thank you for you submission");
        }
    document.links[0].onclick = onSubmit;

</script>

In the above, we accessed document object links is an array of links and assign onSubmit() function its properties onclick. This work the same way as previous code .

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???…