Pitch your project

Random text






Blogs

0    
By admin Category Uncategorized, Posted March 16th, 2016
The JavaScript "Event" object

When you’re on the web, your browser registers different types of events. It’s the browser’s way of saying, “Hey, this just happened”. Your script can then respond to these events.

Events occurs when users click or tap on a link, hover or swipe over an element, type on the keyboard, resize the window or when the page they requested has loaded.

When an event occurs, or fires, it can be used to trigger a particular function in JavaScript.

Different event types

Here are some examples of events that occurs on a web page. Any of these events can be used to trigger a function in your JavaScript code.

  • UI Events – Occurs when a user interacts with the browser’s user interface (UI) rather than the web page .
    • load, unload, error, resize, scroll
  • Keyboard Events – Occurs when a user interacts with the keyboard.
    • keydown, keyup, keypress
  • Mouse Events – Occurs when a user interacts with a mouse,trackpad or touchscreen.
    • click, dbclick, mousedown, mouseup, mouseover
  • Focus Events – Occurs when an element (e.g., a link or form field) gains or loses focus.
    • focus, blur
  • Form Events – Occurs when a user interacts with a form element.
    • input, submit, copy
  • Mutation Events – Occur when the DOM structure has been changed by a script.
    • DOMSubtreeModified, DOMNodeRemoved, DOMNodeRemovedFromDocument.

Note: All these are the examples of events if you want to know more about specific type you should visit here to get more specific events.

3 Ways to bind an event to an element.

When the user interacts with HTML on a web page, there are three steps involved in getting it to trigger some JavaScript code. Together these steps are known as event handling.

  1. Select the element you want the script to respond to.
  2. Specify which event on the selected element will trigger the response.
  3. Call the code you want to run when the event occurs.

Event handlers handles the events that occurs at the moment when a user trigger an event.

There are 3 types of event handlers.
– HTML Event Handlers
– Traditional DOM Event Handlers
– DOM Level 2 Event Listeners

You shouldn’t use HTML Event Handlers because it’s bad practice since you want to separate your JavaScript code from your HTML.

//Do not use !!!!
    <button onclick="clickMe()">Click me</button>
//when the user click on the button the function clickMe() will be called.

What you want to use is this the “Traditional DOM event handlers” or the “Event listeners”.

Traditional DOM event handlers

With this method can you only attach one function to each event handler.

Here is the syntax to bind event handler to an element and indicate which function should be executed when that event fires.

element.onevent = functionName;
  • element is the DOM element to target.
  • onevent is the event that needs to occur
  • functionName is the function that will be called when the event occurs

Here is an example :

//select an DOM element with JavaScript by targeting the Id of the element
var element = document.getElementById("say-my-name");

//binding click event on the element and define the function;
element.onclick = function () {
    alert("Event Handlers");
}

HTML:

    <button id="say-my-name">Say My Name</button>

Event Listeners

Event listeners are a more recent approach to handling events. They can handle with more than 1 function at a time.

Here is the synxtax to bind an event to an element using Event listeners.

element.addEventListener('event', functionName[,Boolean]);
  • element is the DOM element to target.
  • addEventListener() is a method to add event listerner to the DOM elements.
  • ‘event’ is a string where you specify the event thats needs to occur.
  • functionName is the function that needs to be called when the event occurs.
  • Boolean is where you indicates something you called capture (Event Flow), usually set to false

Here is an example :

// get the DOM element.
var el = document.getElementById('whats-my-age');

//calls the the addEventListener() method, define the event.
//write the function to call when event occurs and set event flow to false.
el.addEventListener('click', function () {
    alertMyAge(20);
}, false);

//define alertMyAge function
function alertMyAge (age) {
    alert('My Age Is : ' + age);
}

Because you can’t have parentheses after the function names in event handlers or listeners, passing arguments requires a workaround. By wrapping the function in a anonymous function you can pass the parameters with no problems.

Note: IE version < 9 doesn’t support the addEventListener() method, instead use attachEvent() which did same job but availablein Internet Explorer. the syntax is :

element.attachEvent('on + event', functionName);

The Event Object

Now that you know what events, handlers and listeners are it’s time to talk about the Event Object.

When an event occurs, the event objects tells you information about the event, and the element it happened upon.

Every time an event fires, the event object contains helpful data about the event, such as: which element the event happened on, which key was pressed for ‘keypressed’ event.

The event object is passed to any function that is the event handler or listener.
if you need to pass arguments to a named function, the event object will be first passed to the anonymous function wrapper functions (this happens automatically).

Like other objects has properties and methods so does the Event object. It has so many I won’t able to mention all of them.

here are some that frequent used :
event.target : The target of the event(most specific the element interacted with).
event.type : Type of the event that was fired.
event.preventDefault() : Cancel default behaviour of the event.
event.stopPropagation() : Stops the event from bubbling or capturing further.
more details : Event

Event delegation

For event delegation is basically instead of adding allot of event listeners to a li’s for example you can add 1 event listener to the parent(<ul> or <ol></ol> in this case). Everytime you click on the <li> basically you are clicking on the whole <ul>.

Here’s an example:
HTML:

</ul><ul id="myList">
    <li id="li_1"></li>
    <li id="li_2"></li>
    <li id="li_3"></li>
    <li id="li_4"></li>
    <li id="li_5"></li>
    <li id="li_6"></li>
</ul>
//get the parent(<ul>)
var parent = document.getElementById('myList');

//add the event listener
//add define the event click
//pass the event object (e) to the function
parent.addEventListener('click',function (e) {
    //get the target (clicked element)
    var target = e.target || e.srcElement;

    //check if the target exist and if the target is an <li> element.
    if (target && target.nodeName === "LI") {
        //log the clicked item.
        console.log("List item ", target.id, " was clicked!");
    }
},false);

Hope you learned a lot about events and objects and thanks for reading!

Posted by Steven Wu

Leave a Reply

Your email address will not be published. Required fields are marked *