Browser events and event listeners

Loading JS

JS can be loaded using script tag. script is loaded in 3 ways.
  • default - HTML parsing is blocked until script is loaded and executed
  • async - Script is loaded asynchronously but HTML parsing is blocked during execution phase.
  • defer - Script is loaded asynchronously and executed after the HTML parsing is completed. That's why it is called as defer

JS events

All html events inherit from Event object. This event object has below properties and methods.
  • createEvent - creates new event dynamically
  • target - element that triggered the event
  • currentTarget - element to which event listener is attached
  • preventDefault - prevents default action of event. e.g. when user clicks on link, new page opens. But if you use e.preventDefault() , new page will not open. Another example where we use preventDefault() is when user hits submit button in a form. By default, when the submit button is clicked, form is submitted to server. But we can prevent this by using e.preventDefault()
  • stopPropagation - stops the propagation of event to parent elements.
  • stopImmediatePropagation - stops the propagation of event to parent and also stops calling remaining handlers. e.g. We can have 2 event handlers on the same element. In this case, if first event handler calls e.stopImmediatePropagation(), other handler will not get called.
  • type - name of event
  • eventPhase - 0 - NONE, 1 - CAPTURING_PHASE, 2 - AT_TARGET, 3 - BUBBLING_PHASE
  • cancelable - Can this event's default action be prevented? e.g. resize event is not cancelable and does not bubble.
Events can be categorized as below.
  • event - abort, afterprint, beforeprint, online, offline
  • document events - DOMContentLoaded, onload, beforeunload, onunload, onresize, onscroll
  • Focus Event - onblur, onfocus, onfocusin, onfocusout - onfocusin, onfocusout events are not part of standard. onfocus and onblur events do not bubble to parent.
  • Element events - oninput, onchange, onselect, onsearch, oninvalid, ontoggle, onsubmit, onreset
  • mouse events - onclick, oncontextmenu, ondblclick, onmouseover, onmouseout, onmouseenter, onmouseleave, onmousemove, onmousedown, onmouseup, ondrag, ondragend, ondrop, ondragstart, ondragenter, ondragleave, ondragover, onwheel
  • keyboard events - keypress, onkeyup, onkeydown, oninput
  • clipboard event - oncopy, oncut, onpaste
  • Progress Event - onerror, onloadstart
  • Touch Event - ontouchcancel, ontouchend, ontouchmove, ontouchstart
  • Storage event
  • Page Transition events - pagehide, pageshow
  • Resource loading (e.g. js file) - onload, onerror

Examples

Below examples show how to use event handlers and event listeners.


//3 ways in which you can handle events

//<button onclick="alert('You clicked me');">Click here</button>
element.addEventListener('abort', (event) => { })
element.onabort = (event) => { }

//to remove even listner
element.removeEventListener("click", <functionName>);


/* oninput, onchange, onselect, onsearch, oninvalid,
ontoggle, onsubmit, onreset */

inputElement = document.getElementById("name")
inputElement.oninput = () => console.log("on input")
//onchange is similar to oninput except that it gets invoked only after element loses focus
inputElement.onchange = () => console.log("on change")


inputElement.onfocus = () => console.log("on focus")
inputElement.onblur = () => console.log("on blur")

//inputElement.onfocusin = () => console.log("on focus In")
 

window.onresize = function() {    
console.log("resized", window.innerWidth)
}

window.onscroll = function() {    
console.log("scrolled", window.scrollY)
}

window.onload = function(){
 console.log("loaded...")
 }
 
window.onbeforeunload = function(e) {    
console.log("before unloading")
//when we return non null value, confirmation dialog pops up asking user if 
//they want to leave the page.
return "Confirm before leaving"
}

window.onunload = function() {    
console.log("unloaded")
}

Form Validations

In this topic, you will learn how to validate the HTML forms using JavaScript. Below JavaScript example shows how we can prevent form from being submitted. The form element has an attribute called as "post" which is used to send the HTTP POST request to the server. To prevent the invalid data from being sent to the server, we need to validate the form. We are calling checkForm() function just before submitting the form. "checkForm()" function will check if all fields in HTML form have valid data. If validation is successful, it will return true and form will be submitted successfully. If validation is not successful, it will return false and form will not be submitted.

<script>
function checkForm() {
  var num = document.getElementById("number").value;
  if (num == "") {
  console.log("Number can not be empty");
  return false;
  }
  }
</script>

  <form name="simple" action="abc.php" onsubmit="return checkForm()" method="post">
  <input type="text" id="number">
  <input type="submit" value="Submit">
  </form>

We can add these validation attributes for HTML element.
  • required - When HTML element has this attribute, it means that it is mandatory to fill the data for this field.
  • disabled - This attribute means that field should be disabled.
  • max and min - These attributes can be used to set range of the value for specific field.
Consider below HTML snippet. Here we have added attributes min, max and required. It means that age field should be filled with number between 1 and 130.


<input id="age" type="number" min="1" max="130" required>

var ageObject = document.getElementById("age");
if (ageObject .checkValidity() == false) {
console.log("age validation was not successful." + ageObject.validationMessage);
}

Above JavaScript code shows how to validate this field. Note that we have used "checkValidity()" function and if it returns true, we are displaying validation message on the page.

Web development and Automation testing

solutions delivered!!